mirror of
https://github.com/Buriburizaem0n/admin-frontend-domain.git
synced 2026-02-04 12:40:08 +00:00
Dashboard Redesign (#48)
* feat: add user_template setting * style: header * style: page padding * style: header * feat: header now time * style: login page * feat: nav indicator * style: button inset shadow * style: footer text size * feat: header show login_ip * fix: error toast * fix: frontend_templates setting * fix: lint * feat: pr auto format * chore: auto-fix linting and formatting issues --------- Co-authored-by: hamster1963 <hamster1963@users.noreply.github.com>
This commit is contained in:
@@ -1,14 +1,15 @@
|
||||
import { ModelAlertRuleForm } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createAlertRule = async (data: ModelAlertRuleForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/alert-rule', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/alert-rule", data)
|
||||
}
|
||||
|
||||
export const updateAlertRule = async (id: number, data: ModelAlertRuleForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/alert-rule/${id}`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/alert-rule/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteAlertRules = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/alert-rule', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/alert-rule", id)
|
||||
}
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
interface CommonResponse<T> {
|
||||
success: boolean;
|
||||
error: string;
|
||||
data: T;
|
||||
success: boolean
|
||||
error: string
|
||||
data: T
|
||||
}
|
||||
|
||||
function buildUrl(path: string, data?: any): string {
|
||||
if (!data)
|
||||
return path
|
||||
const url = new URL(path);
|
||||
if (!data) return path
|
||||
const url = new URL(path)
|
||||
for (const key in data) {
|
||||
url.searchParams.append(key, data[key]);
|
||||
url.searchParams.append(key, data[key])
|
||||
}
|
||||
return url.toString();
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
export enum FetcherMethod {
|
||||
@@ -22,14 +21,14 @@ export enum FetcherMethod {
|
||||
DELETE = "DELETE",
|
||||
}
|
||||
|
||||
let lastestRefreshTokenAt = 0;
|
||||
let lastestRefreshTokenAt = 0
|
||||
|
||||
export async function fetcher<T>(method: FetcherMethod, path: string, data?: any): Promise<T> {
|
||||
let response;
|
||||
let response
|
||||
if (method === FetcherMethod.GET || method === FetcherMethod.DELETE) {
|
||||
response = await fetch(buildUrl(path, data), {
|
||||
method: "GET",
|
||||
});
|
||||
})
|
||||
} else {
|
||||
response = await fetch(path, {
|
||||
method: method,
|
||||
@@ -37,25 +36,28 @@ export async function fetcher<T>(method: FetcherMethod, path: string, data?: any
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: data ? JSON.stringify(data) : null,
|
||||
});
|
||||
})
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
throw new Error(response.statusText)
|
||||
}
|
||||
const responseData: CommonResponse<T> = await response.json();
|
||||
const responseData: CommonResponse<T> = await response.json()
|
||||
if (!responseData.success) {
|
||||
throw new Error(responseData.error);
|
||||
throw new Error(responseData.error)
|
||||
}
|
||||
|
||||
// auto refresh token
|
||||
if (document.cookie && (!lastestRefreshTokenAt || Date.now() - lastestRefreshTokenAt > 1000 * 60 * 60)) {
|
||||
lastestRefreshTokenAt = Date.now();
|
||||
if (
|
||||
document.cookie &&
|
||||
(!lastestRefreshTokenAt || Date.now() - lastestRefreshTokenAt > 1000 * 60 * 60)
|
||||
) {
|
||||
lastestRefreshTokenAt = Date.now()
|
||||
fetch("/api/v1/refresh-token")
|
||||
}
|
||||
|
||||
return responseData.data;
|
||||
return responseData.data
|
||||
}
|
||||
|
||||
export async function swrFetcher<T>(input: string | URL | globalThis.Request, init?: RequestInit) {
|
||||
return fetcher<T>(init?.method as FetcherMethod, input.toString(), init?.body);
|
||||
return fetcher<T>(init?.method as FetcherMethod, input.toString(), init?.body)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { ModelCronForm } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createCron = async (data: ModelCronForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/cron', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/cron", data)
|
||||
}
|
||||
|
||||
export const updateCron = async (id: number, data: ModelCronForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/cron/${id}`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/cron/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteCron = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/cron', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/cron", id)
|
||||
}
|
||||
|
||||
export const runCron = async (id: number): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.GET, `/api/v1/cron/${id}/manual`, null);
|
||||
return fetcher<void>(FetcherMethod.GET, `/api/v1/cron/${id}/manual`, null)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { ModelDDNSForm } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createDDNSProfile = async (data: ModelDDNSForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/ddns', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/ddns", data)
|
||||
}
|
||||
|
||||
export const updateDDNSProfile = async (id: number, data: ModelDDNSForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/ddns/${id}`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/ddns/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteDDNSProfiles = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/ddns', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/ddns", id)
|
||||
}
|
||||
|
||||
export const getDDNSProviders = async (): Promise<string[]> => {
|
||||
return fetcher<string[]>(FetcherMethod.GET, '/api/v1/ddns/providers', null);
|
||||
return fetcher<string[]>(FetcherMethod.GET, "/api/v1/ddns/providers", null)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ModelCreateFMResponse } from "@/types";
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
import { ModelCreateFMResponse } from "@/types"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createFM = async (id: string): Promise<ModelCreateFMResponse> => {
|
||||
return fetcher<ModelCreateFMResponse>(FetcherMethod.GET, `/api/v1/file?id=${id}`, null);
|
||||
return fetcher<ModelCreateFMResponse>(FetcherMethod.GET, `/api/v1/file?id=${id}`, null)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { ModelNATForm } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createNAT = async (data: ModelNATForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/nat', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/nat", data)
|
||||
}
|
||||
|
||||
export const updateNAT = async (id: number, data: ModelNATForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/nat/${id}`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/nat/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteNAT = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/nat', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/nat", id)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import { ModelNotificationGroupForm, ModelNotificationGroupResponseItem } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
export const createNotificationGroup = async (data: ModelNotificationGroupForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/notification-group', data);
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createNotificationGroup = async (
|
||||
data: ModelNotificationGroupForm,
|
||||
): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/notification-group", data)
|
||||
}
|
||||
|
||||
export const updateNotificationGroup = async (id: number, data: ModelNotificationGroupForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/notification-group/${id}`, data);
|
||||
export const updateNotificationGroup = async (
|
||||
id: number,
|
||||
data: ModelNotificationGroupForm,
|
||||
): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/notification-group/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteNotificationGroups = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/notification-group`, id);
|
||||
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/notification-group`, id)
|
||||
}
|
||||
|
||||
export const getNotificationGroups = async (): Promise<ModelNotificationGroupResponseItem[]> => {
|
||||
return fetcher<ModelNotificationGroupResponseItem[]>(FetcherMethod.GET, '/api/v1/notification-group', null);
|
||||
return fetcher<ModelNotificationGroupResponseItem[]>(
|
||||
FetcherMethod.GET,
|
||||
"/api/v1/notification-group",
|
||||
null,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import { ModelNotificationForm, ModelNotification } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
import { ModelNotification, ModelNotificationForm } from "@/types"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createNotification = async (data: ModelNotificationForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/notification', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/notification", data)
|
||||
}
|
||||
|
||||
export const updateNotification = async (id: number, data: ModelNotificationForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/notification/${id}`, data);
|
||||
export const updateNotification = async (
|
||||
id: number,
|
||||
data: ModelNotificationForm,
|
||||
): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/notification/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteNotification = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/notification', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/notification", id)
|
||||
}
|
||||
|
||||
export const getNotification = async (): Promise<ModelNotification[]> => {
|
||||
return fetcher<ModelNotification[]>(FetcherMethod.GET, '/api/v1/notification', null);
|
||||
return fetcher<ModelNotification[]>(FetcherMethod.GET, "/api/v1/notification", null)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { ModelServerGroupForm, ModelServerGroupResponseItem } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createServerGroup = async (data: ModelServerGroupForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/server-group', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/server-group", data)
|
||||
}
|
||||
|
||||
export const updateServerGroup = async (id: number, data: ModelServerGroupForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/server-group/${id}`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/server-group/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteServerGroups = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/server-group`, id);
|
||||
return fetcher<void>(FetcherMethod.POST, `/api/v1/batch-delete/server-group`, id)
|
||||
}
|
||||
|
||||
export const getServerGroups = async (): Promise<ModelServerGroupResponseItem[]> => {
|
||||
return fetcher<ModelServerGroupResponseItem[]>(FetcherMethod.GET, '/api/v1/server-group', null);
|
||||
return fetcher<ModelServerGroupResponseItem[]>(FetcherMethod.GET, "/api/v1/server-group", null)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { ModelServer, ModelServerForm, ModelForceUpdateResponse } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
import { ModelForceUpdateResponse, ModelServer, ModelServerForm } from "@/types"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const updateServer = async (id: number, data: ModelServerForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/server/${id}`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/server/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteServer = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/server', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/server", id)
|
||||
}
|
||||
|
||||
export const forceUpdateServer = async (id: number[]): Promise<ModelForceUpdateResponse> => {
|
||||
return fetcher<ModelForceUpdateResponse>(FetcherMethod.POST, '/api/v1/force-update/server', id);
|
||||
return fetcher<ModelForceUpdateResponse>(FetcherMethod.POST, "/api/v1/force-update/server", id)
|
||||
}
|
||||
|
||||
export const getServers = async (): Promise<ModelServer[]> => {
|
||||
return fetcher<ModelServer[]>(FetcherMethod.GET, '/api/v1/server', null);
|
||||
return fetcher<ModelServer[]>(FetcherMethod.GET, "/api/v1/server", null)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { ModelServiceForm } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createService = async (data: ModelServiceForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/service', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/service", data)
|
||||
}
|
||||
|
||||
export const updateService = async (id: number, data: ModelServiceForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/service/${id}`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/service/${id}`, data)
|
||||
}
|
||||
|
||||
export const deleteService = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/service', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/service", id)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { ModelSettingForm, ModelSettingResponse } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const updateSettings = async (data: ModelSettingForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/setting`, data);
|
||||
return fetcher<void>(FetcherMethod.PATCH, `/api/v1/setting`, data)
|
||||
}
|
||||
|
||||
export const getSettings = async (): Promise<ModelSettingResponse> => {
|
||||
return fetcher<ModelSettingResponse>(FetcherMethod.GET, '/api/v1/setting', null);
|
||||
return fetcher<ModelSettingResponse>(FetcherMethod.GET, "/api/v1/setting", null)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ModelCreateTerminalResponse } from "@/types";
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
import { ModelCreateTerminalResponse } from "@/types"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const createTerminal = async (id: number): Promise<ModelCreateTerminalResponse> => {
|
||||
return fetcher<ModelCreateTerminalResponse>(FetcherMethod.POST, '/api/v1/terminal', {
|
||||
return fetcher<ModelCreateTerminalResponse>(FetcherMethod.POST, "/api/v1/terminal", {
|
||||
server_id: id,
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import { ModelProfile, ModelUserForm, ModelProfileForm } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
import { ModelProfile, ModelProfileForm, ModelUserForm } from "@/types"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const getProfile = async (): Promise<ModelProfile> => {
|
||||
return fetcher<ModelProfile>(FetcherMethod.GET, '/api/v1/profile', null);
|
||||
return fetcher<ModelProfile>(FetcherMethod.GET, "/api/v1/profile", null)
|
||||
}
|
||||
|
||||
export const login = async (username: string, password: string): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/login', { username, password });
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/login", { username, password })
|
||||
}
|
||||
|
||||
export const createUser = async (data: ModelUserForm): Promise<number> => {
|
||||
return fetcher<number>(FetcherMethod.POST, '/api/v1/user', data);
|
||||
return fetcher<number>(FetcherMethod.POST, "/api/v1/user", data)
|
||||
}
|
||||
|
||||
export const deleteUser = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/user', id);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/user", id)
|
||||
}
|
||||
|
||||
export const updateProfile = async (data: ModelProfileForm): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/profile', data);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/profile", data)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { ModelWAFApiMock } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
import { FetcherMethod, fetcher } from "./api"
|
||||
|
||||
export const deleteWAF = async (ip: string[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/waf', ip);
|
||||
return fetcher<void>(FetcherMethod.POST, "/api/v1/batch-delete/waf", ip)
|
||||
}
|
||||
|
||||
export const getWAFList = async (): Promise<ModelWAFApiMock[]> => {
|
||||
return fetcher<ModelWAFApiMock[]>(FetcherMethod.GET, '/api/v1/waf', null);
|
||||
return fetcher<ModelWAFApiMock[]>(FetcherMethod.GET, "/api/v1/waf", null)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { IconButton } from "@/components/xui/icon-button";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -10,22 +9,33 @@ import {
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { KeyedMutator } from "swr";
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import { KeyedMutator } from "swr"
|
||||
|
||||
interface ButtonGroupProps<E, U> {
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
delete: { fn: (id: E[]) => Promise<void>, id: E, mutate: KeyedMutator<U> };
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
delete: { fn: (id: E[]) => Promise<void>; id: E; mutate: KeyedMutator<U> }
|
||||
}
|
||||
|
||||
export function ActionButtonGroup<E, U>({ className, children, delete: { fn, id, mutate } }: ButtonGroupProps<E, U>) {
|
||||
const { t } = useTranslation();
|
||||
export function ActionButtonGroup<E, U>({
|
||||
className,
|
||||
children,
|
||||
delete: { fn, id, mutate },
|
||||
}: ButtonGroupProps<E, U>) {
|
||||
const { t } = useTranslation()
|
||||
const handleDelete = async () => {
|
||||
await fn([id]);
|
||||
await mutate();
|
||||
try {
|
||||
await fn([id])
|
||||
} catch (error: any) {
|
||||
toast(t("Error"), {
|
||||
description: error.message,
|
||||
})
|
||||
}
|
||||
await mutate()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -44,7 +54,12 @@ export function ActionButtonGroup<E, U>({ className, children, delete: { fn, id,
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("Close")}</AlertDialogCancel>
|
||||
<AlertDialogAction className={buttonVariants({ variant: "destructive" })} onClick={handleDelete}>{t("Confirm")}</AlertDialogAction>
|
||||
<AlertDialogAction
|
||||
className={buttonVariants({ variant: "destructive" })}
|
||||
onClick={handleDelete}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createAlertRule, updateAlertRule } from "@/api/alert-rule"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
@@ -9,14 +11,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -25,29 +19,35 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelAlertRule } from "@/types"
|
||||
import { createAlertRule, updateAlertRule } from "@/api/alert-rule"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { triggerModes } from "@/types"
|
||||
import { Textarea } from "./ui/textarea"
|
||||
import { useNotification } from "@/hooks/useNotfication"
|
||||
import { Combobox } from "./ui/combobox"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ModelAlertRule } from "@/types"
|
||||
import { triggerModes } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Combobox } from "./ui/combobox"
|
||||
import { Textarea } from "./ui/textarea"
|
||||
|
||||
interface AlertRuleCardProps {
|
||||
data?: ModelAlertRule;
|
||||
mutate: KeyedMutator<ModelAlertRule[]>;
|
||||
data?: ModelAlertRule
|
||||
mutate: KeyedMutator<ModelAlertRule[]>
|
||||
}
|
||||
|
||||
const ruleSchema = z.object({
|
||||
@@ -56,87 +56,91 @@ const ruleSchema = z.object({
|
||||
max: asOptionalField(z.number()),
|
||||
cycle_start: asOptionalField(z.string()),
|
||||
cycle_interval: asOptionalField(z.number()),
|
||||
cycle_unit: asOptionalField(z.enum(['hour', 'day', 'week', 'month', 'year'])),
|
||||
cycle_unit: asOptionalField(z.enum(["hour", "day", "week", "month", "year"])),
|
||||
duration: asOptionalField(z.number()),
|
||||
cover: z.number().int().min(0),
|
||||
ignore: asOptionalField(z.record(z.boolean())),
|
||||
next_transfer_at: asOptionalField(z.record(z.string())),
|
||||
last_cycle_status: asOptionalField((z.boolean())),
|
||||
});
|
||||
last_cycle_status: asOptionalField(z.boolean()),
|
||||
})
|
||||
|
||||
const alertRuleFormSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
rules_raw: z.string().refine((val) => {
|
||||
try {
|
||||
JSON.parse(val);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}, {
|
||||
message: 'Invalid JSON string',
|
||||
}),
|
||||
rules_raw: z.string().refine(
|
||||
(val) => {
|
||||
try {
|
||||
JSON.parse(val)
|
||||
return true
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
},
|
||||
{
|
||||
message: "Invalid JSON string",
|
||||
},
|
||||
),
|
||||
rules: z.array(ruleSchema),
|
||||
fail_trigger_tasks: z.array(z.number()),
|
||||
recover_trigger_tasks: z.array(z.number()),
|
||||
notification_group_id: z.coerce.number().int(),
|
||||
trigger_mode: z.coerce.number().int().min(0),
|
||||
enable: asOptionalField(z.boolean()),
|
||||
});
|
||||
})
|
||||
|
||||
export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof alertRuleFormSchema>>({
|
||||
resolver: zodResolver(alertRuleFormSchema),
|
||||
defaultValues: data ? {
|
||||
...data,
|
||||
rules_raw: JSON.stringify(data.rules),
|
||||
} : {
|
||||
name: "",
|
||||
rules_raw: "",
|
||||
rules: [],
|
||||
fail_trigger_tasks: [],
|
||||
recover_trigger_tasks: [],
|
||||
notification_group_id: 0,
|
||||
trigger_mode: 0,
|
||||
},
|
||||
defaultValues: data
|
||||
? {
|
||||
...data,
|
||||
rules_raw: JSON.stringify(data.rules),
|
||||
}
|
||||
: {
|
||||
name: "",
|
||||
rules_raw: "",
|
||||
rules: [],
|
||||
fail_trigger_tasks: [],
|
||||
recover_trigger_tasks: [],
|
||||
notification_group_id: 0,
|
||||
trigger_mode: 0,
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof alertRuleFormSchema>) => {
|
||||
values.rules = JSON.parse(values.rules_raw);
|
||||
const { rules_raw, ...requiredFields } = values;
|
||||
data?.id ? await updateAlertRule(data.id, requiredFields) : await createAlertRule(requiredFields);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
values.rules = JSON.parse(values.rules_raw)
|
||||
const { rules_raw, ...requiredFields } = values
|
||||
data?.id
|
||||
? await updateAlertRule(data.id, requiredFields)
|
||||
: await createAlertRule(requiredFields)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
const { notifierGroup } = useNotification();
|
||||
const ngroupList = notifierGroup?.map(ng => ({
|
||||
const { notifierGroup } = useNotification()
|
||||
const ngroupList = notifierGroup?.map((ng) => ({
|
||||
value: `${ng.group.id}`,
|
||||
label: ng.group.name,
|
||||
})) || [{ value: "", label: "" }];
|
||||
})) || [{ value: "", label: "" }]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data ? t("EditAlertRule") : t("CreateAlertRule")}</DialogTitle>
|
||||
<DialogTitle>
|
||||
{data ? t("EditAlertRule") : t("CreateAlertRule")}
|
||||
</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -148,9 +152,7 @@ export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) =>
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
/>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -163,10 +165,7 @@ export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) =>
|
||||
<FormItem>
|
||||
<FormLabel>{t("Rules")}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className="resize-y"
|
||||
{...field}
|
||||
/>
|
||||
<Textarea className="resize-y" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -196,7 +195,10 @@ export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) =>
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("TriggerMode")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
@@ -204,7 +206,9 @@ export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) =>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(triggerModes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -217,15 +221,20 @@ export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) =>
|
||||
name="fail_trigger_tasks"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("TasksToTriggerOnAlert") + t("SeparateWithComma")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("TasksToTriggerOnAlert") +
|
||||
t("SeparateWithComma")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="1,2,3"
|
||||
{...field}
|
||||
value={conv.arrToStr(field.value ?? [])}
|
||||
onChange={e => {
|
||||
const arr = conv.strToArr(e.target.value).map(Number);
|
||||
field.onChange(arr);
|
||||
onChange={(e) => {
|
||||
const arr = conv
|
||||
.strToArr(e.target.value)
|
||||
.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -238,15 +247,20 @@ export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) =>
|
||||
name="recover_trigger_tasks"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("TasksToTriggerAfterRecovery") + t("SeparateWithComma")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("TasksToTriggerAfterRecovery") +
|
||||
t("SeparateWithComma")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="1,2,3"
|
||||
{...field}
|
||||
value={conv.arrToStr(field.value ?? [])}
|
||||
onChange={e => {
|
||||
const arr = conv.strToArr(e.target.value).map(Number);
|
||||
field.onChange(arr);
|
||||
onChange={(e) => {
|
||||
const arr = conv
|
||||
.strToArr(e.target.value)
|
||||
.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -278,7 +292,9 @@ export const AlertRuleCard: React.FC<AlertRuleCardProps> = ({ data, mutate }) =>
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createCron, updateCron } from "@/api/cron"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -25,28 +27,26 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelCron } from "@/types"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { createCron, updateCron } from "@/api/cron"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { cronTypes, cronCoverageTypes } from "@/types"
|
||||
import { Textarea } from "./ui/textarea"
|
||||
import { useServer } from "@/hooks/useServer"
|
||||
import { useNotification } from "@/hooks/useNotfication"
|
||||
import { MultiSelect } from "./xui/multi-select"
|
||||
import { Combobox } from "./ui/combobox"
|
||||
import { useServer } from "@/hooks/useServer"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ModelCron } from "@/types"
|
||||
import { cronCoverageTypes, cronTypes } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Combobox } from "./ui/combobox"
|
||||
import { Textarea } from "./ui/textarea"
|
||||
import { MultiSelect } from "./xui/multi-select"
|
||||
|
||||
interface CronCardProps {
|
||||
data?: ModelCron;
|
||||
mutate: KeyedMutator<ModelCron[]>;
|
||||
data?: ModelCron
|
||||
mutate: KeyedMutator<ModelCron[]>
|
||||
}
|
||||
|
||||
const cronFormSchema = z.object({
|
||||
@@ -58,61 +58,58 @@ const cronFormSchema = z.object({
|
||||
cover: z.coerce.number().int(),
|
||||
push_successful: asOptionalField(z.boolean()),
|
||||
notification_group_id: z.coerce.number().int(),
|
||||
});
|
||||
})
|
||||
|
||||
export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof cronFormSchema>>({
|
||||
resolver: zodResolver(cronFormSchema),
|
||||
defaultValues: data ? data : {
|
||||
name: "",
|
||||
task_type: 0,
|
||||
scheduler: "",
|
||||
servers: [],
|
||||
cover: 0,
|
||||
notification_group_id: 0,
|
||||
},
|
||||
defaultValues: data
|
||||
? data
|
||||
: {
|
||||
name: "",
|
||||
task_type: 0,
|
||||
scheduler: "",
|
||||
servers: [],
|
||||
cover: 0,
|
||||
notification_group_id: 0,
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof cronFormSchema>) => {
|
||||
data?.id ? await updateCron(data.id, values) : await createCron(values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
data?.id ? await updateCron(data.id, values) : await createCron(values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
const { servers } = useServer();
|
||||
const serverList = servers?.map(s => ({
|
||||
const { servers } = useServer()
|
||||
const serverList = servers?.map((s) => ({
|
||||
value: `${s.id}`,
|
||||
label: s.name,
|
||||
})) || [{ value: "", label: "" }];
|
||||
})) || [{ value: "", label: "" }]
|
||||
|
||||
const { notifierGroup } = useNotification();
|
||||
const ngroupList = notifierGroup?.map(ng => ({
|
||||
const { notifierGroup } = useNotification()
|
||||
const ngroupList = notifierGroup?.map((ng) => ({
|
||||
value: `${ng.group.id}`,
|
||||
label: ng.group.name,
|
||||
})) || [{ value: "", label: "" }];
|
||||
})) || [{ value: "", label: "" }]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data?t("EditTask"):t("CreateTask")}</DialogTitle>
|
||||
<DialogTitle>{data ? t("EditTask") : t("CreateTask")}</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -124,10 +121,7 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="My Task"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="My Task" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -139,7 +133,10 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("Type")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select task type" />
|
||||
@@ -147,7 +144,9 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(cronTypes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -160,7 +159,7 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
name="scheduler"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("CronExpression") }</FormLabel>
|
||||
<FormLabel>{t("CronExpression")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="0 0 0 3 * * (At 3 AM)"
|
||||
@@ -178,10 +177,7 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Command")}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className="resize-y"
|
||||
{...field}
|
||||
/>
|
||||
<Textarea className="resize-y" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -193,16 +189,23 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("Coverage")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(cronCoverageTypes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
))}
|
||||
{Object.entries(cronCoverageTypes).map(
|
||||
([k, v]) => (
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
),
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
@@ -218,9 +221,9 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
<FormControl>
|
||||
<MultiSelect
|
||||
options={serverList}
|
||||
onValueChange={e => {
|
||||
const arr = e.map(Number);
|
||||
field.onChange(arr);
|
||||
onValueChange={(e) => {
|
||||
const arr = e.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
defaultValue={field.value?.map(String)}
|
||||
/>
|
||||
@@ -253,7 +256,9 @@ export const CronCard: React.FC<CronCardProps> = ({ data, mutate }) => {
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createDDNSProfile, updateDDNSProfile } from "@/api/ddns"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
@@ -9,14 +11,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -25,28 +19,34 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelDDNSProfile } from "@/types"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { ddnsTypes, ddnsRequestTypes } from "@/types"
|
||||
import { createDDNSProfile, updateDDNSProfile } from "@/api/ddns"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ModelDDNSProfile } from "@/types"
|
||||
import { ddnsRequestTypes, ddnsTypes } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
import { Textarea } from "./ui/textarea"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface DDNSCardProps {
|
||||
data?: ModelDDNSProfile;
|
||||
providers: string[];
|
||||
mutate: KeyedMutator<ModelDDNSProfile[]>;
|
||||
data?: ModelDDNSProfile
|
||||
providers: string[]
|
||||
mutate: KeyedMutator<ModelDDNSProfile[]>
|
||||
}
|
||||
|
||||
const ddnsFormSchema = z.object({
|
||||
@@ -63,47 +63,44 @@ const ddnsFormSchema = z.object({
|
||||
webhook_request_type: asOptionalField(z.coerce.number().int().min(1).max(255)),
|
||||
webhook_request_body: asOptionalField(z.string()),
|
||||
webhook_headers: asOptionalField(z.string()),
|
||||
});
|
||||
})
|
||||
|
||||
export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof ddnsFormSchema>>({
|
||||
resolver: zodResolver(ddnsFormSchema),
|
||||
defaultValues: data ? data : {
|
||||
max_retries: 3,
|
||||
name: "",
|
||||
provider: "dummy",
|
||||
domains: [],
|
||||
},
|
||||
defaultValues: data
|
||||
? data
|
||||
: {
|
||||
max_retries: 3,
|
||||
name: "",
|
||||
provider: "dummy",
|
||||
domains: [],
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof ddnsFormSchema>) => {
|
||||
data?.id ? await updateDDNSProfile(data.id, values) : await createDDNSProfile(values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
data?.id ? await updateDDNSProfile(data.id, values) : await createDDNSProfile(values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data?t("EditDDNS"):t("CreateDDNS")}</DialogTitle>
|
||||
<DialogTitle>{data ? t("EditDDNS") : t("CreateDDNS")}</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -115,10 +112,7 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="My DDNS Profile"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="My DDNS Profile" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -130,7 +124,10 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("Provider")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select service type" />
|
||||
@@ -138,7 +135,9 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{providers.map((v, i) => (
|
||||
<SelectItem key={i} value={v}>{v}</SelectItem>
|
||||
<SelectItem key={i} value={v}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -151,15 +150,17 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
name="domains"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("Domains") + t("SeparateWithComma")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("Domains") + t("SeparateWithComma")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="www.example.com"
|
||||
{...field}
|
||||
value={conv.arrToStr(field.value ?? [])}
|
||||
onChange={e => {
|
||||
const arr = conv.strToArr(e.target.value);
|
||||
field.onChange(arr);
|
||||
onChange={(e) => {
|
||||
const arr = conv.strToArr(e.target.value)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -174,10 +175,7 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
<FormItem>
|
||||
<FormLabel>{t("Credential")} 1</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Token ID"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="Token ID" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -190,10 +188,7 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
<FormItem>
|
||||
<FormLabel>{t("Credential")} 2</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Token Secret"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="Token Secret" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -206,11 +201,7 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
<FormItem>
|
||||
<FormLabel>{t("MaximumRetryAttempts")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="3"
|
||||
{...field}
|
||||
/>
|
||||
<Input type="number" placeholder="3" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -238,7 +229,10 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Webhook {t("RequestMethod")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Webhook Request Method" />
|
||||
@@ -246,7 +240,9 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(ddnsTypes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -260,16 +256,23 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Webhook {t("RequestType")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Webhook Request Type" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(ddnsRequestTypes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
))}
|
||||
{Object.entries(ddnsRequestTypes).map(
|
||||
([k, v]) => (
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
),
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
@@ -321,7 +324,9 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("Enable")} IPv4</Label>
|
||||
<Label className="text-sm">
|
||||
{t("Enable")} IPv4
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -339,7 +344,9 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("Enable")} IPv6</Label>
|
||||
<Label className="text-sm">
|
||||
{t("Enable")} IPv6
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -352,7 +359,9 @@ export const DDNSCard: React.FC<DDNSCardProps> = ({ data, providers, mutate }) =
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,42 +1,15 @@
|
||||
import { useEffect, useState, useRef, HTMLAttributes } from "react"
|
||||
import {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
} from "./xui/overlayless-sheet"
|
||||
import { IconButton } from "./xui/icon-button"
|
||||
import { createFM } from "@/api/fm"
|
||||
import { ModelCreateFMResponse, FMEntry, FMOpcode, FMIdentifier, FMWorkerData, FMWorkerOpcode } from "@/types"
|
||||
import { toast } from "sonner"
|
||||
import { ColumnDef } from "@tanstack/react-table"
|
||||
import { Folder, File } from "lucide-react"
|
||||
import { copyToClipboard, fm, formatPath, fmWorker as worker } from "@/lib/utils"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogFooter,
|
||||
AlertDialogCancel,
|
||||
AlertDialogAction,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Row, flexRender } from "@tanstack/react-table"
|
||||
import { TableRow, TableCell } from "./ui/table"
|
||||
import { DataTable } from "./xui/virtulized-data-table"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Filepath } from "./xui/filepath"
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery"
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
@@ -44,49 +17,80 @@ import {
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
} from "@/components/ui/drawer"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery"
|
||||
import { copyToClipboard, fm, formatPath, fmWorker as worker } from "@/lib/utils"
|
||||
import {
|
||||
FMEntry,
|
||||
FMIdentifier,
|
||||
FMOpcode,
|
||||
FMWorkerData,
|
||||
FMWorkerOpcode,
|
||||
ModelCreateFMResponse,
|
||||
} from "@/types"
|
||||
import { ColumnDef } from "@tanstack/react-table"
|
||||
import { Row, flexRender } from "@tanstack/react-table"
|
||||
import { File, Folder } from "lucide-react"
|
||||
import { HTMLAttributes, useEffect, useRef, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { TableCell, TableRow } from "./ui/table"
|
||||
import { Filepath } from "./xui/filepath"
|
||||
import { IconButton } from "./xui/icon-button"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "./xui/overlayless-sheet"
|
||||
import { DataTable } from "./xui/virtulized-data-table"
|
||||
|
||||
interface FMProps {
|
||||
wsUrl: string;
|
||||
wsUrl: string
|
||||
}
|
||||
|
||||
const arraysEqual = (a: Uint8Array, b: Uint8Array) => {
|
||||
if (a.length !== b.length) return false;
|
||||
if (a.length !== b.length) return false
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
if (a[i] !== b[i]) return false
|
||||
}
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
|
||||
const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl, ...props }) => {
|
||||
const { t } = useTranslation();
|
||||
const fmRef = useRef<HTMLDivElement>(null);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const { t } = useTranslation()
|
||||
const fmRef = useRef<HTMLDivElement>(null)
|
||||
const wsRef = useRef<WebSocket | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
wsRef.current?.close();
|
||||
};
|
||||
}, []);
|
||||
wsRef.current?.close()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const [dOpen, setdOpen] = useState(false);
|
||||
const [uOpen, setuOpen] = useState(false);
|
||||
const [dOpen, setdOpen] = useState(false)
|
||||
const [uOpen, setuOpen] = useState(false)
|
||||
|
||||
const columns: ColumnDef<FMEntry>[] = [
|
||||
{
|
||||
id: "type",
|
||||
header: () => <span>{t("Type")}</span>,
|
||||
accessorFn: row => row.type,
|
||||
cell: ({ row }) => (
|
||||
row.original.type == 0 ? <File size={24} /> : <Folder size={24} />
|
||||
),
|
||||
accessorFn: (row) => row.type,
|
||||
cell: ({ row }) => (row.original.type == 0 ? <File size={24} /> : <Folder size={24} />),
|
||||
},
|
||||
{
|
||||
header: () => <span>{t("Name")}</span>,
|
||||
id: "name",
|
||||
accessorFn: row => row.name,
|
||||
accessorFn: (row) => row.name,
|
||||
cell: ({ row }) => (
|
||||
<div className="max-w-48 text-sm whitespace-normal break-words">
|
||||
{row.original.name}
|
||||
@@ -99,24 +103,26 @@ const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl,
|
||||
id: "download",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<IconButton variant="ghost" icon="download" onClick={
|
||||
() => {
|
||||
if (!dOpen) setdOpen(true);
|
||||
downloadFile(row.original.name);
|
||||
}
|
||||
} />
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
icon="download"
|
||||
onClick={() => {
|
||||
if (!dOpen) setdOpen(true)
|
||||
downloadFile(row.original.name)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
}
|
||||
},
|
||||
]
|
||||
|
||||
const tableRowComponent = (rows: Row<FMEntry>[]) =>
|
||||
function getTableRow(props: HTMLAttributes<HTMLTableRowElement>) {
|
||||
// @ts-expect-error data-index is a valid attribute
|
||||
const index = props["data-index"];
|
||||
const row = rows[index];
|
||||
const index = props["data-index"]
|
||||
const row = rows[index]
|
||||
|
||||
if (!row) return null;
|
||||
if (!row) return null
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
@@ -124,7 +130,7 @@ const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl,
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
onClick={() => {
|
||||
if (row.original.type === 1) {
|
||||
setPath(`${currentPath}/${row.original.name}`);
|
||||
setPath(`${currentPath}/${row.original.name}`)
|
||||
}
|
||||
}}
|
||||
className={row.original.type === 1 ? "cursor-pointer" : "cursor-default"}
|
||||
@@ -136,155 +142,163 @@ const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl,
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
const [fmEntires, setFMEntries] = useState<FMEntry[]>([]);
|
||||
const [fmEntires, setFMEntries] = useState<FMEntry[]>([])
|
||||
|
||||
const firstChunk = useRef(true);
|
||||
const handleReady = useRef(false);
|
||||
const currentBasename = useRef('temp');
|
||||
const firstChunk = useRef(true)
|
||||
const handleReady = useRef(false)
|
||||
const currentBasename = useRef("temp")
|
||||
|
||||
const waitForHandleReady = async () => {
|
||||
while (!handleReady.current) {
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
worker.onmessage = async (event: MessageEvent<FMWorkerData>) => {
|
||||
switch (event.data.type) {
|
||||
case FMWorkerOpcode.Error: {
|
||||
console.error('Error from worker', event.data.error);
|
||||
break;
|
||||
console.error("Error from worker", event.data.error)
|
||||
break
|
||||
}
|
||||
case FMWorkerOpcode.Progress: {
|
||||
handleReady.current = true;
|
||||
break;
|
||||
handleReady.current = true
|
||||
break
|
||||
}
|
||||
case FMWorkerOpcode.Result: {
|
||||
handleReady.current = false;
|
||||
handleReady.current = false
|
||||
|
||||
if (event.data.blob && event.data.fileName) {
|
||||
const url = URL.createObjectURL(event.data.blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = event.data.fileName;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(url);
|
||||
const url = URL.createObjectURL(event.data.blob)
|
||||
const anchor = document.createElement("a")
|
||||
anchor.href = url
|
||||
anchor.download = event.data.fileName
|
||||
anchor.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
firstChunk.current = true;
|
||||
if (dOpen) setdOpen(false);
|
||||
break;
|
||||
firstChunk.current = true
|
||||
if (dOpen) setdOpen(false)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const [currentPath, setPath] = useState('');
|
||||
const [currentPath, setPath] = useState("")
|
||||
useEffect(() => {
|
||||
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||
listFile();
|
||||
listFile()
|
||||
}
|
||||
}, [wsRef.current, currentPath])
|
||||
|
||||
useEffect(() => {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
wsRef.current = ws;
|
||||
ws.binaryType = 'arraybuffer';
|
||||
const ws = new WebSocket(wsUrl)
|
||||
wsRef.current = ws
|
||||
ws.binaryType = "arraybuffer"
|
||||
ws.onopen = () => {
|
||||
listFile();
|
||||
listFile()
|
||||
}
|
||||
ws.onclose = (e) => {
|
||||
console.log('WebSocket connection closed:', e);
|
||||
console.log("WebSocket connection closed:", e)
|
||||
}
|
||||
ws.onerror = (e) => {
|
||||
console.error(e);
|
||||
console.error(e)
|
||||
toast("Websocket" + " " + t("Error"), {
|
||||
description: t("Results.UnExpectedError"),
|
||||
})
|
||||
}
|
||||
ws.onmessage = async (e) => {
|
||||
try {
|
||||
const buf: ArrayBufferLike = e.data;
|
||||
const buf: ArrayBufferLike = e.data
|
||||
|
||||
if (firstChunk.current) {
|
||||
const identifier = new Uint8Array(buf, 0, 4);
|
||||
const identifier = new Uint8Array(buf, 0, 4)
|
||||
if (arraysEqual(identifier, FMIdentifier.file)) {
|
||||
worker.postMessage({ operation: 1, arrayBuffer: buf, fileName: currentBasename.current });
|
||||
firstChunk.current = false;
|
||||
worker.postMessage({
|
||||
operation: 1,
|
||||
arrayBuffer: buf,
|
||||
fileName: currentBasename.current,
|
||||
})
|
||||
firstChunk.current = false
|
||||
} else if (arraysEqual(identifier, FMIdentifier.fileName)) {
|
||||
const { path, fmList } = await fm.parseFMList(buf);
|
||||
setPath(path);
|
||||
setFMEntries(fmList);
|
||||
const { path, fmList } = await fm.parseFMList(buf)
|
||||
setPath(path)
|
||||
setFMEntries(fmList)
|
||||
} else if (arraysEqual(identifier, FMIdentifier.error)) {
|
||||
const errBytes = buf.slice(4);
|
||||
const errMsg = new TextDecoder('utf-8').decode(errBytes);
|
||||
throw new Error(errMsg);
|
||||
const errBytes = buf.slice(4)
|
||||
const errMsg = new TextDecoder("utf-8").decode(errBytes)
|
||||
throw new Error(errMsg)
|
||||
} else if (arraysEqual(identifier, FMIdentifier.complete)) {
|
||||
// Upload completed
|
||||
if (uOpen) setuOpen(false);
|
||||
listFile();
|
||||
if (uOpen) setuOpen(false)
|
||||
listFile()
|
||||
} else {
|
||||
throw new Error(t("Results.UnknownIdentifier"));
|
||||
throw new Error(t("Results.UnknownIdentifier"))
|
||||
}
|
||||
} else {
|
||||
await waitForHandleReady();
|
||||
worker.postMessage({ operation: 2, arrayBuffer: buf, fileName: currentBasename.current });
|
||||
await waitForHandleReady()
|
||||
worker.postMessage({
|
||||
operation: 2,
|
||||
arrayBuffer: buf,
|
||||
fileName: currentBasename.current,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing received data:', error);
|
||||
console.error("Error processing received data:", error)
|
||||
toast("FM" + " " + t("Error"), {
|
||||
description: t("Results.UnExpectedError"),
|
||||
})
|
||||
if (dOpen) setdOpen(false);
|
||||
if (uOpen) setuOpen(false);
|
||||
if (dOpen) setdOpen(false)
|
||||
if (uOpen) setuOpen(false)
|
||||
}
|
||||
}
|
||||
}, [wsUrl])
|
||||
|
||||
let listFile = () => {
|
||||
const prefix = new Int8Array([FMOpcode.List]);
|
||||
const pathMsg = new TextEncoder().encode(currentPath);
|
||||
const listFile = () => {
|
||||
const prefix = new Int8Array([FMOpcode.List])
|
||||
const pathMsg = new TextEncoder().encode(currentPath)
|
||||
|
||||
const msg = new Int8Array(prefix.length + pathMsg.length);
|
||||
msg.set(prefix);
|
||||
msg.set(pathMsg, prefix.length);
|
||||
const msg = new Int8Array(prefix.length + pathMsg.length)
|
||||
msg.set(prefix)
|
||||
msg.set(pathMsg, prefix.length)
|
||||
|
||||
wsRef.current?.send(msg);
|
||||
wsRef.current?.send(msg)
|
||||
}
|
||||
|
||||
const downloadFile = (basename: string) => {
|
||||
currentBasename.current = basename;
|
||||
const prefix = new Int8Array([FMOpcode.Download]);
|
||||
const filePathMessage = new TextEncoder().encode(`${currentPath}/${basename}`);
|
||||
currentBasename.current = basename
|
||||
const prefix = new Int8Array([FMOpcode.Download])
|
||||
const filePathMessage = new TextEncoder().encode(`${currentPath}/${basename}`)
|
||||
|
||||
const msg = new Int8Array(prefix.length + filePathMessage.length);
|
||||
msg.set(prefix);
|
||||
msg.set(filePathMessage, prefix.length);
|
||||
const msg = new Int8Array(prefix.length + filePathMessage.length)
|
||||
msg.set(prefix)
|
||||
msg.set(filePathMessage, prefix.length)
|
||||
|
||||
wsRef.current?.send(msg);
|
||||
wsRef.current?.send(msg)
|
||||
}
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
const chunkSize = 1048576; // 1MB chunk
|
||||
let offset = 0;
|
||||
const chunkSize = 1048576 // 1MB chunk
|
||||
let offset = 0
|
||||
|
||||
// Send header
|
||||
const header = fm.buildUploadHeader({ path: currentPath, file: file });
|
||||
wsRef.current?.send(header);
|
||||
const header = fm.buildUploadHeader({ path: currentPath, file: file })
|
||||
wsRef.current?.send(header)
|
||||
|
||||
// Send data chunks
|
||||
while (offset < file.size) {
|
||||
const chunk = file.slice(offset, offset + chunkSize);
|
||||
const arrayBuffer = await fm.readFileAsArrayBuffer(chunk);
|
||||
if (arrayBuffer) wsRef.current?.send(arrayBuffer);
|
||||
offset += chunkSize;
|
||||
const chunk = file.slice(offset, offset + chunkSize)
|
||||
const arrayBuffer = await fm.readFileAsArrayBuffer(chunk)
|
||||
if (arrayBuffer) wsRef.current?.send(arrayBuffer)
|
||||
offset += chunkSize
|
||||
}
|
||||
}
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const [gotoPath, setGotoPath] = useState('');
|
||||
const [gotoPath, setGotoPath] = useState("")
|
||||
return (
|
||||
<div ref={fmRef} {...props}>
|
||||
<div className="flex justify-center items-center gap-4">
|
||||
@@ -294,45 +308,72 @@ const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl,
|
||||
<IconButton variant="ghost" icon="menu" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={listFile}>{t('Refresh')}</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={
|
||||
async () => {
|
||||
await copyToClipboard(formatPath(currentPath));
|
||||
}
|
||||
}>{t("CopyPath")}</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={listFile}>{t("Refresh")}</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={async () => {
|
||||
try {
|
||||
await copyToClipboard(formatPath(currentPath))
|
||||
} catch (error: any) {
|
||||
toast("FM" + " " + t("Error"), {
|
||||
description: error.message,
|
||||
})
|
||||
console.log("copy error: ", error)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("CopyPath")}
|
||||
</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem>{t('Goto')}</DropdownMenuItem>
|
||||
<DropdownMenuItem>{t("Goto")}</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('Goto')}</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("Goto")}</AlertDialogTitle>
|
||||
<AlertDialogDescription />
|
||||
</AlertDialogHeader>
|
||||
<Input className="mb-1" placeholder="Path" value={gotoPath} onChange={(e) => { setGotoPath(e.target.value) }} />
|
||||
<Input
|
||||
className="mb-1"
|
||||
placeholder="Path"
|
||||
value={gotoPath}
|
||||
onChange={(e) => {
|
||||
setGotoPath(e.target.value)
|
||||
}}
|
||||
/>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("Close")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => { setPath(gotoPath) }}>{t("Confirm")}</AlertDialogAction>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
setPath(gotoPath)
|
||||
}}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<h1 className="text-base">{t("FileManager")}</h1>
|
||||
<div className="ml-auto">
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={
|
||||
async (e) => {
|
||||
const files = e.target.files;
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={async (e) => {
|
||||
const files = e.target.files
|
||||
if (files && files.length > 0) {
|
||||
if (!uOpen) setuOpen(true);
|
||||
await uploadFile(files[0]);
|
||||
if (!uOpen) setuOpen(true)
|
||||
await uploadFile(files[0])
|
||||
}
|
||||
}
|
||||
} />
|
||||
<IconButton icon="upload" variant="ghost" onClick={
|
||||
() => {
|
||||
if (fileInputRef.current) fileInputRef.current.click();
|
||||
}
|
||||
} />
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="upload"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
if (fileInputRef.current) fileInputRef.current.click()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Filepath path={currentPath} setPath={setPath} />
|
||||
@@ -354,83 +395,83 @@ const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl,
|
||||
</AlertDialog>
|
||||
<DataTable columns={columns} data={fmEntires} rowComponent={tableRowComponent} />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export const FMCard = ({ id }: { id?: string }) => {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [fm, setFM] = useState<ModelCreateFMResponse | null>(null);
|
||||
const [init, setInit] = useState(false);
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [fm, setFM] = useState<ModelCreateFMResponse | null>(null)
|
||||
const [init, setInit] = useState(false)
|
||||
|
||||
const isDesktop = useMediaQuery("(min-width: 640px)");
|
||||
const isDesktop = useMediaQuery("(min-width: 640px)")
|
||||
|
||||
const fetchFM = async () => {
|
||||
if (id) {
|
||||
try {
|
||||
setInit(false);
|
||||
const createdFM = await createFM(id);
|
||||
setFM(createdFM);
|
||||
setInit(false)
|
||||
const createdFM = await createFM(id)
|
||||
setFM(createdFM)
|
||||
} catch (e) {
|
||||
toast(t("Error"), {
|
||||
description: t("Results.UnExpectedError"),
|
||||
})
|
||||
console.error("fetch error", e);
|
||||
return;
|
||||
console.error("fetch error", e)
|
||||
return
|
||||
}
|
||||
setInit(true);
|
||||
setInit(true)
|
||||
}
|
||||
}
|
||||
|
||||
return (isDesktop ?
|
||||
(
|
||||
<Sheet
|
||||
modal={false}
|
||||
open={open}
|
||||
onOpenChange={(isOpen) => { if (isOpen) setOpen(true); }}
|
||||
>
|
||||
<SheetTrigger asChild>
|
||||
<IconButton icon="folder-closed" onClick={fetchFM} />
|
||||
</SheetTrigger>
|
||||
<SheetContent
|
||||
setOpen={setOpen}
|
||||
className="min-w-[35%]"
|
||||
>
|
||||
<div className="overflow-auto">
|
||||
<SheetTitle />
|
||||
<SheetHeader className="pb-2">
|
||||
<SheetDescription />
|
||||
</SheetHeader>
|
||||
{fm?.session_id && init
|
||||
?
|
||||
<FMComponent className="p-1 space-y-5" wsUrl={`/api/v1/ws/file/${fm.session_id}`} />
|
||||
:
|
||||
<p>{t("Results.TheServerDoesNotOnline")}</p>
|
||||
}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
: (
|
||||
<Drawer>
|
||||
<DrawerTrigger asChild>
|
||||
<IconButton icon="folder-closed" onClick={fetchFM} />
|
||||
</DrawerTrigger>
|
||||
<DrawerContent className="min-h-[60%] p-4">
|
||||
<div className="overflow-auto">
|
||||
<DrawerTitle />
|
||||
<DrawerHeader className="pb-2">
|
||||
<SheetDescription />
|
||||
</DrawerHeader>
|
||||
{fm?.session_id && init
|
||||
?
|
||||
<FMComponent className="p-1 space-y-5" wsUrl={`/api/v1/ws/file/${fm.session_id}`} />
|
||||
:
|
||||
<p>{t("Results.TheServerDoesNotOnline")}</p>
|
||||
}
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
)
|
||||
return isDesktop ? (
|
||||
<Sheet
|
||||
modal={false}
|
||||
open={open}
|
||||
onOpenChange={(isOpen) => {
|
||||
if (isOpen) setOpen(true)
|
||||
}}
|
||||
>
|
||||
<SheetTrigger asChild>
|
||||
<IconButton icon="folder-closed" onClick={fetchFM} />
|
||||
</SheetTrigger>
|
||||
<SheetContent setOpen={setOpen} className="min-w-[35%]">
|
||||
<div className="overflow-auto">
|
||||
<SheetTitle />
|
||||
<SheetHeader className="pb-2">
|
||||
<SheetDescription />
|
||||
</SheetHeader>
|
||||
{fm?.session_id && init ? (
|
||||
<FMComponent
|
||||
className="p-1 space-y-5"
|
||||
wsUrl={`/api/v1/ws/file/${fm.session_id}`}
|
||||
/>
|
||||
) : (
|
||||
<p>{t("Results.TheServerDoesNotOnline")}</p>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
) : (
|
||||
<Drawer>
|
||||
<DrawerTrigger asChild>
|
||||
<IconButton icon="folder-closed" onClick={fetchFM} />
|
||||
</DrawerTrigger>
|
||||
<DrawerContent className="min-h-[60%] p-4">
|
||||
<div className="overflow-auto">
|
||||
<DrawerTitle />
|
||||
<DrawerHeader className="pb-2">
|
||||
<SheetDescription />
|
||||
</DrawerHeader>
|
||||
{fm?.session_id && init ? (
|
||||
<FMComponent
|
||||
className="p-1 space-y-5"
|
||||
wsUrl={`/api/v1/ws/file/${fm.session_id}`}
|
||||
/>
|
||||
) : (
|
||||
<p>{t("Results.TheServerDoesNotOnline")}</p>
|
||||
)}
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
import {
|
||||
Tabs,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { Link, useLocation } from "react-router-dom"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export const GroupTab = ({ className }: { className?: string }) => {
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation()
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<Tabs defaultValue={location.pathname} className={className}>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { IconButton } from "@/components/xui/icon-button";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -11,34 +9,48 @@ import {
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { KeyedMutator } from "swr";
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { KeyedMutator } from "swr"
|
||||
|
||||
interface ButtonGroupProps<E, U> {
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
delete: { fn: (id: E[]) => Promise<void>, id: E[], mutate: KeyedMutator<U> };
|
||||
className?: string
|
||||
children?: React.ReactNode
|
||||
delete: { fn: (id: E[]) => Promise<void>; id: E[]; mutate: KeyedMutator<U> }
|
||||
}
|
||||
|
||||
export function HeaderButtonGroup<E, U>({ className, children, delete: { fn, id, mutate } }: ButtonGroupProps<E, U>) {
|
||||
export function HeaderButtonGroup<E, U>({
|
||||
className,
|
||||
children,
|
||||
delete: { fn, id, mutate },
|
||||
}: ButtonGroupProps<E, U>) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const handleDelete = async () => {
|
||||
await fn(id);
|
||||
await mutate();
|
||||
try {
|
||||
await fn(id)
|
||||
} catch (error: any) {
|
||||
toast(t("Error"), {
|
||||
description: error.message,
|
||||
})
|
||||
}
|
||||
await mutate()
|
||||
}
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
{id.length < 1 ? (
|
||||
<>
|
||||
<IconButton variant="destructive" icon="trash" onClick={() => {
|
||||
toast(t("Error"), {
|
||||
description: t("Results.NoRowsAreSelected")
|
||||
});
|
||||
}} />
|
||||
<IconButton
|
||||
variant="destructive"
|
||||
icon="trash"
|
||||
onClick={() => {
|
||||
toast(t("Error"), {
|
||||
description: t("Results.NoRowsAreSelected"),
|
||||
})
|
||||
}}
|
||||
/>
|
||||
{children}
|
||||
</>
|
||||
) : (
|
||||
@@ -56,7 +68,12 @@ export function HeaderButtonGroup<E, U>({ className, children, delete: { fn, id,
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("Close")}</AlertDialogCancel>
|
||||
<AlertDialogAction className={buttonVariants({ variant: "destructive" })} onClick={handleDelete}>{t("Confirm")}</AlertDialogAction>
|
||||
<AlertDialogAction
|
||||
className={buttonVariants({ variant: "destructive" })}
|
||||
onClick={handleDelete}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
@@ -1,20 +1,4 @@
|
||||
import {
|
||||
NavigationMenu,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuLink,
|
||||
NavigationMenuList,
|
||||
navigationMenuTriggerStyle,
|
||||
} from "@/components/ui/navigation-menu"
|
||||
import { ModeToggle } from "@/components/mode-toggle";
|
||||
import { Card } from "./ui/card";
|
||||
import { useMainStore } from "@/hooks/useMainStore";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar";
|
||||
import { NzNavigationMenuLink } from "./xui/navigation-menu";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuTrigger } from "./ui/dropdown-menu";
|
||||
import { LogOut, Settings, User2 } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { Link, useLocation, useNavigate } from "react-router-dom";
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery";
|
||||
import { ModeToggle } from "@/components/mode-toggle"
|
||||
import {
|
||||
Drawer,
|
||||
DrawerClose,
|
||||
@@ -25,13 +9,38 @@ import {
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
} from "@/components/ui/drawer"
|
||||
import { Button } from "./ui/button";
|
||||
import { IconButton } from "./xui/icon-button";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
NavigationMenu,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuLink,
|
||||
navigationMenuTriggerStyle,
|
||||
} from "@/components/ui/navigation-menu"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { useMainStore } from "@/hooks/useMainStore"
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery"
|
||||
import i18next from "i18next"
|
||||
import { LogOut, Settings, User2 } from "lucide-react"
|
||||
import { DateTime } from "luxon"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { Link, useLocation, useNavigate } from "react-router-dom"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar"
|
||||
import { Button } from "./ui/button"
|
||||
import { Card } from "./ui/card"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuTrigger,
|
||||
} from "./ui/dropdown-menu"
|
||||
import { IconButton } from "./xui/icon-button"
|
||||
import { NzNavigationMenuLink } from "./xui/navigation-menu"
|
||||
|
||||
import i18next from "i18next";
|
||||
const pages = [
|
||||
{ href: "/dashboard", label: i18next.t("Server") },
|
||||
{ href: "/dashboard/service", label: i18next.t("Service") },
|
||||
@@ -43,209 +52,329 @@ const pages = [
|
||||
]
|
||||
|
||||
export default function Header() {
|
||||
const { t } = useTranslation();
|
||||
const { logout } = useAuth();
|
||||
const profile = useMainStore(store => store.profile);
|
||||
const { t } = useTranslation()
|
||||
const { logout } = useAuth()
|
||||
const profile = useMainStore((store) => store.profile)
|
||||
|
||||
const location = useLocation();
|
||||
const location = useLocation()
|
||||
const isDesktop = useMediaQuery("(min-width: 890px)")
|
||||
|
||||
const [open, setOpen] = useState(false)
|
||||
const [dropdownOpen, setDropdownOpen] = useState(false);
|
||||
const [dropdownOpen, setDropdownOpen] = useState(false)
|
||||
|
||||
const navigate = useNavigate();
|
||||
const navigate = useNavigate()
|
||||
|
||||
return (
|
||||
isDesktop ? (
|
||||
<header className="h-16 flex items-center border-b-2 px-4 overflow-x-auto">
|
||||
<NavigationMenu className="sm:max-w-full">
|
||||
<NavigationMenuList>
|
||||
<Card className="mr-1">
|
||||
<NavigationMenuLink asChild className={navigationMenuTriggerStyle() + ' !text-foreground'}>
|
||||
<Link to={profile ? "/dashboard" : '#'}><img className="h-7 mr-1" src='/dashboard/logo.svg' /> {t("nezha")}</Link>
|
||||
</NavigationMenuLink>
|
||||
</Card>
|
||||
return isDesktop ? (
|
||||
<header className="flex pt-8 px-4 overflow-x-auto dark:bg-black/40 bg-muted border-b-[1px]">
|
||||
<NavigationMenu className="flex flex-col items-start max-w-5xl mx-auto">
|
||||
<section className="w-full flex items-center justify-between">
|
||||
<div className="flex justify-between items-center w-full">
|
||||
<NavigationMenuLink
|
||||
asChild
|
||||
className={navigationMenuTriggerStyle() + " !text-foreground"}
|
||||
>
|
||||
<Link to={profile ? "/dashboard" : "#"}>
|
||||
<img className="h-7 mr-1" src="/dashboard/logo.svg" />
|
||||
{t("nezha")}
|
||||
</Link>
|
||||
</NavigationMenuLink>
|
||||
|
||||
{
|
||||
profile && (
|
||||
<div className="flex items-center gap-1">
|
||||
<ModeToggle />
|
||||
{profile && (
|
||||
<>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard"} className={navigationMenuTriggerStyle()}>
|
||||
<Link to="/dashboard">{t("Server")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/service"} className={navigationMenuTriggerStyle()}>
|
||||
<Link to="/dashboard/service">{t("Service")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/cron"} className={navigationMenuTriggerStyle()}>
|
||||
<Link to="/dashboard/cron">{t('Task')}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/notification" || location.pathname === "/dashboard/alert-rule"} className={navigationMenuTriggerStyle()}>
|
||||
<Link to="/dashboard/notification">{t('Notification')}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/ddns"} className={navigationMenuTriggerStyle()}>
|
||||
<Link to="/dashboard/ddns">{t('DDNS')}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/nat"} className={navigationMenuTriggerStyle()}>
|
||||
<Link to="/dashboard/nat">{t('NATT')}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink asChild active={location.pathname === "/dashboard/server-group" || location.pathname === "/dashboard/notification-group"} className={navigationMenuTriggerStyle()}>
|
||||
<Link to="/dashboard/server-group">{t('Group')}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<DropdownMenu
|
||||
open={dropdownOpen}
|
||||
onOpenChange={setDropdownOpen}
|
||||
>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Avatar className="ml-1 h-8 w-8 cursor-pointer border-foreground border-[1px]">
|
||||
<AvatarImage
|
||||
src={
|
||||
"https://api.dicebear.com/7.x/notionists/svg?seed=" +
|
||||
profile.username
|
||||
}
|
||||
alt={profile.username}
|
||||
/>
|
||||
<AvatarFallback>{profile.username}</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-32">
|
||||
<DropdownMenuLabel>
|
||||
{profile.username}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/profile")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<User2 />
|
||||
{t("Profile")}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/settings")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<Settings />
|
||||
{t("Settings")}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={logout}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<LogOut />
|
||||
{t("Logout")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
)
|
||||
}
|
||||
</NavigationMenuList>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<ModeToggle />
|
||||
{
|
||||
profile && <>
|
||||
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Avatar className="ml-1 h-8 w-8 cursor-pointer border-foreground border-[1px]">
|
||||
<AvatarImage src={'https://api.dicebear.com/7.x/notionists/svg?seed=' + profile.username} alt={profile.username} />
|
||||
<AvatarFallback>{profile.username}</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-32">
|
||||
<DropdownMenuLabel>{profile.username}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/profile")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<User2 />
|
||||
{t('Profile')}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/settings")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<Settings />
|
||||
{t('Settings')}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={logout} className="cursor-pointer">
|
||||
<LogOut />
|
||||
{t('Logout')}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</NavigationMenu>
|
||||
</header>
|
||||
)
|
||||
: (
|
||||
<header className="flex border-b-2 px-4 h-16">
|
||||
<div className="flex max-w-max flex-1 items-center justify-center gap-2">
|
||||
{profile &&
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger aria-label="Toggle Menu" asChild>
|
||||
<IconButton icon="menu" variant="ghost" />
|
||||
</DrawerTrigger>
|
||||
<DrawerContent>
|
||||
<DrawerHeader className="text-left">
|
||||
<DrawerTitle>{t('NavigateTo')}</DrawerTitle>
|
||||
<DrawerDescription>{t('SelectAPageToNavigateTo')}</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="grid gap-1 px-4">
|
||||
{pages.slice(0).map((item, index) => (
|
||||
<Link
|
||||
key={index}
|
||||
to={item.href ? item.href : "#"}
|
||||
className="py-1 text-sm"
|
||||
onClick={() => { setOpen(false) }}
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">{t('Close')}</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
}
|
||||
</div>
|
||||
<Card className="mx-2 my-2 flex justify-center items-center hover:bg-accent transition duration-200">
|
||||
<Link className="inline-flex w-full items-center px-4 py-2" to={profile ? "/dashboard" : '#'}><img className="h-7 mr-1" src='/dashboard/logo.svg' /> NEZHA</Link>
|
||||
</Card>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<ModeToggle />
|
||||
{
|
||||
profile && <>
|
||||
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Avatar className="ml-1 h-8 w-8 cursor-pointer border-foreground border-[1px]">
|
||||
<AvatarImage src={'https://api.dicebear.com/7.x/notionists/svg?seed=' + profile.username} alt={profile.username} />
|
||||
<AvatarFallback>{profile.username}</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
<DropdownMenuLabel>{profile.username}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/profile")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<User2 />
|
||||
{t('Profile')}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/settings")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<Settings />
|
||||
{t('Settings')}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={logout} className="cursor-pointer">
|
||||
<LogOut />
|
||||
{t('Logout')}
|
||||
<DropdownMenuShortcut>⇧⌘Q</DropdownMenuShortcut>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
</section>
|
||||
<div className="flex mt-4 ml-4">
|
||||
<Overview />
|
||||
</div>
|
||||
<div className="flex mt-4 list-none">
|
||||
{profile && (
|
||||
<>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink
|
||||
asChild
|
||||
active={location.pathname === "/dashboard"}
|
||||
className={navigationMenuTriggerStyle()}
|
||||
>
|
||||
<Link to="/dashboard">{t("Server")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink
|
||||
asChild
|
||||
active={location.pathname === "/dashboard/service"}
|
||||
className={navigationMenuTriggerStyle()}
|
||||
>
|
||||
<Link to="/dashboard/service">{t("Service")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink
|
||||
asChild
|
||||
active={location.pathname === "/dashboard/cron"}
|
||||
className={navigationMenuTriggerStyle()}
|
||||
>
|
||||
<Link to="/dashboard/cron">{t("Task")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink
|
||||
asChild
|
||||
active={
|
||||
location.pathname === "/dashboard/notification" ||
|
||||
location.pathname === "/dashboard/alert-rule"
|
||||
}
|
||||
className={navigationMenuTriggerStyle()}
|
||||
>
|
||||
<Link to="/dashboard/notification">{t("Notification")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink
|
||||
asChild
|
||||
active={location.pathname === "/dashboard/ddns"}
|
||||
className={navigationMenuTriggerStyle()}
|
||||
>
|
||||
<Link to="/dashboard/ddns">{t("DDNS")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink
|
||||
asChild
|
||||
active={location.pathname === "/dashboard/nat"}
|
||||
className={navigationMenuTriggerStyle()}
|
||||
>
|
||||
<Link to="/dashboard/nat">{t("NATT")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NzNavigationMenuLink
|
||||
asChild
|
||||
active={
|
||||
location.pathname === "/dashboard/server-group" ||
|
||||
location.pathname === "/dashboard/notification-group"
|
||||
}
|
||||
className={navigationMenuTriggerStyle()}
|
||||
>
|
||||
<Link to="/dashboard/server-group">{t("Group")}</Link>
|
||||
</NzNavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</NavigationMenu>
|
||||
</header>
|
||||
) : (
|
||||
<header className="flex border-b-2 px-4 h-16">
|
||||
<div className="flex max-w-max flex-1 items-center justify-center gap-2">
|
||||
{profile && (
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger aria-label="Toggle Menu" asChild>
|
||||
<IconButton icon="menu" variant="ghost" />
|
||||
</DrawerTrigger>
|
||||
<DrawerContent>
|
||||
<DrawerHeader className="text-left">
|
||||
<DrawerTitle>{t("NavigateTo")}</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
{t("SelectAPageToNavigateTo")}
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="grid gap-1 px-4">
|
||||
{pages.slice(0).map((item, index) => (
|
||||
<Link
|
||||
key={index}
|
||||
to={item.href ? item.href : "#"}
|
||||
className="py-1 text-sm"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">{t("Close")}</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
)}
|
||||
</div>
|
||||
<Card className="mx-2 my-2 flex justify-center items-center hover:bg-accent transition duration-200">
|
||||
<Link
|
||||
className="inline-flex w-full items-center px-4 py-2"
|
||||
to={profile ? "/dashboard" : "#"}
|
||||
>
|
||||
<img className="h-7 mr-1" src="/dashboard/logo.svg" /> NEZHA
|
||||
</Link>
|
||||
</Card>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<ModeToggle />
|
||||
{profile && (
|
||||
<>
|
||||
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Avatar className="ml-1 h-8 w-8 cursor-pointer border-foreground border-[1px]">
|
||||
<AvatarImage
|
||||
src={
|
||||
"https://api.dicebear.com/7.x/notionists/svg?seed=" +
|
||||
profile.username
|
||||
}
|
||||
alt={profile.username}
|
||||
/>
|
||||
<AvatarFallback>{profile.username}</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
<DropdownMenuLabel>{profile.username}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/profile")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<User2 />
|
||||
{t("Profile")}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setDropdownOpen(false)
|
||||
navigate("/dashboard/settings")
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<Settings />
|
||||
{t("Settings")}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={logout} className="cursor-pointer">
|
||||
<LogOut />
|
||||
{t("Logout")}
|
||||
<DropdownMenuShortcut>⇧⌘Q</DropdownMenuShortcut>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
// https://github.com/streamich/react-use/blob/master/src/useInterval.ts
|
||||
const useInterval = (callback: () => void, delay?: number | null) => {
|
||||
const savedCallback = useRef<() => void>(() => {})
|
||||
useEffect(() => {
|
||||
savedCallback.current = callback
|
||||
})
|
||||
useEffect(() => {
|
||||
if (delay !== null) {
|
||||
const interval = setInterval(() => savedCallback.current(), delay || 0)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
return undefined
|
||||
}, [delay])
|
||||
}
|
||||
|
||||
function Overview() {
|
||||
const { t } = useTranslation()
|
||||
const profile = useMainStore((store) => store.profile)
|
||||
const timeOption = DateTime.TIME_SIMPLE
|
||||
timeOption.hour12 = true
|
||||
const [timeString, setTimeString] = useState(
|
||||
DateTime.now().setLocale("en-US").toLocaleString(timeOption),
|
||||
)
|
||||
useInterval(() => {
|
||||
setTimeString(DateTime.now().setLocale("en-US").toLocaleString(timeOption))
|
||||
}, 1000)
|
||||
return (
|
||||
<section className={"flex flex-col"}>
|
||||
{profile && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="flex gap-1.5 text-sm font-semibold">
|
||||
👋 Hi, {profile?.username}
|
||||
{profile?.login_ip && (
|
||||
<p className="font-medium opacity-45">from {profile?.login_ip}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!profile && <p className="text-sm font-semibold">{t("LoginFirst")}</p>}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-[13px] font-medium opacity-50">{t("CurrentTime")}</p>
|
||||
<p className="opacity-1 text-[13px] font-medium">{timeString}</p>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,46 +1,45 @@
|
||||
import { Button, ButtonProps } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Button, ButtonProps } from "@/components/ui/button"
|
||||
import { forwardRef, useState } from "react"
|
||||
import useSettings from "@/hooks/useSetting"
|
||||
import { ModelSettingResponse } from "@/types"
|
||||
import { Check, Clipboard } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { copyToClipboard } from "@/lib/utils"
|
||||
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { ModelSettingResponse } from "@/types"
|
||||
import i18next from "i18next"
|
||||
import { Check, Clipboard } from "lucide-react"
|
||||
import { forwardRef, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
enum OSTypes {
|
||||
Linux = 1,
|
||||
macOS,
|
||||
Windows
|
||||
Windows,
|
||||
}
|
||||
|
||||
export const InstallCommandsMenu = forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => {
|
||||
const [copy, setCopy] = useState(false);
|
||||
const settings = useSettings();
|
||||
const { t } = useTranslation();
|
||||
const [copy, setCopy] = useState(false)
|
||||
const settings = useSettings()
|
||||
const { t } = useTranslation()
|
||||
|
||||
const switchState = async (type: number) => {
|
||||
if (!copy) {
|
||||
try {
|
||||
setCopy(true);
|
||||
if (!settings) throw new Error("Settings is not found.");
|
||||
await copyToClipboard(generateCommand(type, settings) || '');
|
||||
setCopy(true)
|
||||
if (!settings) throw new Error("Settings is not found.")
|
||||
await copyToClipboard(generateCommand(type, settings) || "")
|
||||
} catch (e: Error | any) {
|
||||
console.error(e);
|
||||
console.error(e)
|
||||
toast(t("Error"), {
|
||||
description: e.message,
|
||||
})
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
setCopy(false);
|
||||
}, 2 * 1000);
|
||||
setCopy(false)
|
||||
}, 2 * 1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,32 +53,54 @@ export const InstallCommandsMenu = forwardRef<HTMLButtonElement, ButtonProps>((p
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem className="nezha-copy" onClick={async () => { switchState(OSTypes.Linux) }}>Linux</DropdownMenuItem>
|
||||
<DropdownMenuItem className="nezha-copy" onClick={async () => { switchState(OSTypes.macOS) }}>macOS</DropdownMenuItem>
|
||||
<DropdownMenuItem className="nezha-copy" onClick={async () => { switchState(OSTypes.Windows) }}>Windows</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="nezha-copy"
|
||||
onClick={async () => {
|
||||
switchState(OSTypes.Linux)
|
||||
}}
|
||||
>
|
||||
Linux
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="nezha-copy"
|
||||
onClick={async () => {
|
||||
switchState(OSTypes.macOS)
|
||||
}}
|
||||
>
|
||||
macOS
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="nezha-copy"
|
||||
onClick={async () => {
|
||||
switchState(OSTypes.Windows)
|
||||
}}
|
||||
>
|
||||
Windows
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
)
|
||||
})
|
||||
|
||||
const generateCommand = (type: number, { agent_secret_key, install_host, tls }: ModelSettingResponse) => {
|
||||
|
||||
if (!install_host)
|
||||
throw new Error(i18next.t("Results.InstallHostRequired"));
|
||||
const generateCommand = (
|
||||
type: number,
|
||||
{ agent_secret_key, install_host, tls }: ModelSettingResponse,
|
||||
) => {
|
||||
if (!install_host) throw new Error(i18next.t("Results.InstallHostRequired"))
|
||||
|
||||
const env = `NZ_SERVER=${install_host} NZ_TLS=${tls || false} NZ_CLIENT_SECRET=${agent_secret_key}`;
|
||||
const env_win = `$env:NZ_SERVER=\"${install_host}\";$env:NZ_TLS=\"${tls || false}\";$env:NZ_CLIENT_SECRET=\"${agent_secret_key}\";`;
|
||||
const env = `NZ_SERVER=${install_host} NZ_TLS=${tls || false} NZ_CLIENT_SECRET=${agent_secret_key}`
|
||||
const env_win = `$env:NZ_SERVER=\"${install_host}\";$env:NZ_TLS=\"${tls || false}\";$env:NZ_CLIENT_SECRET=\"${agent_secret_key}\";`
|
||||
|
||||
switch (type) {
|
||||
case OSTypes.Linux:
|
||||
case OSTypes.macOS: {
|
||||
return `curl -L https://raw.githubusercontent.com/nezhahq/scripts/main/agent/install.sh -o agent.sh && chmod +x agent.sh && env ${env} ./agent.sh`
|
||||
}
|
||||
case OSTypes.Windows: {
|
||||
return `${env_win} [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3 -bor [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12;set-ExecutionPolicy RemoteSigned;Invoke-WebRequest https://raw.githubusercontent.com/nezhahq/scripts/main/agent/install.ps1 -OutFile C:\install.ps1;powershell.exe C:\install.ps1`
|
||||
}
|
||||
default: {
|
||||
throw new Error(`Unknown OS: ${type}`);
|
||||
}
|
||||
case OSTypes.Linux:
|
||||
case OSTypes.macOS: {
|
||||
return `curl -L https://raw.githubusercontent.com/nezhahq/scripts/main/agent/install.sh -o agent.sh && chmod +x agent.sh && env ${env} ./agent.sh`
|
||||
}
|
||||
case OSTypes.Windows: {
|
||||
return `${env_win} [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3 -bor [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12;set-ExecutionPolicy RemoteSigned;Invoke-WebRequest https://raw.githubusercontent.com/nezhahq/scripts/main/agent/install.ps1 -OutFile C:\install.ps1;powershell.exe C:\install.ps1`
|
||||
}
|
||||
default: {
|
||||
throw new Error(`Unknown OS: ${type}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
|
||||
import { Theme, useTheme } from "@/components/theme-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -7,16 +6,15 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Theme, useTheme } from "@/components/theme-provider"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
export function ModeToggle() {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const { setTheme } = useTheme()
|
||||
|
||||
const toggleTheme = (theme: Theme) => {
|
||||
setTheme(theme);
|
||||
setTheme(theme)
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createNAT, updateNAT } from "@/api/nat"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -18,21 +18,20 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelNAT } from "@/types"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { createNAT, updateNAT } from "@/api/nat"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ModelNAT } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
interface NATCardProps {
|
||||
data?: ModelNAT;
|
||||
mutate: KeyedMutator<ModelNAT[]>;
|
||||
data?: ModelNAT
|
||||
mutate: KeyedMutator<ModelNAT[]>
|
||||
}
|
||||
|
||||
const natFormSchema = z.object({
|
||||
@@ -40,47 +39,44 @@ const natFormSchema = z.object({
|
||||
server_id: z.coerce.number().int(),
|
||||
host: z.string(),
|
||||
domain: z.string(),
|
||||
});
|
||||
})
|
||||
|
||||
export const NATCard: React.FC<NATCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof natFormSchema>>({
|
||||
resolver: zodResolver(natFormSchema),
|
||||
defaultValues: data ? data : {
|
||||
name: "",
|
||||
server_id: 0,
|
||||
host: "",
|
||||
domain: "",
|
||||
},
|
||||
defaultValues: data
|
||||
? data
|
||||
: {
|
||||
name: "",
|
||||
server_id: 0,
|
||||
host: "",
|
||||
domain: "",
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof natFormSchema>) => {
|
||||
data?.id ? await updateNAT(data.id, values) : await createNAT(values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
data?.id ? await updateNAT(data.id, values) : await createNAT(values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data?t("EditNAT"):t("CreateNAT")}</DialogTitle>
|
||||
<DialogTitle>{data ? t("EditNAT") : t("CreateNAT")}</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -92,10 +88,7 @@ export const NATCard: React.FC<NATCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="My NAT Profile"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="My NAT Profile" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -108,11 +101,7 @@ export const NATCard: React.FC<NATCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Server")} ID</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="1"
|
||||
{...field}
|
||||
/>
|
||||
<Input type="number" placeholder="1" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -156,7 +145,9 @@ export const NATCard: React.FC<NATCardProps> = ({ data, mutate }) => {
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,53 +1,69 @@
|
||||
import { ButtonProps } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { ButtonProps } from "@/components/ui/button"
|
||||
import { copyToClipboard } from "@/lib/utils"
|
||||
import { forwardRef, useState } from "react"
|
||||
import { IconButton } from "./xui/icon-button"
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { copyToClipboard } from "@/lib/utils";
|
||||
import { IconButton } from "./xui/icon-button"
|
||||
|
||||
interface NoteMenuProps extends ButtonProps {
|
||||
note: { private?: string, public?: string };
|
||||
note: { private?: string; public?: string }
|
||||
}
|
||||
|
||||
export const NoteMenu = forwardRef<HTMLButtonElement, NoteMenuProps>((props, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [copy, setCopy] = useState(false);
|
||||
const { t } = useTranslation()
|
||||
const [copy, setCopy] = useState(false)
|
||||
|
||||
const switchState = async (text?: string) => {
|
||||
if (!text) {
|
||||
toast("Warning", {
|
||||
description: "You didn't have any note."
|
||||
description: "You didn't have any note.",
|
||||
})
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
if (!copy) {
|
||||
setCopy(true);
|
||||
await copyToClipboard(text);
|
||||
setCopy(true)
|
||||
await copyToClipboard(text)
|
||||
setTimeout(() => {
|
||||
setCopy(false);
|
||||
}, 2 * 1000);
|
||||
setCopy(false)
|
||||
}, 2 * 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<IconButton {...props} ref={ref} variant="outline" size="icon" icon={
|
||||
copy ? "check" : "clipboard"
|
||||
} />
|
||||
<IconButton
|
||||
{...props}
|
||||
ref={ref}
|
||||
variant="outline"
|
||||
size="icon"
|
||||
icon={copy ? "check" : "clipboard"}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={() => { switchState(props.note.private) }}>{t("Private")}</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => { switchState(props.note.public) }}>{t("Public")}</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
switchState(props.note.private)
|
||||
}}
|
||||
>
|
||||
{t("Private")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
switchState(props.note.public)
|
||||
}}
|
||||
>
|
||||
{t("Public")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createNotificationGroup, updateNotificationGroup } from "@/api/notification-group"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -18,76 +18,76 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelNotificationGroupResponseItem } from "@/types"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { createNotificationGroup, updateNotificationGroup } from "@/api/notification-group"
|
||||
import { MultiSelect } from "@/components/xui/multi-select"
|
||||
import { useNotification } from "@/hooks/useNotfication"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ModelNotificationGroupResponseItem } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
interface NotificationGroupCardProps {
|
||||
data?: ModelNotificationGroupResponseItem;
|
||||
mutate: KeyedMutator<ModelNotificationGroupResponseItem[]>;
|
||||
data?: ModelNotificationGroupResponseItem
|
||||
mutate: KeyedMutator<ModelNotificationGroupResponseItem[]>
|
||||
}
|
||||
|
||||
const notificationGroupFormSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
notifications: z.array(z.number()),
|
||||
});
|
||||
})
|
||||
|
||||
export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof notificationGroupFormSchema>>({
|
||||
resolver: zodResolver(notificationGroupFormSchema),
|
||||
defaultValues: data ? {
|
||||
name: data.group.name,
|
||||
notifications: data.notifications,
|
||||
} : {
|
||||
name: "",
|
||||
notifications: [],
|
||||
},
|
||||
defaultValues: data
|
||||
? {
|
||||
name: data.group.name,
|
||||
notifications: data.notifications,
|
||||
}
|
||||
: {
|
||||
name: "",
|
||||
notifications: [],
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof notificationGroupFormSchema>) => {
|
||||
data?.group.id ? await updateNotificationGroup(data.group.id, values) : await createNotificationGroup(values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
data?.group.id
|
||||
? await updateNotificationGroup(data.group.id, values)
|
||||
: await createNotificationGroup(values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
const { notifiers } = useNotification();
|
||||
const notifierList = notifiers?.map(n => ({
|
||||
const { notifiers } = useNotification()
|
||||
const notifierList = notifiers?.map((n) => ({
|
||||
value: `${n.id}`,
|
||||
label: n.name,
|
||||
})) || [{ value: "", label: "" }];
|
||||
})) || [{ value: "", label: "" }]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data ? t("EditNotifierGroup") : t("CreateNotifierGroup")}</DialogTitle>
|
||||
<DialogTitle>
|
||||
{data ? t("EditNotifierGroup") : t("CreateNotifierGroup")}
|
||||
</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -99,10 +99,7 @@ export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ da
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Group Name"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="Group Name" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -116,9 +113,9 @@ export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ da
|
||||
<FormLabel>{t("Notification")}</FormLabel>
|
||||
<MultiSelect
|
||||
options={notifierList}
|
||||
onValueChange={e => {
|
||||
const arr = e.map(Number);
|
||||
field.onChange(arr);
|
||||
onValueChange={(e) => {
|
||||
const arr = e.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
defaultValue={field.value?.map(String)}
|
||||
/>
|
||||
@@ -132,7 +129,9 @@ export const NotificationGroupCard: React.FC<NotificationGroupCardProps> = ({ da
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import {
|
||||
Tabs,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { Link, useLocation } from "react-router-dom"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
|
||||
export const NotificationTab = ({ className }: { className?: string }) => {
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation()
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<Tabs defaultValue={location.pathname} className={className}>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createNotification, updateNotification } from "@/api/notification"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
@@ -9,14 +11,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -25,26 +19,32 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelNotification } from "@/types"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { nrequestTypes, nrequestMethods } from "@/types"
|
||||
import { createNotification, updateNotification } from "@/api/notification"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ModelNotification } from "@/types"
|
||||
import { nrequestMethods, nrequestTypes } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
import { Textarea } from "./ui/textarea"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface NotifierCardProps {
|
||||
data?: ModelNotification;
|
||||
mutate: KeyedMutator<ModelNotification[]>;
|
||||
data?: ModelNotification
|
||||
mutate: KeyedMutator<ModelNotification[]>
|
||||
}
|
||||
|
||||
const notificationFormSchema = z.object({
|
||||
@@ -56,49 +56,48 @@ const notificationFormSchema = z.object({
|
||||
request_body: z.string(),
|
||||
verify_tls: asOptionalField(z.boolean()),
|
||||
skip_check: asOptionalField(z.boolean()),
|
||||
});
|
||||
})
|
||||
|
||||
export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof notificationFormSchema>>({
|
||||
resolver: zodResolver(notificationFormSchema),
|
||||
defaultValues: data ? data : {
|
||||
name: "",
|
||||
url: "",
|
||||
request_method: 1,
|
||||
request_type: 1,
|
||||
request_header: "",
|
||||
request_body: "",
|
||||
},
|
||||
defaultValues: data
|
||||
? data
|
||||
: {
|
||||
name: "",
|
||||
url: "",
|
||||
request_method: 1,
|
||||
request_type: 1,
|
||||
request_header: "",
|
||||
request_body: "",
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof notificationFormSchema>) => {
|
||||
data?.id ? await updateNotification(data.id, values) : await createNotification(values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
data?.id ? await updateNotification(data.id, values) : await createNotification(values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data?t("EditNotifier"):t("CreateNotifier")}</DialogTitle>
|
||||
<DialogTitle>
|
||||
{data ? t("EditNotifier") : t("CreateNotifier")}
|
||||
</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -110,10 +109,7 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="My Notifier"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="My Notifier" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -126,9 +122,7 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
/>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -140,16 +134,23 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("RequestMethod")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Request Method" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(nrequestMethods).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
))}
|
||||
{Object.entries(nrequestMethods).map(
|
||||
([k, v]) => (
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
),
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
@@ -162,7 +163,10 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("Type")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Request Type" />
|
||||
@@ -170,7 +174,9 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(nrequestTypes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -223,7 +229,9 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("VerifyTLS")}</Label>
|
||||
<Label className="text-sm">
|
||||
{t("VerifyTLS")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -241,7 +249,9 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("DoNotSendTestMessage")}</Label>
|
||||
<Label className="text-sm">
|
||||
{t("DoNotSendTestMessage")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -254,7 +264,9 @@ export const NotifierCard: React.FC<NotifierCardProps> = ({ data, mutate }) => {
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getProfile, updateProfile } from "@/api/user"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -18,54 +18,53 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { getProfile, updateProfile } from "@/api/user"
|
||||
import { useState } from "react"
|
||||
import { useMainStore } from "@/hooks/useMainStore"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod"
|
||||
|
||||
const profileFormSchema = z.object({
|
||||
original_password: z.string().min(5).max(72),
|
||||
new_password: z.string().min(8).max(72),
|
||||
new_username: z.string().min(1).max(32),
|
||||
});
|
||||
})
|
||||
|
||||
export const ProfileCard = ({ className }: { className: string }) => {
|
||||
const { t } = useTranslation();
|
||||
const { profile, setProfile } = useMainStore();
|
||||
const { t } = useTranslation()
|
||||
const { profile, setProfile } = useMainStore()
|
||||
|
||||
const form = useForm<z.infer<typeof profileFormSchema>>({
|
||||
resolver: zodResolver(profileFormSchema),
|
||||
defaultValues: {
|
||||
original_password: '',
|
||||
new_password: '',
|
||||
original_password: "",
|
||||
new_password: "",
|
||||
new_username: profile?.username,
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof profileFormSchema>) => {
|
||||
try {
|
||||
await updateProfile(values);
|
||||
await updateProfile(values)
|
||||
} catch (e) {
|
||||
toast(t("Error"), {
|
||||
description: `${e}`,
|
||||
})
|
||||
return;
|
||||
return
|
||||
}
|
||||
const profile = await getProfile();
|
||||
setProfile(profile);
|
||||
setOpen(false);
|
||||
form.reset();
|
||||
const profile = await getProfile()
|
||||
setProfile(profile)
|
||||
setOpen(false)
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -91,10 +90,7 @@ export const ProfileCard = ({ className }: { className: string }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("NewUsername")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="username"
|
||||
{...field}
|
||||
/>
|
||||
<Input autoComplete="username" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -107,10 +103,7 @@ export const ProfileCard = ({ className }: { className: string }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("OriginalPassword")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
autoComplete="current-password"
|
||||
{...field}
|
||||
/>
|
||||
<Input autoComplete="current-password" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -123,9 +116,7 @@ export const ProfileCard = ({ className }: { className: string }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("NewPassword")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
/>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -138,7 +129,9 @@ export const ProfileCard = ({ className }: { className: string }) => {
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createServerGroup, updateServerGroup } from "@/api/server-group"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -18,76 +18,76 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelServerGroupResponseItem } from "@/types"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { createServerGroup, updateServerGroup } from "@/api/server-group"
|
||||
import { MultiSelect } from "@/components/xui/multi-select"
|
||||
import { useServer } from "@/hooks/useServer"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ModelServerGroupResponseItem } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
interface ServerGroupCardProps {
|
||||
data?: ModelServerGroupResponseItem;
|
||||
mutate: KeyedMutator<ModelServerGroupResponseItem[]>;
|
||||
data?: ModelServerGroupResponseItem
|
||||
mutate: KeyedMutator<ModelServerGroupResponseItem[]>
|
||||
}
|
||||
|
||||
const serverGroupFormSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
servers: z.array(z.number()),
|
||||
});
|
||||
})
|
||||
|
||||
export const ServerGroupCard: React.FC<ServerGroupCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof serverGroupFormSchema>>({
|
||||
resolver: zodResolver(serverGroupFormSchema),
|
||||
defaultValues: data ? {
|
||||
name: data.group.name,
|
||||
servers: data.servers,
|
||||
} : {
|
||||
name: "",
|
||||
servers: [],
|
||||
},
|
||||
defaultValues: data
|
||||
? {
|
||||
name: data.group.name,
|
||||
servers: data.servers,
|
||||
}
|
||||
: {
|
||||
name: "",
|
||||
servers: [],
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof serverGroupFormSchema>) => {
|
||||
data?.group.id ? await updateServerGroup(data.group.id, values) : await createServerGroup(values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
data?.group.id
|
||||
? await updateServerGroup(data.group.id, values)
|
||||
: await createServerGroup(values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
const { servers } = useServer();
|
||||
const serverList = servers?.map(s => ({
|
||||
const { servers } = useServer()
|
||||
const serverList = servers?.map((s) => ({
|
||||
value: `${s.id}`,
|
||||
label: s.name,
|
||||
})) || [{ value: "", label: "" }];
|
||||
})) || [{ value: "", label: "" }]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data? t("EditServerGroup"):t("CreateServerGroup")}</DialogTitle>
|
||||
<DialogTitle>
|
||||
{data ? t("EditServerGroup") : t("CreateServerGroup")}
|
||||
</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -99,10 +99,7 @@ export const ServerGroupCard: React.FC<ServerGroupCardProps> = ({ data, mutate }
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Group Name"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="Group Name" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -117,9 +114,9 @@ export const ServerGroupCard: React.FC<ServerGroupCardProps> = ({ data, mutate }
|
||||
<FormControl>
|
||||
<MultiSelect
|
||||
options={serverList}
|
||||
onValueChange={e => {
|
||||
const arr = e.map(Number);
|
||||
field.onChange(arr);
|
||||
onValueChange={(e) => {
|
||||
const arr = e.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
defaultValue={field.value?.map(String)}
|
||||
/>
|
||||
@@ -134,7 +131,9 @@ export const ServerGroupCard: React.FC<ServerGroupCardProps> = ({ data, mutate }
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { updateServer } from "@/api/server"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
@@ -9,7 +11,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -18,25 +19,24 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelServer } from "@/types"
|
||||
import { updateServer } from "@/api/server"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ModelServer } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
interface ServerCardProps {
|
||||
data: ModelServer;
|
||||
mutate: KeyedMutator<ModelServer[]>;
|
||||
data: ModelServer
|
||||
mutate: KeyedMutator<ModelServer[]>
|
||||
}
|
||||
|
||||
const serverFormSchema = z.object({
|
||||
@@ -47,25 +47,25 @@ const serverFormSchema = z.object({
|
||||
hide_for_guest: asOptionalField(z.boolean()),
|
||||
enable_ddns: asOptionalField(z.boolean()),
|
||||
ddns_profiles: asOptionalField(z.array(z.number())),
|
||||
});
|
||||
})
|
||||
|
||||
export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof serverFormSchema>>({
|
||||
resolver: zodResolver(serverFormSchema),
|
||||
defaultValues: data,
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof serverFormSchema>) => {
|
||||
await updateServer(data.id, values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
await updateServer(data.id, values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -77,7 +77,7 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("EditServer") }</DialogTitle>
|
||||
<DialogTitle>{t("EditServer")}</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -89,10 +89,7 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="My Server"
|
||||
{...field}
|
||||
/>
|
||||
<Input placeholder="My Server" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -105,11 +102,7 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Weight")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="0"
|
||||
{...field}
|
||||
/>
|
||||
<Input type="number" placeholder="0" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -120,16 +113,20 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
name="ddns_profiles"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("DDNSProfiles") + t("SeparateWithComma")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("DDNSProfiles") + t("SeparateWithComma")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="1,2,3"
|
||||
{...field}
|
||||
value={conv.arrToStr(field.value || [])}
|
||||
onChange={e => {
|
||||
onChange={(e) => {
|
||||
console.log(field.value)
|
||||
const arr = conv.strToArr(e.target.value).map(Number);
|
||||
field.onChange(arr);
|
||||
const arr = conv
|
||||
.strToArr(e.target.value)
|
||||
.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -148,7 +145,9 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("Enable") + t("DDNS") }</Label>
|
||||
<Label className="text-sm">
|
||||
{t("Enable") + t("DDNS")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -166,7 +165,9 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("HideForGuest")}</Label>
|
||||
<Label className="text-sm">
|
||||
{t("HideForGuest")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -180,10 +181,7 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Private") + t("Note")}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className="resize-none"
|
||||
{...field}
|
||||
/>
|
||||
<Textarea className="resize-none" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -196,10 +194,7 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Public") + t("Note")}</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className="resize-y"
|
||||
{...field}
|
||||
/>
|
||||
<Textarea className="resize-y" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -211,7 +206,9 @@ export const ServerCard: React.FC<ServerCardProps> = ({ data, mutate }) => {
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Submit")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Submit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createService, updateService } from "@/api/service"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
@@ -9,14 +11,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -25,30 +19,36 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelService } from "@/types"
|
||||
import { createService, updateService } from "@/api/service"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { serviceTypes, serviceCoverageTypes } from "@/types"
|
||||
import { MultiSelect } from "./xui/multi-select"
|
||||
import { Combobox } from "./ui/combobox"
|
||||
import { useServer } from "@/hooks/useServer"
|
||||
import { useNotification } from "@/hooks/useNotfication"
|
||||
import { useServer } from "@/hooks/useServer"
|
||||
import { conv } from "@/lib/utils"
|
||||
import { asOptionalField } from "@/lib/utils"
|
||||
import { ModelService } from "@/types"
|
||||
import { serviceCoverageTypes, serviceTypes } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Combobox } from "./ui/combobox"
|
||||
import { MultiSelect } from "./xui/multi-select"
|
||||
|
||||
interface ServiceCardProps {
|
||||
data?: ModelService;
|
||||
mutate: KeyedMutator<ModelService[]>;
|
||||
data?: ModelService
|
||||
mutate: KeyedMutator<ModelService[]>
|
||||
}
|
||||
|
||||
const serviceFormSchema = z.object({
|
||||
@@ -68,72 +68,73 @@ const serviceFormSchema = z.object({
|
||||
skip_servers_raw: z.array(z.string()),
|
||||
target: z.string(),
|
||||
type: z.coerce.number().int().min(0),
|
||||
});
|
||||
})
|
||||
|
||||
export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof serviceFormSchema>>({
|
||||
resolver: zodResolver(serviceFormSchema),
|
||||
defaultValues: data ? {
|
||||
...data,
|
||||
skip_servers_raw: conv.recordToStrArr(data.skip_servers ? data.skip_servers : {}),
|
||||
} : {
|
||||
type: 1,
|
||||
cover: 0,
|
||||
name: "",
|
||||
target: "",
|
||||
max_latency: 0.0,
|
||||
min_latency: 0.0,
|
||||
duration: 30,
|
||||
notification_group_id: 0,
|
||||
fail_trigger_tasks: [],
|
||||
recover_trigger_tasks: [],
|
||||
skip_servers: {},
|
||||
skip_servers_raw: [],
|
||||
},
|
||||
defaultValues: data
|
||||
? {
|
||||
...data,
|
||||
skip_servers_raw: conv.recordToStrArr(data.skip_servers ? data.skip_servers : {}),
|
||||
}
|
||||
: {
|
||||
type: 1,
|
||||
cover: 0,
|
||||
name: "",
|
||||
target: "",
|
||||
max_latency: 0.0,
|
||||
min_latency: 0.0,
|
||||
duration: 30,
|
||||
notification_group_id: 0,
|
||||
fail_trigger_tasks: [],
|
||||
recover_trigger_tasks: [],
|
||||
skip_servers: {},
|
||||
skip_servers_raw: [],
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof serviceFormSchema>) => {
|
||||
values.skip_servers = conv.arrToRecord(values.skip_servers_raw);
|
||||
const { skip_servers_raw, ...requiredFields } = values;
|
||||
data?.id ? await updateService(data.id, requiredFields) : await createService(requiredFields);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
values.skip_servers = conv.arrToRecord(values.skip_servers_raw)
|
||||
const { skip_servers_raw, ...requiredFields } = values
|
||||
data?.id
|
||||
? await updateService(data.id, requiredFields)
|
||||
: await createService(requiredFields)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
const { servers } = useServer();
|
||||
const serverList = servers?.map(s => ({
|
||||
const { servers } = useServer()
|
||||
const serverList = servers?.map((s) => ({
|
||||
value: `${s.id}`,
|
||||
label: s.name,
|
||||
})) || [{ value: "", label: "" }];
|
||||
})) || [{ value: "", label: "" }]
|
||||
|
||||
const { notifierGroup } = useNotification();
|
||||
const ngroupList = notifierGroup?.map(ng => ({
|
||||
const { notifierGroup } = useNotification()
|
||||
const ngroupList = notifierGroup?.map((ng) => ({
|
||||
value: `${ng.group.id}`,
|
||||
label: ng.group.name,
|
||||
})) || [{ value: "", label: "" }];
|
||||
})) || [{ value: "", label: "" }]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{data
|
||||
?
|
||||
<IconButton variant="outline" icon="edit" />
|
||||
:
|
||||
<IconButton icon="plus" />
|
||||
}
|
||||
{data ? <IconButton variant="outline" icon="edit" /> : <IconButton icon="plus" />}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<ScrollArea className="max-h-[calc(100dvh-5rem)] p-3">
|
||||
<div className="items-center mx-1">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{data?t("EditService"):t("CreateService")}</DialogTitle>
|
||||
<DialogTitle>
|
||||
{data ? t("EditService") : t("CreateService")}
|
||||
</DialogTitle>
|
||||
<DialogDescription />
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
@@ -176,7 +177,10 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("Type")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select service type" />
|
||||
@@ -184,7 +188,9 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(serviceTypes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
@@ -203,7 +209,9 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("ShowInService")}</Label>
|
||||
<Label className="text-sm">
|
||||
{t("ShowInService")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -217,11 +225,7 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Interval")} (s)</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="30"
|
||||
{...field}
|
||||
/>
|
||||
<Input type="number" placeholder="30" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -233,16 +237,23 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("Coverage")}</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={`${field.value}`}>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={`${field.value}`}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(serviceCoverageTypes).map(([k, v]) => (
|
||||
<SelectItem key={k} value={k}>{v}</SelectItem>
|
||||
))}
|
||||
{Object.entries(serviceCoverageTypes).map(
|
||||
([k, v]) => (
|
||||
<SelectItem key={k} value={k}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
),
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
@@ -295,7 +306,9 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("EnableFailureNotification")}</Label>
|
||||
<Label className="text-sm">
|
||||
{t("EnableFailureNotification")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -347,7 +360,9 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("EnableLatencyNotification")}</Label>
|
||||
<Label className="text-sm">
|
||||
{t("EnableLatencyNotification")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -365,7 +380,9 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<Label className="text-sm">{t("EnableTriggerTask")}</Label>
|
||||
<Label className="text-sm">
|
||||
{t("EnableTriggerTask")}
|
||||
</Label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -377,15 +394,20 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
name="fail_trigger_tasks"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("TasksToTriggerOnAlert") + t("SeparateWithComma")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("TasksToTriggerOnAlert") +
|
||||
t("SeparateWithComma")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="1,2,3"
|
||||
{...field}
|
||||
value={conv.arrToStr(field.value ?? [])}
|
||||
onChange={e => {
|
||||
const arr = conv.strToArr(e.target.value).map(Number);
|
||||
field.onChange(arr);
|
||||
onChange={(e) => {
|
||||
const arr = conv
|
||||
.strToArr(e.target.value)
|
||||
.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -398,15 +420,20 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
name="recover_trigger_tasks"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("TasksToTriggerAfterRecovery") + t("SeparateWithComma")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("TasksToTriggerAfterRecovery") +
|
||||
t("SeparateWithComma")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="1,2,3"
|
||||
{...field}
|
||||
value={conv.arrToStr(field.value ?? [])}
|
||||
onChange={e => {
|
||||
const arr = conv.strToArr(e.target.value).map(Number);
|
||||
field.onChange(arr);
|
||||
onChange={(e) => {
|
||||
const arr = conv
|
||||
.strToArr(e.target.value)
|
||||
.map(Number)
|
||||
field.onChange(arr)
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
@@ -420,7 +447,9 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ data, mutate }) => {
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Submit")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Submit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
import {
|
||||
Tabs,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { Link, useLocation } from "react-router-dom"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export const SettingsTab = ({ className }: { className?: string }) => {
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation()
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<Tabs defaultValue={location.pathname} className={className}>
|
||||
|
||||
@@ -7,137 +7,144 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import { AttachAddon } from "@xterm/addon-attach";
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import { useRef, useEffect, useState, useMemo } from "react";
|
||||
import { sleep } from "@/lib/utils";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Button } from "./ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { FMCard } from "./fm";
|
||||
import useTerminal from "@/hooks/useTerminal";
|
||||
import { IconButton } from "./xui/icon-button";
|
||||
import useTerminal from "@/hooks/useTerminal"
|
||||
import { sleep } from "@/lib/utils"
|
||||
import { AttachAddon } from "@xterm/addon-attach"
|
||||
import { FitAddon } from "@xterm/addon-fit"
|
||||
import { Terminal } from "@xterm/xterm"
|
||||
import "@xterm/xterm/css/xterm.css"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import { useParams } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { FMCard } from "./fm"
|
||||
import { Button } from "./ui/button"
|
||||
import { IconButton } from "./xui/icon-button"
|
||||
|
||||
interface XtermProps {
|
||||
wsUrl: string;
|
||||
setClose: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
wsUrl: string
|
||||
setClose: React.Dispatch<React.SetStateAction<boolean>>
|
||||
}
|
||||
|
||||
const XtermComponent: React.FC<XtermProps & JSX.IntrinsicElements["div"]> = ({ wsUrl, setClose, ...props }) => {
|
||||
const terminalIdRef = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const XtermComponent: React.FC<XtermProps & JSX.IntrinsicElements["div"]> = ({
|
||||
wsUrl,
|
||||
setClose,
|
||||
...props
|
||||
}) => {
|
||||
const terminalIdRef = useRef<HTMLDivElement>(null)
|
||||
const terminalRef = useRef<Terminal | null>(null)
|
||||
const wsRef = useRef<WebSocket | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
wsRef.current?.close();
|
||||
terminalRef.current?.dispose();
|
||||
};
|
||||
}, []);
|
||||
wsRef.current?.close()
|
||||
terminalRef.current?.dispose()
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
terminalRef.current = new Terminal({
|
||||
cursorBlink: true,
|
||||
fontSize: 16,
|
||||
});
|
||||
const ws = new WebSocket(wsUrl);
|
||||
wsRef.current = ws;
|
||||
ws.binaryType = "arraybuffer";
|
||||
})
|
||||
const ws = new WebSocket(wsUrl)
|
||||
wsRef.current = ws
|
||||
ws.binaryType = "arraybuffer"
|
||||
ws.onopen = () => {
|
||||
onResize();
|
||||
onResize()
|
||||
}
|
||||
ws.onclose = () => {
|
||||
terminalRef.current?.dispose();
|
||||
setClose(true);
|
||||
terminalRef.current?.dispose()
|
||||
setClose(true)
|
||||
}
|
||||
ws.onerror = (e) => {
|
||||
console.error(e);
|
||||
console.error(e)
|
||||
toast("Websocket error", {
|
||||
description: "View console for details.",
|
||||
})
|
||||
}
|
||||
}, [wsUrl]);
|
||||
}, [wsUrl])
|
||||
|
||||
|
||||
const fitAddon = useRef(new FitAddon()).current;
|
||||
const sendResize = useRef(false);
|
||||
const fitAddon = useRef(new FitAddon()).current
|
||||
const sendResize = useRef(false)
|
||||
|
||||
const doResize = () => {
|
||||
if (!terminalIdRef.current) return;
|
||||
if (!terminalIdRef.current) return
|
||||
|
||||
fitAddon.fit();
|
||||
fitAddon.fit()
|
||||
|
||||
const dimensions = fitAddon.proposeDimensions();
|
||||
const dimensions = fitAddon.proposeDimensions()
|
||||
|
||||
if (dimensions) {
|
||||
const prefix = new Int8Array([1]);
|
||||
const resizeMessage = new TextEncoder().encode(JSON.stringify({
|
||||
Rows: dimensions.rows,
|
||||
Cols: dimensions.cols,
|
||||
}));
|
||||
const prefix = new Int8Array([1])
|
||||
const resizeMessage = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
Rows: dimensions.rows,
|
||||
Cols: dimensions.cols,
|
||||
}),
|
||||
)
|
||||
|
||||
const msg = new Int8Array(prefix.length + resizeMessage.length);
|
||||
msg.set(prefix);
|
||||
msg.set(resizeMessage, prefix.length);
|
||||
const msg = new Int8Array(prefix.length + resizeMessage.length)
|
||||
msg.set(prefix)
|
||||
msg.set(resizeMessage, prefix.length)
|
||||
|
||||
wsRef.current?.send(msg);
|
||||
wsRef.current?.send(msg)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const onResize = async () => {
|
||||
if (sendResize.current) return;
|
||||
if (sendResize.current) return
|
||||
|
||||
sendResize.current = true;
|
||||
sendResize.current = true
|
||||
try {
|
||||
await sleep(1500);
|
||||
doResize();
|
||||
await sleep(1500)
|
||||
doResize()
|
||||
} catch (error) {
|
||||
console.error('resize error', error);
|
||||
console.error("resize error", error)
|
||||
} finally {
|
||||
sendResize.current = false;
|
||||
sendResize.current = false
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!wsRef.current || !terminalIdRef.current || !terminalRef.current) return;
|
||||
const attachAddon = new AttachAddon(wsRef.current);
|
||||
terminalRef.current.loadAddon(attachAddon);
|
||||
terminalRef.current.loadAddon(fitAddon);
|
||||
terminalRef.current.open(terminalIdRef.current);
|
||||
window.addEventListener('resize', onResize);
|
||||
if (!wsRef.current || !terminalIdRef.current || !terminalRef.current) return
|
||||
const attachAddon = new AttachAddon(wsRef.current)
|
||||
terminalRef.current.loadAddon(attachAddon)
|
||||
terminalRef.current.loadAddon(fitAddon)
|
||||
terminalRef.current.open(terminalIdRef.current)
|
||||
window.addEventListener("resize", onResize)
|
||||
return () => {
|
||||
window.removeEventListener('resize', onResize);
|
||||
window.removeEventListener("resize", onResize)
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
wsRef.current.close()
|
||||
}
|
||||
};
|
||||
}, [wsRef.current, terminalRef.current, terminalIdRef.current]);
|
||||
}
|
||||
}, [wsRef.current, terminalRef.current, terminalIdRef.current])
|
||||
|
||||
return <div ref={terminalIdRef} {...props} />;
|
||||
};
|
||||
return <div ref={terminalIdRef} {...props} />
|
||||
}
|
||||
|
||||
export const TerminalPage = () => {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [open, setOpen] = useState(false);
|
||||
const terminal = useTerminal(id ? parseInt(id) : undefined);
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const [open, setOpen] = useState(false)
|
||||
const terminal = useTerminal(id ? parseInt(id) : undefined)
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<h1 className="flex-1 text-3xl font-bold tracking-tight">
|
||||
{`Terminal (${id})`}
|
||||
</h1>
|
||||
<h1 className="flex-1 text-3xl font-bold tracking-tight">{`Terminal (${id})`}</h1>
|
||||
<div className="flex-2 flex ml-auto gap-2">
|
||||
<FMCard id={id} />
|
||||
</div>
|
||||
</div>
|
||||
{terminal?.session_id
|
||||
?
|
||||
<XtermComponent className="max-h-[60%] mb-5" wsUrl={`/api/v1/ws/terminal/${terminal?.session_id}`} setClose={setOpen} />
|
||||
:
|
||||
{terminal?.session_id ? (
|
||||
<XtermComponent
|
||||
className="max-h-[60%] mb-5"
|
||||
wsUrl={`/api/v1/ws/terminal/${terminal?.session_id}`}
|
||||
setClose={setOpen}
|
||||
/>
|
||||
) : (
|
||||
<p>The server does not exist, or have not been connected yet.</p>
|
||||
}
|
||||
)}
|
||||
<AlertDialog open={open} onOpenChange={setOpen}>
|
||||
<AlertDialogContent className="sm:max-w-lg">
|
||||
<AlertDialogHeader>
|
||||
@@ -148,9 +155,7 @@ export const TerminalPage = () => {
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogAction asChild>
|
||||
<Button onClick={window.close}>
|
||||
Close
|
||||
</Button>
|
||||
<Button onClick={window.close}>Close</Button>
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
@@ -161,10 +166,8 @@ export const TerminalPage = () => {
|
||||
|
||||
export const TerminalButton = ({ id }: { id: number }) => {
|
||||
const handleOpenNewTab = () => {
|
||||
window.open(`/dashboard/terminal/${id}`, '_blank');
|
||||
};
|
||||
window.open(`/dashboard/terminal/${id}`, "_blank")
|
||||
}
|
||||
|
||||
return (
|
||||
<IconButton variant="outline" icon="terminal" onClick={handleOpenNewTab} />
|
||||
)
|
||||
return <IconButton variant="outline" icon="terminal" onClick={handleOpenNewTab} />
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ export function ThemeProvider({
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -36,8 +36,7 @@ export function ThemeProvider({
|
||||
root.classList.remove("light", "dark")
|
||||
|
||||
if (theme === "system") {
|
||||
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
|
||||
.matches
|
||||
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light"
|
||||
|
||||
@@ -66,8 +65,7 @@ export function ThemeProvider({
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext)
|
||||
|
||||
if (context === undefined)
|
||||
throw new Error("useTheme must be used within a ThemeProvider")
|
||||
if (context === undefined) throw new Error("useTheme must be used within a ThemeProvider")
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import * as React from "react"
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||
import * as React from "react"
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.Root
|
||||
|
||||
@@ -11,129 +10,105 @@ const AlertDialogTrigger = AlertDialogPrimitive.Trigger
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
<AlertDialogPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
))
|
||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
))
|
||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
|
||||
|
||||
const AlertDialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-2 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
|
||||
)
|
||||
AlertDialogHeader.displayName = "AlertDialogHeader"
|
||||
|
||||
const AlertDialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
AlertDialogFooter.displayName = "AlertDialogFooter"
|
||||
|
||||
const AlertDialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
<AlertDialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
|
||||
|
||||
const AlertDialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
<AlertDialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogDescription.displayName =
|
||||
AlertDialogPrimitive.Description.displayName
|
||||
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName
|
||||
|
||||
const AlertDialogAction = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Action
|
||||
ref={ref}
|
||||
className={cn(buttonVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
|
||||
))
|
||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
|
||||
|
||||
const AlertDialogCancel = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn(
|
||||
buttonVariants({ variant: "outline" }),
|
||||
"mt-2 sm:mt-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
}
|
||||
|
||||
@@ -1,47 +1,43 @@
|
||||
import * as React from "react"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
import * as React from "react"
|
||||
|
||||
const Avatar = React.forwardRef<
|
||||
React.ElementRef<typeof AvatarPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
|
||||
React.ElementRef<typeof AvatarPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AvatarPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<AvatarPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Avatar.displayName = AvatarPrimitive.Root.displayName
|
||||
|
||||
const AvatarImage = React.forwardRef<
|
||||
React.ElementRef<typeof AvatarPrimitive.Image>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
|
||||
React.ElementRef<typeof AvatarPrimitive.Image>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AvatarPrimitive.Image
|
||||
ref={ref}
|
||||
className={cn("aspect-square h-full w-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
<AvatarPrimitive.Image
|
||||
ref={ref}
|
||||
className={cn("aspect-square h-full w-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AvatarImage.displayName = AvatarPrimitive.Image.displayName
|
||||
|
||||
const AvatarFallback = React.forwardRef<
|
||||
React.ElementRef<typeof AvatarPrimitive.Fallback>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
|
||||
React.ElementRef<typeof AvatarPrimitive.Fallback>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AvatarPrimitive.Fallback
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full items-center justify-center rounded-full bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<AvatarPrimitive.Fallback
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full items-center justify-center rounded-full bg-muted",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
|
||||
|
||||
|
||||
@@ -1,36 +1,33 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { type VariantProps, cva } from "class-variance-authority"
|
||||
import * as React from "react"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
)
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
|
||||
@@ -1,115 +1,100 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
const Breadcrumb = React.forwardRef<
|
||||
HTMLElement,
|
||||
React.ComponentPropsWithoutRef<"nav"> & {
|
||||
separator?: React.ReactNode
|
||||
}
|
||||
HTMLElement,
|
||||
React.ComponentPropsWithoutRef<"nav"> & {
|
||||
separator?: React.ReactNode
|
||||
}
|
||||
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
|
||||
Breadcrumb.displayName = "Breadcrumb"
|
||||
|
||||
const BreadcrumbList = React.forwardRef<
|
||||
HTMLOListElement,
|
||||
React.ComponentPropsWithoutRef<"ol">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ol
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const BreadcrumbList = React.forwardRef<HTMLOListElement, React.ComponentPropsWithoutRef<"ol">>(
|
||||
({ className, ...props }, ref) => (
|
||||
<ol
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
)
|
||||
BreadcrumbList.displayName = "BreadcrumbList"
|
||||
|
||||
const BreadcrumbItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentPropsWithoutRef<"li">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<li
|
||||
ref={ref}
|
||||
className={cn("inline-flex items-center gap-1.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const BreadcrumbItem = React.forwardRef<HTMLLIElement, React.ComponentPropsWithoutRef<"li">>(
|
||||
({ className, ...props }, ref) => (
|
||||
<li ref={ref} className={cn("inline-flex items-center gap-1.5", className)} {...props} />
|
||||
),
|
||||
)
|
||||
BreadcrumbItem.displayName = "BreadcrumbItem"
|
||||
|
||||
const BreadcrumbLink = React.forwardRef<
|
||||
HTMLAnchorElement,
|
||||
React.ComponentPropsWithoutRef<"a"> & {
|
||||
asChild?: boolean
|
||||
}
|
||||
HTMLAnchorElement,
|
||||
React.ComponentPropsWithoutRef<"a"> & {
|
||||
asChild?: boolean
|
||||
}
|
||||
>(({ asChild, className, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
className={cn("transition-colors hover:text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
className={cn("transition-colors hover:text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
BreadcrumbLink.displayName = "BreadcrumbLink"
|
||||
|
||||
const BreadcrumbPage = React.forwardRef<
|
||||
HTMLSpanElement,
|
||||
React.ComponentPropsWithoutRef<"span">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<span
|
||||
ref={ref}
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("font-normal text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const BreadcrumbPage = React.forwardRef<HTMLSpanElement, React.ComponentPropsWithoutRef<"span">>(
|
||||
({ className, ...props }, ref) => (
|
||||
<span
|
||||
ref={ref}
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("font-normal text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
)
|
||||
BreadcrumbPage.displayName = "BreadcrumbPage"
|
||||
|
||||
const BreadcrumbSeparator = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) => (
|
||||
<li
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
const BreadcrumbSeparator = ({ children, className, ...props }: React.ComponentProps<"li">) => (
|
||||
<li
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
)
|
||||
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
|
||||
|
||||
const BreadcrumbEllipsis = ({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) => (
|
||||
<span
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex h-9 w-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
const BreadcrumbEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => (
|
||||
<span
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex h-9 w-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
|
||||
|
||||
export {
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
}
|
||||
|
||||
@@ -1,55 +1,52 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { type VariantProps, cva } from "class-variance-authority"
|
||||
import * as React from "react"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
|
||||
@@ -1,79 +1,55 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Card = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-lg border bg-card text-card-foreground shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
)
|
||||
Card.displayName = "Card"
|
||||
|
||||
const CardHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardHeader.displayName = "CardHeader"
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-2xl font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn("text-2xl font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
)
|
||||
CardTitle.displayName = "CardTitle"
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
||||
))
|
||||
CardDescription.displayName = "CardDescription"
|
||||
|
||||
const CardContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
))
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardContent.displayName = "CardContent"
|
||||
|
||||
const CardFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex items-center p-6 pt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardFooter.displayName = "CardFooter"
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { Check } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
const Checkbox = React.forwardRef<
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
className={cn("flex items-center justify-center text-current")}
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
<CheckboxPrimitive.Indicator
|
||||
className={cn("flex items-center justify-center text-current")}
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
))
|
||||
Checkbox.displayName = CheckboxPrimitive.Root.displayName
|
||||
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Check, ChevronDown } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Command,
|
||||
@@ -13,106 +9,97 @@ import {
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command"
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Check, ChevronDown } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
interface ComboboxProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
interface ComboboxProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
options: {
|
||||
label: string,
|
||||
value: string,
|
||||
}[];
|
||||
label: string
|
||||
value: string
|
||||
}[]
|
||||
|
||||
placeholder?: string;
|
||||
defaultValue?: string;
|
||||
className?: string;
|
||||
onValueChange: (value: string) => void;
|
||||
placeholder?: string
|
||||
defaultValue?: string
|
||||
className?: string
|
||||
onValueChange: (value: string) => void
|
||||
}
|
||||
|
||||
export const Combobox = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
ComboboxProps
|
||||
>(({
|
||||
options,
|
||||
placeholder,
|
||||
defaultValue,
|
||||
className,
|
||||
onValueChange,
|
||||
...props
|
||||
}, ref) => {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [value, setValue] = React.useState(defaultValue)
|
||||
export const Combobox = React.forwardRef<HTMLButtonElement, ComboboxProps>(
|
||||
({ options, placeholder, defaultValue, className, onValueChange, ...props }, ref) => {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [value, setValue] = React.useState(defaultValue)
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
ref={ref}
|
||||
{...props}
|
||||
role="combobox"
|
||||
variant="outline"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"flex w-full justify-between hover:bg-inherit",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{value
|
||||
? (() => {
|
||||
const val = options.find((option) => option.value === value)?.label
|
||||
return (
|
||||
val ? (
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
ref={ref}
|
||||
{...props}
|
||||
role="combobox"
|
||||
variant="outline"
|
||||
aria-expanded={open}
|
||||
className={cn("flex w-full justify-between hover:bg-inherit", className)}
|
||||
>
|
||||
{value ? (
|
||||
(() => {
|
||||
const val = options.find((option) => option.value === value)?.label
|
||||
return val ? (
|
||||
<div>{val}</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground">{placeholder}</div>
|
||||
)
|
||||
)
|
||||
})()
|
||||
: <div className="text-muted-foreground">{placeholder}</div>}
|
||||
<ChevronDown className="ml-auto opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Command
|
||||
filter={(value, search, keywords = []) => {
|
||||
const extendValue = value + " " + keywords.join(" ");
|
||||
if (extendValue.toLowerCase().includes(search.toLowerCase())) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}}
|
||||
>
|
||||
<CommandInput placeholder={placeholder} className="h-9" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No result found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{options.map((option) => (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
keywords={[option.label]}
|
||||
onSelect={(currentValue) => {
|
||||
setValue(currentValue === value ? "" : currentValue)
|
||||
onValueChange(currentValue === value ? "" : currentValue)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"justify-start",
|
||||
value === option.value ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
});
|
||||
})()
|
||||
) : (
|
||||
<div className="text-muted-foreground">{placeholder}</div>
|
||||
)}
|
||||
<ChevronDown className="ml-auto opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Command
|
||||
filter={(value, search, keywords = []) => {
|
||||
const extendValue = value + " " + keywords.join(" ")
|
||||
if (extendValue.toLowerCase().includes(search.toLowerCase())) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}}
|
||||
>
|
||||
<CommandInput placeholder={placeholder} className="h-9" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No result found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{options.map((option) => (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
keywords={[option.label]}
|
||||
onSelect={(currentValue) => {
|
||||
setValue(currentValue === value ? "" : currentValue)
|
||||
onValueChange(
|
||||
currentValue === value ? "" : currentValue,
|
||||
)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"justify-start",
|
||||
value === option.value
|
||||
? "opacity-100"
|
||||
: "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -1,151 +1,140 @@
|
||||
import * as React from "react"
|
||||
import { Dialog, DialogContent } from "@/components/ui/dialog"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { type DialogProps } from "@radix-ui/react-dialog"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { Search } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Dialog, DialogContent } from "@/components/ui/dialog"
|
||||
import * as React from "react"
|
||||
|
||||
const Command = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
|
||||
React.ElementRef<typeof CommandPrimitive>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<CommandPrimitive
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Command.displayName = CommandPrimitive.displayName
|
||||
|
||||
const CommandDialog = ({ children, ...props }: DialogProps) => {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogContent className="overflow-hidden p-0 shadow-lg">
|
||||
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogContent className="overflow-hidden p-0 shadow-lg">
|
||||
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
const CommandInput = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Input>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
|
||||
React.ElementRef<typeof CommandPrimitive.Input>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
|
||||
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
|
||||
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
|
||||
CommandInput.displayName = CommandPrimitive.Input.displayName
|
||||
|
||||
const CommandList = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
|
||||
React.ElementRef<typeof CommandPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.List
|
||||
ref={ref}
|
||||
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
|
||||
{...props}
|
||||
/>
|
||||
<CommandPrimitive.List
|
||||
ref={ref}
|
||||
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandList.displayName = CommandPrimitive.List.displayName
|
||||
|
||||
const CommandEmpty = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Empty>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
|
||||
React.ElementRef<typeof CommandPrimitive.Empty>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
|
||||
>((props, ref) => (
|
||||
<CommandPrimitive.Empty
|
||||
ref={ref}
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
<CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm" {...props} />
|
||||
))
|
||||
|
||||
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
|
||||
|
||||
const CommandGroup = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Group>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
|
||||
React.ElementRef<typeof CommandPrimitive.Group>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Group
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<CommandPrimitive.Group
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandGroup.displayName = CommandPrimitive.Group.displayName
|
||||
|
||||
const CommandSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
|
||||
React.ElementRef<typeof CommandPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
<CommandPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
|
||||
|
||||
const CommandItem = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
|
||||
React.ElementRef<typeof CommandPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<CommandPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandItem.displayName = CommandPrimitive.Item.displayName
|
||||
|
||||
const CommandShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
const CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
CommandShortcut.displayName = "CommandShortcut"
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
const Dialog = DialogPrimitive.Root
|
||||
|
||||
@@ -13,108 +12,93 @@ const DialogPortal = DialogPrimitive.Portal
|
||||
const DialogClose = DialogPrimitive.Close
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
))
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName
|
||||
|
||||
const DialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-1.5 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogHeader.displayName = "DialogHeader"
|
||||
|
||||
const DialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogFooter.displayName = "DialogFooter"
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-lg font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
}
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
import { Drawer as DrawerPrimitive } from "vaul"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Drawer = ({
|
||||
shouldScaleBackground = true,
|
||||
...props
|
||||
shouldScaleBackground = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
|
||||
<DrawerPrimitive.Root
|
||||
shouldScaleBackground={shouldScaleBackground}
|
||||
{...props}
|
||||
/>
|
||||
<DrawerPrimitive.Root shouldScaleBackground={shouldScaleBackground} {...props} />
|
||||
)
|
||||
Drawer.displayName = "Drawer"
|
||||
|
||||
@@ -21,96 +17,81 @@ const DrawerPortal = DrawerPrimitive.Portal
|
||||
const DrawerClose = DrawerPrimitive.Close
|
||||
|
||||
const DrawerOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
|
||||
React.ElementRef<typeof DrawerPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DrawerPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn("fixed inset-0 z-50 bg-black/80", className)}
|
||||
{...props}
|
||||
/>
|
||||
<DrawerPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn("fixed inset-0 z-50 bg-black/80", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
|
||||
|
||||
const DrawerContent = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
|
||||
React.ElementRef<typeof DrawerPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DrawerPortal>
|
||||
<DrawerOverlay />
|
||||
<DrawerPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
<DrawerPortal>
|
||||
<DrawerOverlay />
|
||||
<DrawerPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
))
|
||||
DrawerContent.displayName = "DrawerContent"
|
||||
|
||||
const DrawerHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
const DrawerHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)} {...props} />
|
||||
)
|
||||
DrawerHeader.displayName = "DrawerHeader"
|
||||
|
||||
const DrawerFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
const DrawerFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />
|
||||
)
|
||||
DrawerFooter.displayName = "DrawerFooter"
|
||||
|
||||
const DrawerTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
|
||||
React.ElementRef<typeof DrawerPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DrawerPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-lg font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DrawerPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
|
||||
|
||||
const DrawerDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
|
||||
React.ElementRef<typeof DrawerPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DrawerPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
<DrawerPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Drawer,
|
||||
DrawerPortal,
|
||||
DrawerOverlay,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerFooter,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
Drawer,
|
||||
DrawerPortal,
|
||||
DrawerOverlay,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerFooter,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { Check, ChevronRight, Circle } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
const DropdownMenu = DropdownMenuPrimitive.Root
|
||||
|
||||
@@ -17,182 +16,169 @@ const DropdownMenuSub = DropdownMenuPrimitive.Sub
|
||||
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
|
||||
|
||||
const DropdownMenuSubTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRight className="ml-auto" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
inset && "pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRight className="ml-auto" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
))
|
||||
DropdownMenuSubTrigger.displayName =
|
||||
DropdownMenuPrimitive.SubTrigger.displayName
|
||||
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName
|
||||
|
||||
const DropdownMenuSubContent = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuSubContent.displayName =
|
||||
DropdownMenuPrimitive.SubContent.displayName
|
||||
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName
|
||||
|
||||
const DropdownMenuContent = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
))
|
||||
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
|
||||
|
||||
const DropdownMenuItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
}
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
inset && "pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
|
||||
|
||||
const DropdownMenuCheckboxItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
|
||||
>(({ className, children, checked, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
))
|
||||
DropdownMenuCheckboxItem.displayName =
|
||||
DropdownMenuPrimitive.CheckboxItem.displayName
|
||||
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName
|
||||
|
||||
const DropdownMenuRadioItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Circle className="h-2 w-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Circle className="h-2 w-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
))
|
||||
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
|
||||
|
||||
const DropdownMenuLabel = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-semibold",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
|
||||
|
||||
const DropdownMenuSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
|
||||
|
||||
const DropdownMenuShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} />
|
||||
)
|
||||
}
|
||||
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuRadioGroup,
|
||||
}
|
||||
|
||||
@@ -1,176 +1,168 @@
|
||||
import * as React from "react"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import * as React from "react"
|
||||
import {
|
||||
Controller,
|
||||
ControllerProps,
|
||||
FieldPath,
|
||||
FieldValues,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
Controller,
|
||||
ControllerProps,
|
||||
FieldPath,
|
||||
FieldValues,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState, formState } = useFormContext()
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState, formState } = useFormContext()
|
||||
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue)
|
||||
|
||||
const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div ref={ref} className={cn("space-y-2", className)} {...props} />
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
const FormItem = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div ref={ref} className={cn("space-y-2", className)} {...props} />
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
})
|
||||
FormItem.displayName = "FormItem"
|
||||
|
||||
const FormLabel = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { error, formItemId } = useFormField()
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
ref={ref}
|
||||
className={cn(error && "text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<Label
|
||||
ref={ref}
|
||||
className={cn(error && "text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormLabel.displayName = "FormLabel"
|
||||
|
||||
const FormControl = React.forwardRef<
|
||||
React.ElementRef<typeof Slot>,
|
||||
React.ComponentPropsWithoutRef<typeof Slot>
|
||||
React.ElementRef<typeof Slot>,
|
||||
React.ComponentPropsWithoutRef<typeof Slot>
|
||||
>(({ ...props }, ref) => {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
ref={ref}
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<Slot
|
||||
ref={ref}
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormControl.displayName = "FormControl"
|
||||
|
||||
const FormDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { formDescriptionId } = useFormField()
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formDescriptionId}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formDescriptionId}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormDescription.displayName = "FormDescription"
|
||||
|
||||
const FormMessage = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, children, ...props }, ref) => {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message) : children
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message) : children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formMessageId}
|
||||
className={cn("text-sm font-medium text-destructive", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formMessageId}
|
||||
className={cn("text-sm font-medium text-destructive", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
})
|
||||
FormMessage.displayName = "FormMessage"
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
|
||||
@@ -1,24 +1,22 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
)
|
||||
Input.displayName = "Input"
|
||||
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { type VariantProps, cva } from "class-variance-authority"
|
||||
import * as React from "react"
|
||||
|
||||
const labelVariants = cva(
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
|
||||
)
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||
VariantProps<typeof labelVariants>
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(labelVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
|
||||
))
|
||||
Label.displayName = LabelPrimitive.Root.displayName
|
||||
|
||||
|
||||
@@ -1,128 +1,122 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { ChevronDown } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
const NavigationMenu = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<NavigationMenuPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-10 flex max-w-max flex-1 items-center justify-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<NavigationMenuViewport />
|
||||
</NavigationMenuPrimitive.Root>
|
||||
<NavigationMenuPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn("relative z-10 flex max-w-max flex-1 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<NavigationMenuViewport />
|
||||
</NavigationMenuPrimitive.Root>
|
||||
))
|
||||
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName
|
||||
|
||||
const NavigationMenuList = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<NavigationMenuPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"group flex flex-1 list-none items-center justify-center space-x-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<NavigationMenuPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"group flex flex-1 list-none items-center justify-center space-x-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
|
||||
|
||||
const NavigationMenuItem = NavigationMenuPrimitive.Item
|
||||
|
||||
const navigationMenuTriggerStyle = cva(
|
||||
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
|
||||
"group inline-flex h-10 w-max items-center justify-center rounded-md px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50",
|
||||
)
|
||||
|
||||
const NavigationMenuTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<NavigationMenuPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}{" "}
|
||||
<ChevronDown
|
||||
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</NavigationMenuPrimitive.Trigger>
|
||||
<NavigationMenuPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}{" "}
|
||||
<ChevronDown
|
||||
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</NavigationMenuPrimitive.Trigger>
|
||||
))
|
||||
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName
|
||||
|
||||
const NavigationMenuContent = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<NavigationMenuPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<NavigationMenuPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName
|
||||
|
||||
const NavigationMenuLink = NavigationMenuPrimitive.Link
|
||||
|
||||
const NavigationMenuViewport = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className={cn("absolute left-0 top-full flex justify-center")}>
|
||||
<NavigationMenuPrimitive.Viewport
|
||||
className={cn(
|
||||
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
<div className={cn("absolute left-0 top-full flex justify-center")}>
|
||||
<NavigationMenuPrimitive.Viewport
|
||||
className={cn(
|
||||
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
NavigationMenuViewport.displayName =
|
||||
NavigationMenuPrimitive.Viewport.displayName
|
||||
NavigationMenuViewport.displayName = NavigationMenuPrimitive.Viewport.displayName
|
||||
|
||||
const NavigationMenuIndicator = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<NavigationMenuPrimitive.Indicator
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
|
||||
</NavigationMenuPrimitive.Indicator>
|
||||
<NavigationMenuPrimitive.Indicator
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
|
||||
</NavigationMenuPrimitive.Indicator>
|
||||
))
|
||||
NavigationMenuIndicator.displayName =
|
||||
NavigationMenuPrimitive.Indicator.displayName
|
||||
NavigationMenuIndicator.displayName = NavigationMenuPrimitive.Indicator.displayName
|
||||
|
||||
export {
|
||||
navigationMenuTriggerStyle,
|
||||
NavigationMenu,
|
||||
NavigationMenuList,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuContent,
|
||||
NavigationMenuTrigger,
|
||||
NavigationMenuLink,
|
||||
NavigationMenuIndicator,
|
||||
NavigationMenuViewport,
|
||||
navigationMenuTriggerStyle,
|
||||
NavigationMenu,
|
||||
NavigationMenuList,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuContent,
|
||||
NavigationMenuTrigger,
|
||||
NavigationMenuLink,
|
||||
NavigationMenuIndicator,
|
||||
NavigationMenuViewport,
|
||||
}
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
import * as React from "react"
|
||||
|
||||
const Popover = PopoverPrimitive.Root
|
||||
|
||||
const PopoverTrigger = PopoverPrimitive.Trigger
|
||||
|
||||
const PopoverContent = React.forwardRef<
|
||||
React.ElementRef<typeof PopoverPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
|
||||
React.ElementRef<typeof PopoverPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
|
||||
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
ref={ref}
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
ref={ref}
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
))
|
||||
PopoverContent.displayName = PopoverPrimitive.Content.displayName
|
||||
|
||||
|
||||
@@ -1,45 +1,42 @@
|
||||
import * as React from "react"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
import * as React from "react"
|
||||
|
||||
const ScrollArea = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
<ScrollAreaPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
))
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
|
||||
|
||||
const ScrollBar = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
>(({ className, orientation = "vertical", ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none select-none transition-colors",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none select-none transition-colors",
|
||||
orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
))
|
||||
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { Check, ChevronDown, ChevronUp } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
const Select = SelectPrimitive.Root
|
||||
|
||||
@@ -11,148 +10,141 @@ const SelectGroup = SelectPrimitive.Group
|
||||
const SelectValue = SelectPrimitive.Value
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
))
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
))
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn("flex cursor-default items-center justify-center py-1", className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
))
|
||||
SelectScrollDownButton.displayName =
|
||||
SelectPrimitive.ScrollDownButton.displayName
|
||||
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = "popper", ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
))
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
))
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
}
|
||||
|
||||
@@ -1,29 +1,23 @@
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
import * as React from "react"
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(
|
||||
(
|
||||
{ className, orientation = "horizontal", decorative = true, ...props },
|
||||
ref
|
||||
) => (
|
||||
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(({ className, orientation = "horizontal", decorative = true, ...props }, ref) => (
|
||||
<SeparatorPrimitive.Root
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border",
|
||||
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border",
|
||||
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
)
|
||||
))
|
||||
Separator.displayName = SeparatorPrimitive.Root.displayName
|
||||
|
||||
export { Separator }
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} />
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
|
||||
@@ -4,26 +4,24 @@ import { Toaster as Sonner } from "sonner"
|
||||
type ToasterProps = React.ComponentProps<typeof Sonner>
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton:
|
||||
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast: "group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
|
||||
@@ -1,117 +1,94 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Table = React.forwardRef<
|
||||
HTMLTableElement,
|
||||
React.HTMLAttributes<HTMLTableElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
)
|
||||
Table.displayName = "Table"
|
||||
|
||||
const TableHeader = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||
))
|
||||
TableHeader.displayName = "TableHeader"
|
||||
|
||||
const TableBody = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tbody
|
||||
ref={ref}
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
|
||||
))
|
||||
TableBody.displayName = "TableBody"
|
||||
|
||||
const TableFooter = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tfoot
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<tfoot
|
||||
ref={ref}
|
||||
className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableFooter.displayName = "TableFooter"
|
||||
|
||||
const TableRow = React.forwardRef<
|
||||
HTMLTableRowElement,
|
||||
React.HTMLAttributes<HTMLTableRowElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
)
|
||||
TableRow.displayName = "TableRow"
|
||||
|
||||
const TableHead = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||
HTMLTableCellElement,
|
||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<th
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<th
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableHead.displayName = "TableHead"
|
||||
|
||||
const TableCell = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||
HTMLTableCellElement,
|
||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<td
|
||||
ref={ref}
|
||||
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
<td
|
||||
ref={ref}
|
||||
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TableCell.displayName = "TableCell"
|
||||
|
||||
const TableCaption = React.forwardRef<
|
||||
HTMLTableCaptionElement,
|
||||
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||
HTMLTableCaptionElement,
|
||||
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<caption
|
||||
ref={ref}
|
||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
|
||||
))
|
||||
TableCaption.displayName = "TableCaption"
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption }
|
||||
|
||||
@@ -1,52 +1,51 @@
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
import * as React from "react"
|
||||
|
||||
const Tabs = TabsPrimitive.Root
|
||||
|
||||
const TabsList = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
React.ElementRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TabsList.displayName = TabsPrimitive.List.displayName
|
||||
|
||||
const TabsTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
|
||||
|
||||
const TabsContent = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
React.ElementRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName
|
||||
|
||||
|
||||
@@ -1,22 +1,20 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Textarea = React.forwardRef<
|
||||
HTMLTextAreaElement,
|
||||
React.ComponentProps<"textarea">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, React.ComponentProps<"textarea">>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
)
|
||||
Textarea.displayName = "Textarea"
|
||||
|
||||
export { Textarea }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createUser } from "@/api/user"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -18,29 +18,28 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { ModelUser } from "@/types"
|
||||
import { useState } from "react"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { createUser } from "@/api/user"
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ModelUser } from "@/types"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { KeyedMutator } from "swr"
|
||||
import { z } from "zod"
|
||||
|
||||
interface UserCardProps {
|
||||
mutate: KeyedMutator<ModelUser[]>;
|
||||
mutate: KeyedMutator<ModelUser[]>
|
||||
}
|
||||
|
||||
const userFormSchema = z.object({
|
||||
username: z.string().min(1),
|
||||
password: z.string().min(8).max(72),
|
||||
});
|
||||
})
|
||||
|
||||
export const UserCard: React.FC<UserCardProps> = ({ mutate }) => {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const form = useForm<z.infer<typeof userFormSchema>>({
|
||||
resolver: zodResolver(userFormSchema),
|
||||
defaultValues: {
|
||||
@@ -49,16 +48,16 @@ export const UserCard: React.FC<UserCardProps> = ({ mutate }) => {
|
||||
},
|
||||
resetOptions: {
|
||||
keepDefaultValues: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof userFormSchema>) => {
|
||||
await createUser(values);
|
||||
setOpen(false);
|
||||
await mutate();
|
||||
form.reset();
|
||||
await createUser(values)
|
||||
setOpen(false)
|
||||
await mutate()
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -82,9 +81,7 @@ export const UserCard: React.FC<UserCardProps> = ({ mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Username")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
/>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -97,9 +94,7 @@ export const UserCard: React.FC<UserCardProps> = ({ mutate }) => {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Password")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
/>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -111,7 +106,9 @@ export const UserCard: React.FC<UserCardProps> = ({ mutate }) => {
|
||||
{t("Close")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" className="my-2">{t("Confirm")}</Button>
|
||||
<Button type="submit" className="my-2">
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -1,102 +1,115 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbEllipsis,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
Breadcrumb,
|
||||
BreadcrumbEllipsis,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { formatPath } from "@/lib/utils"
|
||||
import * as React from "react"
|
||||
|
||||
const ITEMS_TO_DISPLAY = 3
|
||||
|
||||
interface FilepathProps {
|
||||
path: string;
|
||||
setPath: React.Dispatch<React.SetStateAction<string>>;
|
||||
path: string
|
||||
setPath: React.Dispatch<React.SetStateAction<string>>
|
||||
}
|
||||
|
||||
function pathToItems(path: string) {
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
const segments = path.split("/").filter(Boolean)
|
||||
|
||||
const result: { href: string; label: string; }[] = [];
|
||||
const result: { href: string; label: string }[] = []
|
||||
|
||||
let currentPath = '';
|
||||
segments.forEach(segment => {
|
||||
currentPath += `/${segment}`;
|
||||
result.push({ href: currentPath, label: segment });
|
||||
});
|
||||
let currentPath = ""
|
||||
segments.forEach((segment) => {
|
||||
currentPath += `/${segment}`
|
||||
result.push({ href: currentPath, label: segment })
|
||||
})
|
||||
|
||||
return result;
|
||||
return result
|
||||
}
|
||||
|
||||
export const Filepath: React.FC<FilepathProps> = ({ path, setPath }) => {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const items = pathToItems(formatPath(path));
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const items = pathToItems(formatPath(path))
|
||||
|
||||
return (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<p className="cursor-pointer hover:text-white transition" onClick={() => { setPath('/') }}>{'/'}</p>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
{items.length > ITEMS_TO_DISPLAY ? (
|
||||
<>
|
||||
<BreadcrumbItem>
|
||||
{
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger
|
||||
className="flex items-center gap-1"
|
||||
aria-label="Toggle menu"
|
||||
>
|
||||
<BreadcrumbEllipsis className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
{items.slice(0, -ITEMS_TO_DISPLAY).map((item, index) => (
|
||||
<DropdownMenuItem key={index}>
|
||||
<p onClick={() => { setPath(item.href) }}>
|
||||
{item.label}
|
||||
</p>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
}
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
</>
|
||||
) : null}
|
||||
{items.slice(-ITEMS_TO_DISPLAY).map((item, index, slicedItems) => (
|
||||
<React.Fragment key={index}>
|
||||
<BreadcrumbItem className="overflow-auto">
|
||||
{item.href ? (
|
||||
<>
|
||||
<p
|
||||
className="max-w-20 truncate md:max-w-none cursor-pointer hover:text-white transition"
|
||||
onClick={() => { setPath(item.href) }}
|
||||
>
|
||||
{item.label}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<BreadcrumbPage className="max-w-20 truncate md:max-w-none">
|
||||
{item.label}
|
||||
</BreadcrumbPage>
|
||||
)}
|
||||
</BreadcrumbItem>
|
||||
{index !== slicedItems.length - 1 ? <BreadcrumbSeparator /> : null}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)
|
||||
return (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<p
|
||||
className="cursor-pointer hover:text-white transition"
|
||||
onClick={() => {
|
||||
setPath("/")
|
||||
}}
|
||||
>
|
||||
{"/"}
|
||||
</p>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
{items.length > ITEMS_TO_DISPLAY ? (
|
||||
<>
|
||||
<BreadcrumbItem>
|
||||
{
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger
|
||||
className="flex items-center gap-1"
|
||||
aria-label="Toggle menu"
|
||||
>
|
||||
<BreadcrumbEllipsis className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
{items.slice(0, -ITEMS_TO_DISPLAY).map((item, index) => (
|
||||
<DropdownMenuItem key={index}>
|
||||
<p
|
||||
onClick={() => {
|
||||
setPath(item.href)
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</p>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
}
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
</>
|
||||
) : null}
|
||||
{items.slice(-ITEMS_TO_DISPLAY).map((item, index, slicedItems) => (
|
||||
<React.Fragment key={index}>
|
||||
<BreadcrumbItem className="overflow-auto">
|
||||
{item.href ? (
|
||||
<>
|
||||
<p
|
||||
className="max-w-20 truncate md:max-w-none cursor-pointer hover:text-white transition"
|
||||
onClick={() => {
|
||||
setPath(item.href)
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<BreadcrumbPage className="max-w-20 truncate md:max-w-none">
|
||||
{item.label}
|
||||
</BreadcrumbPage>
|
||||
)}
|
||||
</BreadcrumbItem>
|
||||
{index !== slicedItems.length - 1 ? <BreadcrumbSeparator /> : null}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,79 +1,84 @@
|
||||
import { Button, ButtonProps } from "@/components/ui/button"
|
||||
import {
|
||||
Plus,
|
||||
Edit2,
|
||||
Trash2,
|
||||
Terminal,
|
||||
Check,
|
||||
CircleArrowUp,
|
||||
Clipboard,
|
||||
Check,
|
||||
FolderClosed,
|
||||
Play,
|
||||
Download,
|
||||
Upload,
|
||||
Edit2,
|
||||
FolderClosed,
|
||||
Menu,
|
||||
Play,
|
||||
Plus,
|
||||
Terminal,
|
||||
Trash2,
|
||||
Upload,
|
||||
} from "lucide-react"
|
||||
import { Button, ButtonProps } from "@/components/ui/button"
|
||||
import { forwardRef } from "react";
|
||||
import { forwardRef } from "react"
|
||||
|
||||
export interface IconButtonProps extends ButtonProps {
|
||||
icon:
|
||||
"clipboard" |
|
||||
"check" |
|
||||
"edit" |
|
||||
"trash" |
|
||||
"plus" |
|
||||
"terminal" |
|
||||
"update" |
|
||||
"folder-closed" |
|
||||
"play" |
|
||||
"download" |
|
||||
"upload" |
|
||||
"menu";
|
||||
| "clipboard"
|
||||
| "check"
|
||||
| "edit"
|
||||
| "trash"
|
||||
| "plus"
|
||||
| "terminal"
|
||||
| "update"
|
||||
| "folder-closed"
|
||||
| "play"
|
||||
| "download"
|
||||
| "upload"
|
||||
| "menu"
|
||||
}
|
||||
|
||||
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>((props, ref) => {
|
||||
return (
|
||||
<Button {...props} ref={ref} size="icon">
|
||||
<Button
|
||||
className="rounded-lg shadow-[inset_0_1px_0_rgba(255,255,255,0.2)]"
|
||||
{...props}
|
||||
ref={ref}
|
||||
size="icon"
|
||||
>
|
||||
{(() => {
|
||||
switch (props.icon) {
|
||||
case "clipboard": {
|
||||
return <Clipboard />;
|
||||
return <Clipboard />
|
||||
}
|
||||
case "check": {
|
||||
return <Check />;
|
||||
return <Check />
|
||||
}
|
||||
case "edit": {
|
||||
return <Edit2 />;
|
||||
return <Edit2 />
|
||||
}
|
||||
case "trash": {
|
||||
return <Trash2 />;
|
||||
return <Trash2 />
|
||||
}
|
||||
case "plus": {
|
||||
return <Plus />;
|
||||
return <Plus />
|
||||
}
|
||||
case "terminal": {
|
||||
return <Terminal />;
|
||||
return <Terminal />
|
||||
}
|
||||
case "update": {
|
||||
return <CircleArrowUp />;
|
||||
return <CircleArrowUp />
|
||||
}
|
||||
case "folder-closed": {
|
||||
return <FolderClosed />;
|
||||
return <FolderClosed />
|
||||
}
|
||||
case "play": {
|
||||
return <Play />;
|
||||
return <Play />
|
||||
}
|
||||
case "download": {
|
||||
return <Download />;
|
||||
return <Download />
|
||||
}
|
||||
case "upload": {
|
||||
return <Upload />;
|
||||
return <Upload />
|
||||
}
|
||||
case "menu": {
|
||||
return <Menu />;
|
||||
return <Menu />
|
||||
}
|
||||
}
|
||||
})()}
|
||||
</Button>
|
||||
);
|
||||
)
|
||||
})
|
||||
|
||||
@@ -22,392 +22,367 @@
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
CheckIcon,
|
||||
ChevronDown,
|
||||
XIcon,
|
||||
WandSparkles,
|
||||
} from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "@/components/ui/command";
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
} from "@/components/ui/command"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { type VariantProps, cva } from "class-variance-authority"
|
||||
import { CheckIcon, ChevronDown, WandSparkles, XIcon } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
/**
|
||||
* Variants for the multi-select component to handle different styles.
|
||||
* Uses class-variance-authority (cva) to define different styles based on "variant" prop.
|
||||
*/
|
||||
const multiSelectVariants = cva(
|
||||
"m-1 transition ease-in-out delay-150 hover:-translate-y-1 duration-300",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-foreground/10 text-foreground bg-card hover:bg-card/80",
|
||||
secondary:
|
||||
"border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
||||
inverted: "inverted",
|
||||
},
|
||||
"m-1 transition ease-in-out delay-150 hover:-translate-y-1 duration-300",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-foreground/10 text-foreground bg-card hover:bg-card/80",
|
||||
secondary:
|
||||
"border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
||||
inverted: "inverted",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
)
|
||||
|
||||
/**
|
||||
* Props for MultiSelect component
|
||||
*/
|
||||
interface MultiSelectProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof multiSelectVariants> {
|
||||
/**
|
||||
* An array of option objects to be displayed in the multi-select component.
|
||||
* Each option object has a label, value, and an optional icon.
|
||||
*/
|
||||
options: {
|
||||
/** The text to display for the option. */
|
||||
label: string;
|
||||
/** The unique value associated with the option. */
|
||||
value: string;
|
||||
/** Optional icon component to display alongside the option. */
|
||||
icon?: React.ComponentType<{ className?: string }>;
|
||||
}[];
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof multiSelectVariants> {
|
||||
/**
|
||||
* An array of option objects to be displayed in the multi-select component.
|
||||
* Each option object has a label, value, and an optional icon.
|
||||
*/
|
||||
options: {
|
||||
/** The text to display for the option. */
|
||||
label: string
|
||||
/** The unique value associated with the option. */
|
||||
value: string
|
||||
/** Optional icon component to display alongside the option. */
|
||||
icon?: React.ComponentType<{ className?: string }>
|
||||
}[]
|
||||
|
||||
/**
|
||||
* Callback function triggered when the selected values change.
|
||||
* Receives an array of the new selected values.
|
||||
*/
|
||||
onValueChange: (value: string[]) => void;
|
||||
/**
|
||||
* Callback function triggered when the selected values change.
|
||||
* Receives an array of the new selected values.
|
||||
*/
|
||||
onValueChange: (value: string[]) => void
|
||||
|
||||
/** The default selected values when the component mounts. */
|
||||
defaultValue?: string[];
|
||||
/** The default selected values when the component mounts. */
|
||||
defaultValue?: string[]
|
||||
|
||||
/**
|
||||
* Placeholder text to be displayed when no values are selected.
|
||||
* Optional, defaults to "Select options".
|
||||
*/
|
||||
placeholder?: string;
|
||||
/**
|
||||
* Placeholder text to be displayed when no values are selected.
|
||||
* Optional, defaults to "Select options".
|
||||
*/
|
||||
placeholder?: string
|
||||
|
||||
/**
|
||||
* Animation duration in seconds for the visual effects (e.g., bouncing badges).
|
||||
* Optional, defaults to 0 (no animation).
|
||||
*/
|
||||
animation?: number;
|
||||
/**
|
||||
* Animation duration in seconds for the visual effects (e.g., bouncing badges).
|
||||
* Optional, defaults to 0 (no animation).
|
||||
*/
|
||||
animation?: number
|
||||
|
||||
/**
|
||||
* Maximum number of items to display. Extra selected items will be summarized.
|
||||
* Optional, defaults to 3.
|
||||
*/
|
||||
maxCount?: number;
|
||||
/**
|
||||
* Maximum number of items to display. Extra selected items will be summarized.
|
||||
* Optional, defaults to 3.
|
||||
*/
|
||||
maxCount?: number
|
||||
|
||||
/**
|
||||
* The modality of the popover. When set to true, interaction with outside elements
|
||||
* will be disabled and only popover content will be visible to screen readers.
|
||||
* Optional, defaults to false.
|
||||
*/
|
||||
modalPopover?: boolean;
|
||||
/**
|
||||
* The modality of the popover. When set to true, interaction with outside elements
|
||||
* will be disabled and only popover content will be visible to screen readers.
|
||||
* Optional, defaults to false.
|
||||
*/
|
||||
modalPopover?: boolean
|
||||
|
||||
/**
|
||||
* If true, renders the multi-select component as a child of another component.
|
||||
* Optional, defaults to false.
|
||||
*/
|
||||
asChild?: boolean;
|
||||
/**
|
||||
* If true, renders the multi-select component as a child of another component.
|
||||
* Optional, defaults to false.
|
||||
*/
|
||||
asChild?: boolean
|
||||
|
||||
/**
|
||||
* Additional class names to apply custom styles to the multi-select component.
|
||||
* Optional, can be used to add custom styles.
|
||||
*/
|
||||
className?: string;
|
||||
/**
|
||||
* Additional class names to apply custom styles to the multi-select component.
|
||||
* Optional, can be used to add custom styles.
|
||||
*/
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const MultiSelect = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
MultiSelectProps
|
||||
>(
|
||||
(
|
||||
{
|
||||
options,
|
||||
onValueChange,
|
||||
variant,
|
||||
defaultValue = [],
|
||||
placeholder = "Select options",
|
||||
animation = 0,
|
||||
maxCount = 3,
|
||||
modalPopover = false,
|
||||
asChild = false,
|
||||
className,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [selectedValues, setSelectedValues] =
|
||||
React.useState<string[]>(defaultValue);
|
||||
const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
|
||||
const [isAnimating, setIsAnimating] = React.useState(false);
|
||||
|
||||
const handleInputKeyDown = (
|
||||
event: React.KeyboardEvent<HTMLInputElement>
|
||||
export const MultiSelect = React.forwardRef<HTMLButtonElement, MultiSelectProps>(
|
||||
(
|
||||
{
|
||||
options,
|
||||
onValueChange,
|
||||
variant,
|
||||
defaultValue = [],
|
||||
placeholder = "Select options",
|
||||
animation = 0,
|
||||
maxCount = 3,
|
||||
modalPopover = false,
|
||||
asChild = false,
|
||||
className,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
if (event.key === "Enter") {
|
||||
setIsPopoverOpen(true);
|
||||
} else if (event.key === "Backspace" && !event.currentTarget.value) {
|
||||
const newSelectedValues = [...selectedValues];
|
||||
newSelectedValues.pop();
|
||||
setSelectedValues(newSelectedValues);
|
||||
onValueChange(newSelectedValues);
|
||||
}
|
||||
};
|
||||
const [selectedValues, setSelectedValues] = React.useState<string[]>(defaultValue)
|
||||
const [isPopoverOpen, setIsPopoverOpen] = React.useState(false)
|
||||
const [isAnimating, setIsAnimating] = React.useState(false)
|
||||
|
||||
const toggleOption = (option: string) => {
|
||||
const newSelectedValues = selectedValues.includes(option)
|
||||
? selectedValues.filter((value) => value !== option)
|
||||
: [...selectedValues, option];
|
||||
setSelectedValues(newSelectedValues);
|
||||
onValueChange(newSelectedValues);
|
||||
};
|
||||
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === "Enter") {
|
||||
setIsPopoverOpen(true)
|
||||
} else if (event.key === "Backspace" && !event.currentTarget.value) {
|
||||
const newSelectedValues = [...selectedValues]
|
||||
newSelectedValues.pop()
|
||||
setSelectedValues(newSelectedValues)
|
||||
onValueChange(newSelectedValues)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClear = () => {
|
||||
setSelectedValues([]);
|
||||
onValueChange([]);
|
||||
};
|
||||
const toggleOption = (option: string) => {
|
||||
const newSelectedValues = selectedValues.includes(option)
|
||||
? selectedValues.filter((value) => value !== option)
|
||||
: [...selectedValues, option]
|
||||
setSelectedValues(newSelectedValues)
|
||||
onValueChange(newSelectedValues)
|
||||
}
|
||||
|
||||
const handleTogglePopover = () => {
|
||||
setIsPopoverOpen((prev) => !prev);
|
||||
};
|
||||
const handleClear = () => {
|
||||
setSelectedValues([])
|
||||
onValueChange([])
|
||||
}
|
||||
|
||||
const clearExtraOptions = () => {
|
||||
const newSelectedValues = selectedValues.slice(0, maxCount);
|
||||
setSelectedValues(newSelectedValues);
|
||||
onValueChange(newSelectedValues);
|
||||
};
|
||||
const handleTogglePopover = () => {
|
||||
setIsPopoverOpen((prev) => !prev)
|
||||
}
|
||||
|
||||
const toggleAll = () => {
|
||||
if (selectedValues.length === options.length) {
|
||||
handleClear();
|
||||
} else {
|
||||
const allValues = options.map((option) => option.value);
|
||||
setSelectedValues(allValues);
|
||||
onValueChange(allValues);
|
||||
}
|
||||
};
|
||||
const clearExtraOptions = () => {
|
||||
const newSelectedValues = selectedValues.slice(0, maxCount)
|
||||
setSelectedValues(newSelectedValues)
|
||||
onValueChange(newSelectedValues)
|
||||
}
|
||||
|
||||
const stopWheelEventPropagation: React.WheelEventHandler = (e) => {
|
||||
e.stopPropagation();
|
||||
};
|
||||
const toggleAll = () => {
|
||||
if (selectedValues.length === options.length) {
|
||||
handleClear()
|
||||
} else {
|
||||
const allValues = options.map((option) => option.value)
|
||||
setSelectedValues(allValues)
|
||||
onValueChange(allValues)
|
||||
}
|
||||
}
|
||||
|
||||
const stopTouchMoveEventPropagation: React.TouchEventHandler = (e) => {
|
||||
e.stopPropagation();
|
||||
};
|
||||
const stopWheelEventPropagation: React.WheelEventHandler = (e) => {
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={isPopoverOpen}
|
||||
onOpenChange={setIsPopoverOpen}
|
||||
modal={modalPopover}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
ref={ref}
|
||||
{...props}
|
||||
onClick={handleTogglePopover}
|
||||
className={cn(
|
||||
"flex w-full p-1 rounded-md border min-h-10 h-auto items-center justify-between bg-inherit hover:bg-inherit [&_svg]:pointer-events-auto",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{selectedValues.length > 0 ? (
|
||||
<div className="flex justify-between items-center w-full">
|
||||
<div className="flex flex-wrap items-center">
|
||||
{selectedValues.slice(0, maxCount).map((value) => {
|
||||
const option = options.find((o) => o.value === value);
|
||||
const IconComponent = option?.icon;
|
||||
return (
|
||||
<Badge
|
||||
key={value}
|
||||
const stopTouchMoveEventPropagation: React.TouchEventHandler = (e) => {
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen} modal={modalPopover}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
ref={ref}
|
||||
{...props}
|
||||
onClick={handleTogglePopover}
|
||||
className={cn(
|
||||
isAnimating ? "animate-bounce" : "",
|
||||
multiSelectVariants({ variant })
|
||||
"flex w-full p-1 rounded-md border min-h-10 h-auto items-center justify-between bg-inherit hover:bg-inherit [&_svg]:pointer-events-auto",
|
||||
className,
|
||||
)}
|
||||
style={{ animationDuration: `${animation}s` }}
|
||||
>
|
||||
{IconComponent && (
|
||||
<IconComponent className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{option?.label}
|
||||
<XIcon
|
||||
className="ml-2 h-2 w-2 cursor-pointer"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleOption(value);
|
||||
}}
|
||||
/>
|
||||
</Badge>
|
||||
);
|
||||
})}
|
||||
{selectedValues.length > maxCount && (
|
||||
<Badge
|
||||
className={cn(
|
||||
"bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
|
||||
isAnimating ? "animate-bounce" : "",
|
||||
multiSelectVariants({ variant })
|
||||
)}
|
||||
style={{ animationDuration: `${animation}s` }}
|
||||
>
|
||||
{`+ ${selectedValues.length - maxCount} more`}
|
||||
<XIcon
|
||||
className="ml-2 h-2 w-2 cursor-pointer"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
clearExtraOptions();
|
||||
}}
|
||||
/>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<XIcon
|
||||
className="h-4 mx-2 cursor-pointer text-muted-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
handleClear();
|
||||
}}
|
||||
/>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="flex min-h-6 h-full"
|
||||
/>
|
||||
<ChevronDown className="h-4 mx-2 cursor-pointer text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between w-full mx-auto">
|
||||
<span className="text-sm text-muted-foreground mx-3">
|
||||
{placeholder}
|
||||
</span>
|
||||
<ChevronDown className="h-4 cursor-pointer text-muted-foreground mx-2" />
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
className="w-auto p-0"
|
||||
align="start"
|
||||
onEscapeKeyDown={() => setIsPopoverOpen(false)}
|
||||
onWheel={stopWheelEventPropagation}
|
||||
onTouchMove={stopTouchMoveEventPropagation}
|
||||
>
|
||||
<Command>
|
||||
<CommandInput
|
||||
placeholder="Search..."
|
||||
onKeyDown={handleInputKeyDown}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>No results found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
key="all"
|
||||
onSelect={toggleAll}
|
||||
className="cursor-pointer"
|
||||
{selectedValues.length > 0 ? (
|
||||
<div className="flex justify-between items-center w-full">
|
||||
<div className="flex flex-wrap items-center">
|
||||
{selectedValues.slice(0, maxCount).map((value) => {
|
||||
const option = options.find((o) => o.value === value)
|
||||
const IconComponent = option?.icon
|
||||
return (
|
||||
<Badge
|
||||
key={value}
|
||||
className={cn(
|
||||
isAnimating ? "animate-bounce" : "",
|
||||
multiSelectVariants({ variant }),
|
||||
)}
|
||||
style={{ animationDuration: `${animation}s` }}
|
||||
>
|
||||
{IconComponent && (
|
||||
<IconComponent className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{option?.label}
|
||||
<XIcon
|
||||
className="ml-2 h-2 w-2 cursor-pointer"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
toggleOption(value)
|
||||
}}
|
||||
/>
|
||||
</Badge>
|
||||
)
|
||||
})}
|
||||
{selectedValues.length > maxCount && (
|
||||
<Badge
|
||||
className={cn(
|
||||
"bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
|
||||
isAnimating ? "animate-bounce" : "",
|
||||
multiSelectVariants({ variant }),
|
||||
)}
|
||||
style={{ animationDuration: `${animation}s` }}
|
||||
>
|
||||
{`+ ${selectedValues.length - maxCount} more`}
|
||||
<XIcon
|
||||
className="ml-2 h-2 w-2 cursor-pointer"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
clearExtraOptions()
|
||||
}}
|
||||
/>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<XIcon
|
||||
className="h-4 mx-2 cursor-pointer text-muted-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
handleClear()
|
||||
}}
|
||||
/>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="flex min-h-6 h-full"
|
||||
/>
|
||||
<ChevronDown className="h-4 mx-2 cursor-pointer text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between w-full mx-auto">
|
||||
<span className="text-sm text-muted-foreground mx-3">
|
||||
{placeholder}
|
||||
</span>
|
||||
<ChevronDown className="h-4 cursor-pointer text-muted-foreground mx-2" />
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
className="w-auto p-0"
|
||||
align="start"
|
||||
onEscapeKeyDown={() => setIsPopoverOpen(false)}
|
||||
onWheel={stopWheelEventPropagation}
|
||||
onTouchMove={stopTouchMoveEventPropagation}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
|
||||
selectedValues.length === options.length
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "opacity-50 [&_svg]:invisible"
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="h-4 w-4" />
|
||||
</div>
|
||||
<span>(Select All)</span>
|
||||
</CommandItem>
|
||||
{options.map((option) => {
|
||||
const isSelected = selectedValues.includes(option.value);
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
onSelect={() => toggleOption(option.value)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div
|
||||
<Command>
|
||||
<CommandInput placeholder="Search..." onKeyDown={handleInputKeyDown} />
|
||||
<CommandList>
|
||||
<CommandEmpty>No results found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
key="all"
|
||||
onSelect={toggleAll}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
|
||||
selectedValues.length === options.length
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "opacity-50 [&_svg]:invisible",
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="h-4 w-4" />
|
||||
</div>
|
||||
<span>(Select All)</span>
|
||||
</CommandItem>
|
||||
{options.map((option) => {
|
||||
const isSelected = selectedValues.includes(option.value)
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
onSelect={() => toggleOption(option.value)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
|
||||
isSelected
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "opacity-50 [&_svg]:invisible",
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="h-4 w-4" />
|
||||
</div>
|
||||
{option.icon && (
|
||||
<option.icon className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<span>{option.label}</span>
|
||||
</CommandItem>
|
||||
)
|
||||
})}
|
||||
</CommandGroup>
|
||||
<CommandSeparator />
|
||||
<CommandGroup>
|
||||
<div className="flex items-center justify-between">
|
||||
{selectedValues.length > 0 && (
|
||||
<>
|
||||
<CommandItem
|
||||
onSelect={handleClear}
|
||||
className="flex-1 justify-center cursor-pointer"
|
||||
>
|
||||
Clear
|
||||
</CommandItem>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="flex min-h-6 h-full"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<CommandItem
|
||||
onSelect={() => setIsPopoverOpen(false)}
|
||||
className="flex-1 justify-center cursor-pointer max-w-full"
|
||||
>
|
||||
Close
|
||||
</CommandItem>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
{animation > 0 && selectedValues.length > 0 && (
|
||||
<WandSparkles
|
||||
className={cn(
|
||||
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
|
||||
isSelected
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "opacity-50 [&_svg]:invisible"
|
||||
"cursor-pointer my-2 text-foreground bg-background w-3 h-3",
|
||||
isAnimating ? "" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
<CheckIcon className="h-4 w-4" />
|
||||
</div>
|
||||
{option.icon && (
|
||||
<option.icon className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<span>{option.label}</span>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
<CommandSeparator />
|
||||
<CommandGroup>
|
||||
<div className="flex items-center justify-between">
|
||||
{selectedValues.length > 0 && (
|
||||
<>
|
||||
<CommandItem
|
||||
onSelect={handleClear}
|
||||
className="flex-1 justify-center cursor-pointer"
|
||||
>
|
||||
Clear
|
||||
</CommandItem>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="flex min-h-6 h-full"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<CommandItem
|
||||
onSelect={() => setIsPopoverOpen(false)}
|
||||
className="flex-1 justify-center cursor-pointer max-w-full"
|
||||
>
|
||||
Close
|
||||
</CommandItem>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
{animation > 0 && selectedValues.length > 0 && (
|
||||
<WandSparkles
|
||||
className={cn(
|
||||
"cursor-pointer my-2 text-foreground bg-background w-3 h-3",
|
||||
isAnimating ? "" : "text-muted-foreground"
|
||||
)}
|
||||
onClick={() => setIsAnimating(!isAnimating)}
|
||||
/>
|
||||
)}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
);
|
||||
onClick={() => setIsAnimating(!isAnimating)}
|
||||
/>
|
||||
)}
|
||||
</Popover>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
MultiSelect.displayName = "MultiSelect";
|
||||
MultiSelect.displayName = "MultiSelect"
|
||||
|
||||
@@ -1,10 +1,48 @@
|
||||
import { NavigationMenuLinkProps, NavigationMenuTriggerProps } from "@radix-ui/react-navigation-menu"
|
||||
import { NavigationMenuLink, NavigationMenuTrigger, navigationMenuTriggerStyle } from "../ui/navigation-menu"
|
||||
import {
|
||||
NavigationMenuLinkProps,
|
||||
NavigationMenuTriggerProps,
|
||||
} from "@radix-ui/react-navigation-menu"
|
||||
import { motion } from "framer-motion"
|
||||
|
||||
export const NzNavigationMenuLink = (props: NavigationMenuLinkProps & React.RefAttributes<HTMLAnchorElement>) => {
|
||||
return <NavigationMenuLink {...props} className={navigationMenuTriggerStyle() + " hover:bg-inherit data-[active]:bg-inherit transition-colors text-foreground/60 data-[active]:text-foreground hover:text-foreground/90"} />
|
||||
import {
|
||||
NavigationMenuLink,
|
||||
NavigationMenuTrigger,
|
||||
navigationMenuTriggerStyle,
|
||||
} from "../ui/navigation-menu"
|
||||
|
||||
export const NzNavigationMenuLink = (
|
||||
props: NavigationMenuLinkProps & React.RefAttributes<HTMLAnchorElement>,
|
||||
) => {
|
||||
return (
|
||||
<div className="relative">
|
||||
<NavigationMenuLink
|
||||
{...props}
|
||||
className={
|
||||
navigationMenuTriggerStyle() +
|
||||
" hover:bg-inherit data-[active]:bg-inherit transition-colors text-foreground/60 data-[active]:text-foreground hover:text-foreground/90"
|
||||
}
|
||||
/>
|
||||
{props.active && (
|
||||
<motion.div
|
||||
layoutId="tab-underline"
|
||||
className="absolute bottom-0 left-0 right-0 h-[2px] bg-black dark:bg-white"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const NzNavigationMenuTrigger = (props: Omit<NavigationMenuTriggerProps & React.RefAttributes<HTMLButtonElement>, "ref"> & React.RefAttributes<HTMLButtonElement>) => {
|
||||
return <NavigationMenuTrigger {...props} className={navigationMenuTriggerStyle() + " hover:bg-inherit data-[active]:bg-inherit transition-colors text-foreground/60 data-[active]:text-foreground hover:text-foreground/90"} />
|
||||
export const NzNavigationMenuTrigger = (
|
||||
props: Omit<NavigationMenuTriggerProps & React.RefAttributes<HTMLButtonElement>, "ref"> &
|
||||
React.RefAttributes<HTMLButtonElement>,
|
||||
) => {
|
||||
return (
|
||||
<NavigationMenuTrigger
|
||||
{...props}
|
||||
className={
|
||||
navigationMenuTriggerStyle() +
|
||||
" hover:bg-inherit data-[active]:bg-inherit transition-colors text-foreground/60 data-[active]:text-foreground hover:text-foreground/90"
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { type VariantProps, cva } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
import * as React from "react"
|
||||
|
||||
const Sheet = SheetPrimitive.Root
|
||||
|
||||
@@ -14,108 +13,98 @@ const SheetClose = SheetPrimitive.Close
|
||||
const SheetPortal = SheetPrimitive.Portal
|
||||
|
||||
const sheetVariants = cva(
|
||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
||||
bottom:
|
||||
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
||||
right:
|
||||
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
||||
},
|
||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
||||
bottom: "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
||||
right: "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
side: "right",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
side: "right",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
interface SheetContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
|
||||
VariantProps<typeof sheetVariants> { setOpen: React.Dispatch<React.SetStateAction<boolean>> }
|
||||
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
|
||||
VariantProps<typeof sheetVariants> {
|
||||
setOpen: React.Dispatch<React.SetStateAction<boolean>>
|
||||
}
|
||||
|
||||
const SheetContent = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Content>,
|
||||
SheetContentProps
|
||||
React.ElementRef<typeof SheetPrimitive.Content>,
|
||||
SheetContentProps
|
||||
>(({ side = "right", className, children, setOpen, ...props }, ref) => (
|
||||
<SheetPortal>
|
||||
<SheetPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(sheetVariants({ side }), className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<X className="h-4 w-4" onClick={() => { setOpen(false) }} />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
<SheetPortal>
|
||||
<SheetPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(sheetVariants({ side }), className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<X
|
||||
className="h-4 w-4"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
}}
|
||||
/>
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
))
|
||||
SheetContent.displayName = SheetPrimitive.Content.displayName
|
||||
|
||||
const SheetHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-2 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
|
||||
)
|
||||
SheetHeader.displayName = "SheetHeader"
|
||||
|
||||
const SheetFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetFooter.displayName = "SheetFooter"
|
||||
|
||||
const SheetTitle = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
|
||||
React.ElementRef<typeof SheetPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
<SheetPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetTitle.displayName = SheetPrimitive.Title.displayName
|
||||
|
||||
const SheetDescription = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
|
||||
React.ElementRef<typeof SheetPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
<SheetPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetDescription.displayName = SheetPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetPortal,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
Sheet,
|
||||
SheetPortal,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
"use client";
|
||||
"use client"
|
||||
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { TableCell, TableHead, TableRow } from "@/components/ui/table"
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
ColumnDef,
|
||||
Row,
|
||||
@@ -9,36 +13,26 @@ import {
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table";
|
||||
|
||||
import { TableCell, TableHead, TableRow } from "@/components/ui/table";
|
||||
import { HTMLAttributes, forwardRef, useState, useRef, useEffect } from "react";
|
||||
import { TableVirtuoso } from "react-virtuoso";
|
||||
import { cn } from "@/lib/utils"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery";
|
||||
} from "@tanstack/react-table"
|
||||
import { HTMLAttributes, forwardRef, useEffect, useRef, useState } from "react"
|
||||
import { TableVirtuoso } from "react-virtuoso"
|
||||
|
||||
// Original Table is wrapped with a <div> (see https://ui.shadcn.com/docs/components/table#radix-:r24:-content-manual),
|
||||
// but here we don't want it, so let's use a new component with only <table> tag
|
||||
const TableComponent = forwardRef<
|
||||
HTMLTableElement,
|
||||
React.HTMLAttributes<HTMLTableElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableComponent.displayName = "TableComponent";
|
||||
const TableComponent = forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
||||
),
|
||||
)
|
||||
TableComponent.displayName = "TableComponent"
|
||||
|
||||
const TableRowComponent = <TData,>(rows: Row<TData>[]) =>
|
||||
function getTableRow(props: HTMLAttributes<HTMLTableRowElement>) {
|
||||
// @ts-expect-error data-index is a valid attribute
|
||||
const index = props["data-index"];
|
||||
const row = rows[index];
|
||||
const index = props["data-index"]
|
||||
const row = rows[index]
|
||||
|
||||
if (!row) return null;
|
||||
if (!row) return null
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
@@ -53,11 +47,11 @@ const TableRowComponent = <TData,>(rows: Row<TData>[]) =>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
function SortingIndicator({ isSorted }: { isSorted: SortDirection | false }) {
|
||||
if (!isSorted) return null;
|
||||
if (!isSorted) return null
|
||||
return (
|
||||
<div>
|
||||
{
|
||||
@@ -67,13 +61,15 @@ function SortingIndicator({ isSorted }: { isSorted: SortDirection | false }) {
|
||||
}[isSorted]
|
||||
}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[];
|
||||
data: TData[];
|
||||
rowComponent?: (rows: Row<TData>[]) => (props: HTMLAttributes<HTMLTableRowElement>) => JSX.Element | null,
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
rowComponent?: (
|
||||
rows: Row<TData>[],
|
||||
) => (props: HTMLAttributes<HTMLTableRowElement>) => JSX.Element | null
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
@@ -81,10 +77,12 @@ export function DataTable<TData, TValue>({
|
||||
data,
|
||||
rowComponent,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([{
|
||||
id: 'type',
|
||||
desc: true,
|
||||
}]);
|
||||
const [sorting, setSorting] = useState<SortingState>([
|
||||
{
|
||||
id: "type",
|
||||
desc: true,
|
||||
},
|
||||
])
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
@@ -94,41 +92,43 @@ export function DataTable<TData, TValue>({
|
||||
onSortingChange: setSorting,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const { rows } = table.getRowModel();
|
||||
const { rows } = table.getRowModel()
|
||||
|
||||
const [heightState, setHeight] = useState(0)
|
||||
const ref = useRef(null);
|
||||
const isDesktop = useMediaQuery("(min-width: 640px)");
|
||||
const ref = useRef(null)
|
||||
const isDesktop = useMediaQuery("(min-width: 640px)")
|
||||
|
||||
useEffect(() => {
|
||||
const calculateHeight = () => {
|
||||
if (ref.current) {
|
||||
const virtuosoElement = ref.current;
|
||||
let topOffset = 0;
|
||||
let currentElement = virtuosoElement as any;
|
||||
const virtuosoElement = ref.current
|
||||
let topOffset = 0
|
||||
let currentElement = virtuosoElement as any
|
||||
|
||||
// Calculate the total offset from the top of the document
|
||||
while (currentElement) {
|
||||
topOffset += currentElement.offsetTop || 0;
|
||||
currentElement = currentElement.offsetParent as HTMLElement;
|
||||
topOffset += currentElement.offsetTop || 0
|
||||
currentElement = currentElement.offsetParent as HTMLElement
|
||||
}
|
||||
|
||||
const totalHeight = window.innerHeight;
|
||||
const calculatedHeight = totalHeight - topOffset;
|
||||
const totalHeight = window.innerHeight
|
||||
const calculatedHeight = totalHeight - topOffset
|
||||
|
||||
setHeight(calculatedHeight);
|
||||
setHeight(calculatedHeight)
|
||||
}
|
||||
};
|
||||
calculateHeight(); // Initial calculation
|
||||
}
|
||||
calculateHeight() // Initial calculation
|
||||
|
||||
if (isDesktop) {
|
||||
window.addEventListener('resize', calculateHeight);
|
||||
window.addEventListener("resize", calculateHeight)
|
||||
}
|
||||
|
||||
return () => { if (isDesktop) window.removeEventListener('resize', calculateHeight); }
|
||||
}, [isDesktop]);
|
||||
return () => {
|
||||
if (isDesktop) window.removeEventListener("resize", calculateHeight)
|
||||
}
|
||||
}, [isDesktop])
|
||||
|
||||
return (
|
||||
<div className="rounded-md border" ref={ref} style={{ height: heightState }}>
|
||||
@@ -158,11 +158,12 @@ export function DataTable<TData, TValue>({
|
||||
{...{
|
||||
style: header.column.getCanSort()
|
||||
? {
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}
|
||||
: {},
|
||||
onClick: header.column.getToggleSortingHandler(),
|
||||
onClick:
|
||||
header.column.getToggleSortingHandler(),
|
||||
}}
|
||||
>
|
||||
{flexRender(
|
||||
@@ -175,12 +176,12 @@ export function DataTable<TData, TValue>({
|
||||
</div>
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { useRouteError, useNavigate } from "react-router-dom";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardFooter } from "@/components/ui/card";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardFooter } from "@/components/ui/card"
|
||||
import { AlertCircle } from "lucide-react"
|
||||
import { useNavigate, useRouteError } from "react-router-dom"
|
||||
|
||||
interface RouterError {
|
||||
statusText?: string;
|
||||
message?: string;
|
||||
status?: number;
|
||||
statusText?: string
|
||||
message?: string
|
||||
status?: number
|
||||
}
|
||||
|
||||
export default function ErrorPage() {
|
||||
const error = useRouteError() as RouterError;
|
||||
const navigate = useNavigate();
|
||||
console.error(error);
|
||||
const error = useRouteError() as RouterError
|
||||
const navigate = useNavigate()
|
||||
console.error(error)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen w-full flex items-center justify-center bg-background p-4">
|
||||
@@ -32,15 +32,11 @@ export default function ErrorPage() {
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-center pb-6">
|
||||
<Button
|
||||
variant="default"
|
||||
size="lg"
|
||||
onClick={() => navigate('/dashboard')}
|
||||
>
|
||||
<Button variant="default" size="lg" onClick={() => navigate("/dashboard")}>
|
||||
Back to Dashboard
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,51 +1,55 @@
|
||||
import { createContext, useContext, useEffect, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useMainStore } from "./useMainStore";
|
||||
import { AuthContextProps } from "@/types";
|
||||
import { getProfile, login as loginRequest } from "@/api/user";
|
||||
import { toast } from "sonner";
|
||||
import { getProfile, login as loginRequest } from "@/api/user"
|
||||
import { AuthContextProps } from "@/types"
|
||||
import { createContext, useContext, useEffect, useMemo } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useMainStore } from "./useMainStore"
|
||||
|
||||
const AuthContext = createContext<AuthContextProps>({
|
||||
profile: undefined,
|
||||
login: () => { },
|
||||
logout: () => { },
|
||||
});
|
||||
login: () => {},
|
||||
logout: () => {},
|
||||
})
|
||||
|
||||
export const AuthProvider = ({ children }: {
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const profile = useMainStore(store => store.profile)
|
||||
const setProfile = useMainStore(store => store.setProfile)
|
||||
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
const profile = useMainStore((store) => store.profile)
|
||||
const setProfile = useMainStore((store) => store.setProfile)
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
;(async () => {
|
||||
try {
|
||||
const user = await getProfile();
|
||||
setProfile(user);
|
||||
} catch (error) {
|
||||
setProfile(undefined);
|
||||
const user = await getProfile()
|
||||
setProfile(user)
|
||||
} catch (error: any) {
|
||||
setProfile(undefined)
|
||||
console.log("Error fetching profile", error)
|
||||
}
|
||||
})();
|
||||
})()
|
||||
}, [])
|
||||
|
||||
const navigate = useNavigate();
|
||||
const navigate = useNavigate()
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
await loginRequest(username, password);
|
||||
const user = await getProfile();
|
||||
setProfile(user);
|
||||
navigate("/dashboard");
|
||||
await loginRequest(username, password)
|
||||
const user = await getProfile()
|
||||
setProfile(user)
|
||||
navigate("/dashboard")
|
||||
} catch (error: any) {
|
||||
toast(error.message);
|
||||
toast(error.message)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
document.cookie.split(";").forEach(function (c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
|
||||
setProfile(undefined);
|
||||
navigate("/dashboard/login", { replace: true });
|
||||
};
|
||||
document.cookie.split(";").forEach(function (c) {
|
||||
document.cookie = c
|
||||
.replace(/^ +/, "")
|
||||
.replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/")
|
||||
})
|
||||
setProfile(undefined)
|
||||
navigate("/dashboard/login", { replace: true })
|
||||
}
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
@@ -53,11 +57,11 @@ export const AuthProvider = ({ children }: {
|
||||
login,
|
||||
logout,
|
||||
}),
|
||||
[profile]
|
||||
);
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
};
|
||||
[profile],
|
||||
)
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
||||
}
|
||||
|
||||
export const useAuth = () => {
|
||||
return useContext(AuthContext);
|
||||
};
|
||||
return useContext(AuthContext)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { MainStore } from '@/types'
|
||||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { MainStore } from "@/types"
|
||||
import { create } from "zustand"
|
||||
import { createJSONStorage, persist } from "zustand/middleware"
|
||||
|
||||
export const useMainStore = create<MainStore, [['zustand/persist', MainStore]]>(
|
||||
export const useMainStore = create<MainStore, [["zustand/persist", MainStore]]>(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
profile: get()?.profile,
|
||||
setProfile: profile => set({ profile }),
|
||||
setProfile: (profile) => set({ profile }),
|
||||
}),
|
||||
{
|
||||
name: 'mainStore',
|
||||
name: "mainStore",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
},
|
||||
),
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
export function useMediaQuery(query: string) {
|
||||
const [value, setValue] = React.useState(false)
|
||||
const [value, setValue] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
function onChange(event: MediaQueryListEvent) {
|
||||
setValue(event.matches)
|
||||
}
|
||||
React.useEffect(() => {
|
||||
function onChange(event: MediaQueryListEvent) {
|
||||
setValue(event.matches)
|
||||
}
|
||||
|
||||
const result = matchMedia(query)
|
||||
result.addEventListener("change", onChange)
|
||||
setValue(result.matches)
|
||||
const result = matchMedia(query)
|
||||
result.addEventListener("change", onChange)
|
||||
setValue(result.matches)
|
||||
|
||||
return () => result.removeEventListener("change", onChange)
|
||||
}, [query])
|
||||
return () => result.removeEventListener("change", onChange)
|
||||
}, [query])
|
||||
|
||||
return value
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -1,56 +1,71 @@
|
||||
import { createContext, useContext, useEffect, useMemo } from "react"
|
||||
import { useNotificationStore } from "./useNotificationStore"
|
||||
import { getNotificationGroups } from "@/api/notification-group"
|
||||
import { getNotification } from "@/api/notification"
|
||||
import { getNotificationGroups } from "@/api/notification-group"
|
||||
import { NotificationContextProps } from "@/types"
|
||||
import { createContext, useContext, useEffect, useMemo } from "react"
|
||||
import { useLocation } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
const NotificationContext = createContext<NotificationContextProps>({});
|
||||
import { useNotificationStore } from "./useNotificationStore"
|
||||
|
||||
const NotificationContext = createContext<NotificationContextProps>({})
|
||||
|
||||
interface NotificationProviderProps {
|
||||
children: React.ReactNode;
|
||||
withNotifier?: boolean;
|
||||
withNotifierGroup?: boolean;
|
||||
children: React.ReactNode
|
||||
withNotifier?: boolean
|
||||
withNotifierGroup?: boolean
|
||||
}
|
||||
|
||||
export const NotificationProvider: React.FC<NotificationProviderProps> = ({ children, withNotifier, withNotifierGroup }) => {
|
||||
const notifierGroup = useNotificationStore(store => store.notifierGroup);
|
||||
const setNotifierGroup = useNotificationStore(store => store.setNotifierGroup);
|
||||
export const NotificationProvider: React.FC<NotificationProviderProps> = ({
|
||||
children,
|
||||
withNotifier,
|
||||
withNotifierGroup,
|
||||
}) => {
|
||||
const notifierGroup = useNotificationStore((store) => store.notifierGroup)
|
||||
const setNotifierGroup = useNotificationStore((store) => store.setNotifierGroup)
|
||||
|
||||
const notifiers = useNotificationStore(store => store.notifiers);
|
||||
const setNotifier = useNotificationStore(store => store.setNotifier);
|
||||
const notifiers = useNotificationStore((store) => store.notifiers)
|
||||
const setNotifier = useNotificationStore((store) => store.setNotifier)
|
||||
|
||||
const location = useLocation();
|
||||
const location = useLocation()
|
||||
|
||||
useEffect(() => {
|
||||
if (withNotifierGroup)
|
||||
(async () => {
|
||||
try {
|
||||
const ng = await getNotificationGroups();
|
||||
setNotifierGroup(ng);
|
||||
} catch (error) {
|
||||
setNotifierGroup(undefined);
|
||||
const ng = await getNotificationGroups()
|
||||
setNotifierGroup(ng)
|
||||
} catch (error: any) {
|
||||
toast("NotificationProvider Error", {
|
||||
description: error.message,
|
||||
})
|
||||
setNotifierGroup(undefined)
|
||||
}
|
||||
})();
|
||||
})()
|
||||
if (withNotifier)
|
||||
(async () => {
|
||||
try {
|
||||
const n = await getNotification();
|
||||
const nData = n.map(({ id, name }) => ({ id, name }));
|
||||
setNotifier(nData);
|
||||
} catch (error) {
|
||||
setNotifier(undefined);
|
||||
const n = await getNotification()
|
||||
const nData = n.map(({ id, name }) => ({ id, name }))
|
||||
setNotifier(nData)
|
||||
} catch (error: any) {
|
||||
toast("NotificationProvider Error", {
|
||||
description: error.message,
|
||||
})
|
||||
setNotifier(undefined)
|
||||
}
|
||||
})();
|
||||
})()
|
||||
}, [location.pathname])
|
||||
|
||||
const value: NotificationContextProps = useMemo(() => ({
|
||||
notifiers: notifiers,
|
||||
notifierGroup: notifierGroup,
|
||||
}), [notifiers, notifierGroup]);
|
||||
return <NotificationContext.Provider value={value}>{children}</NotificationContext.Provider>;
|
||||
const value: NotificationContextProps = useMemo(
|
||||
() => ({
|
||||
notifiers: notifiers,
|
||||
notifierGroup: notifierGroup,
|
||||
}),
|
||||
[notifiers, notifierGroup],
|
||||
)
|
||||
return <NotificationContext.Provider value={value}>{children}</NotificationContext.Provider>
|
||||
}
|
||||
|
||||
export const useNotification = () => {
|
||||
return useContext(NotificationContext);
|
||||
};
|
||||
return useContext(NotificationContext)
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import { NotificationStore } from '@/types'
|
||||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { NotificationStore } from "@/types"
|
||||
import { create } from "zustand"
|
||||
import { createJSONStorage, persist } from "zustand/middleware"
|
||||
|
||||
export const useNotificationStore = create<NotificationStore, [['zustand/persist', NotificationStore]]>(
|
||||
export const useNotificationStore = create<
|
||||
NotificationStore,
|
||||
[["zustand/persist", NotificationStore]]
|
||||
>(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
notifiers: get()?.notifiers,
|
||||
notifierGroup: get()?.notifierGroup,
|
||||
setNotifier: notifiers => set({ notifiers }),
|
||||
setNotifierGroup: notifierGroup => set({ notifierGroup }),
|
||||
setNotifier: (notifiers) => set({ notifiers }),
|
||||
setNotifierGroup: (notifierGroup) => set({ notifierGroup }),
|
||||
}),
|
||||
{
|
||||
name: 'notificationStore',
|
||||
name: "notificationStore",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
},
|
||||
),
|
||||
|
||||
@@ -1,56 +1,71 @@
|
||||
import { createContext, useContext, useEffect, useMemo } from "react"
|
||||
import { useServerStore } from "./useServerStore"
|
||||
import { getServerGroups } from "@/api/server-group"
|
||||
import { getServers } from "@/api/server"
|
||||
import { getServerGroups } from "@/api/server-group"
|
||||
import { ServerContextProps } from "@/types"
|
||||
import { createContext, useContext, useEffect, useMemo } from "react"
|
||||
import { useLocation } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
const ServerContext = createContext<ServerContextProps>({});
|
||||
import { useServerStore } from "./useServerStore"
|
||||
|
||||
const ServerContext = createContext<ServerContextProps>({})
|
||||
|
||||
interface ServerProviderProps {
|
||||
children: React.ReactNode;
|
||||
withServer?: boolean;
|
||||
withServerGroup?: boolean;
|
||||
children: React.ReactNode
|
||||
withServer?: boolean
|
||||
withServerGroup?: boolean
|
||||
}
|
||||
|
||||
export const ServerProvider: React.FC<ServerProviderProps> = ({ children, withServer, withServerGroup }) => {
|
||||
const serverGroup = useServerStore(store => store.serverGroup);
|
||||
const setServerGroup = useServerStore(store => store.setServerGroup);
|
||||
export const ServerProvider: React.FC<ServerProviderProps> = ({
|
||||
children,
|
||||
withServer,
|
||||
withServerGroup,
|
||||
}) => {
|
||||
const serverGroup = useServerStore((store) => store.serverGroup)
|
||||
const setServerGroup = useServerStore((store) => store.setServerGroup)
|
||||
|
||||
const server = useServerStore(store => store.server);
|
||||
const setServer = useServerStore(store => store.setServer);
|
||||
const server = useServerStore((store) => store.server)
|
||||
const setServer = useServerStore((store) => store.setServer)
|
||||
|
||||
const location = useLocation();
|
||||
const location = useLocation()
|
||||
|
||||
useEffect(() => {
|
||||
if (withServerGroup)
|
||||
(async () => {
|
||||
try {
|
||||
const sg = await getServerGroups();
|
||||
setServerGroup(sg);
|
||||
} catch (error) {
|
||||
setServerGroup(undefined);
|
||||
const sg = await getServerGroups()
|
||||
setServerGroup(sg)
|
||||
} catch (error: any) {
|
||||
toast("ServerProvider Error", {
|
||||
description: error.message,
|
||||
})
|
||||
setServerGroup(undefined)
|
||||
}
|
||||
})();
|
||||
})()
|
||||
if (withServer)
|
||||
(async () => {
|
||||
try {
|
||||
const s = await getServers();
|
||||
const serverData = s.map(({ id, name }) => ({ id, name }));
|
||||
setServer(serverData);
|
||||
} catch (error) {
|
||||
setServer(undefined);
|
||||
const s = await getServers()
|
||||
const serverData = s.map(({ id, name }) => ({ id, name }))
|
||||
setServer(serverData)
|
||||
} catch (error: any) {
|
||||
toast("ServerProvider Error", {
|
||||
description: error.message,
|
||||
})
|
||||
setServer(undefined)
|
||||
}
|
||||
})();
|
||||
})()
|
||||
}, [location.pathname])
|
||||
|
||||
const value: ServerContextProps = useMemo(() => ({
|
||||
servers: server,
|
||||
serverGroups: serverGroup,
|
||||
}), [server, serverGroup]);
|
||||
return <ServerContext.Provider value={value}>{children}</ServerContext.Provider>;
|
||||
const value: ServerContextProps = useMemo(
|
||||
() => ({
|
||||
servers: server,
|
||||
serverGroups: serverGroup,
|
||||
}),
|
||||
[server, serverGroup],
|
||||
)
|
||||
return <ServerContext.Provider value={value}>{children}</ServerContext.Provider>
|
||||
}
|
||||
|
||||
export const useServer = () => {
|
||||
return useContext(ServerContext);
|
||||
};
|
||||
return useContext(ServerContext)
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { ServerStore } from '@/types'
|
||||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { ServerStore } from "@/types"
|
||||
import { create } from "zustand"
|
||||
import { createJSONStorage, persist } from "zustand/middleware"
|
||||
|
||||
export const useServerStore = create<ServerStore, [['zustand/persist', ServerStore]]>(
|
||||
export const useServerStore = create<ServerStore, [["zustand/persist", ServerStore]]>(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
server: get()?.server,
|
||||
serverGroup: get()?.serverGroup,
|
||||
setServer: server => set({ server }),
|
||||
setServerGroup: serverGroup => set({ serverGroup }),
|
||||
setServer: (server) => set({ server }),
|
||||
setServerGroup: (serverGroup) => set({ serverGroup }),
|
||||
}),
|
||||
{
|
||||
name: 'serverStore',
|
||||
name: "serverStore",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
},
|
||||
),
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { ModelSettingResponse } from "@/types";
|
||||
import useSWR from "swr";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { ModelSettingResponse } from "@/types"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function useSetting() {
|
||||
const { data } = useSWR<ModelSettingResponse>(
|
||||
"/api/v1/setting",
|
||||
swrFetcher
|
||||
);
|
||||
return data;
|
||||
const { data } = useSWR<ModelSettingResponse>("/api/v1/setting", swrFetcher)
|
||||
return data
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import { createTerminal } from "@/api/terminal";
|
||||
import { ModelCreateTerminalResponse } from "@/types";
|
||||
import { useState, useEffect } from "react";
|
||||
import { createTerminal } from "@/api/terminal"
|
||||
import { ModelCreateTerminalResponse } from "@/types"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
export default function useTerminal(serverId?: number) {
|
||||
const [terminal, setTerminal] = useState<ModelCreateTerminalResponse | null>(null);
|
||||
const [terminal, setTerminal] = useState<ModelCreateTerminalResponse | null>(null)
|
||||
|
||||
async function fetchTerminal() {
|
||||
try {
|
||||
const response = await createTerminal(serverId!);
|
||||
setTerminal(response);
|
||||
const response = await createTerminal(serverId!)
|
||||
setTerminal(response)
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch terminal:", error);
|
||||
console.error("Failed to fetch terminal:", error)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverId) return;
|
||||
fetchTerminal();
|
||||
}, [serverId]);
|
||||
if (!serverId) return
|
||||
fetchTerminal()
|
||||
}, [serverId])
|
||||
|
||||
return terminal;
|
||||
return terminal
|
||||
}
|
||||
|
||||
127
src/index.css
127
src/index.css
@@ -3,87 +3,86 @@
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--radius: 0.5rem;
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 0 0% 3.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 0 0% 3.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 0 0% 3.9%;
|
||||
--primary: 0 0% 9%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 0 0% 96.1%;
|
||||
--secondary-foreground: 0 0% 9%;
|
||||
--muted: 0 0% 96.1%;
|
||||
--muted-foreground: 0 0% 45.1%;
|
||||
--accent: 0 0% 96.1%;
|
||||
--accent-foreground: 0 0% 9%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 89.8%;
|
||||
--input: 0 0% 89.8%;
|
||||
--ring: 0 0% 3.9%;
|
||||
--chart-1: 12 76% 61%;
|
||||
--chart-2: 173 58% 39%;
|
||||
--chart-3: 197 37% 24%;
|
||||
--chart-4: 43 74% 66%;
|
||||
--chart-5: 27 87% 67%
|
||||
}
|
||||
:root {
|
||||
--radius: 0.5rem;
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 0 0% 3.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 0 0% 3.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 0 0% 3.9%;
|
||||
--primary: 0 0% 9%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 0 0% 96.1%;
|
||||
--secondary-foreground: 0 0% 9%;
|
||||
--muted: 0 0% 96.1%;
|
||||
--muted-foreground: 0 0% 45.1%;
|
||||
--accent: 0 0% 96.1%;
|
||||
--accent-foreground: 0 0% 9%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 89.8%;
|
||||
--input: 0 0% 89.8%;
|
||||
--ring: 0 0% 3.9%;
|
||||
--chart-1: 12 76% 61%;
|
||||
--chart-2: 173 58% 39%;
|
||||
--chart-3: 197 37% 24%;
|
||||
--chart-4: 43 74% 66%;
|
||||
--chart-5: 27 87% 67%;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 0 0% 3.9%;
|
||||
--foreground: 0 0% 98%;
|
||||
--card: 0 0% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
--popover: 0 0% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 0 0% 9%;
|
||||
--secondary: 0 0% 14.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 0 0% 14.9%;
|
||||
--muted-foreground: 0 0% 63.9%;
|
||||
--accent: 0 0% 14.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 14.9%;
|
||||
--input: 0 0% 14.9%;
|
||||
--ring: 0 0% 83.1%;
|
||||
--chart-1: 220 70% 50%;
|
||||
--chart-2: 160 60% 45%;
|
||||
--chart-3: 30 80% 55%;
|
||||
--chart-4: 280 65% 60%;
|
||||
--chart-5: 340 75% 55%
|
||||
}
|
||||
.dark {
|
||||
--background: 0 0% 9%;
|
||||
--foreground: 0 0% 98%;
|
||||
--card: 0 0% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
--popover: 0 0% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 0 0% 9%;
|
||||
--secondary: 0 0% 14.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 0 0% 14.9%;
|
||||
--muted-foreground: 0 0% 63.9%;
|
||||
--accent: 0 0% 14.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 14.9%;
|
||||
--input: 0 0% 14.9%;
|
||||
--ring: 0 0% 83.1%;
|
||||
--chart-1: 220 70% 50%;
|
||||
--chart-2: 160 60% 45%;
|
||||
--chart-3: 30 80% 55%;
|
||||
--chart-4: 280 65% 60%;
|
||||
--chart-5: 340 75% 55%;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
@apply w-2.5 h-2.5;
|
||||
|
||||
@apply h-2.5 w-2.5;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
@apply bg-transparent
|
||||
@apply bg-transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply rounded-full bg-border border-[1px] border-transparent border-solid bg-clip-padding;
|
||||
@apply rounded-full border-[1px] border-solid border-transparent bg-border bg-clip-padding;
|
||||
}
|
||||
|
||||
@@ -1,71 +1,70 @@
|
||||
let receivedLength = 0;
|
||||
let expectedLength = 0;
|
||||
let root: FileSystemDirectoryHandle;
|
||||
let draftHandle: FileSystemFileHandle;
|
||||
let accessHandle: FileSystemSyncAccessHandle;
|
||||
let receivedLength = 0
|
||||
let expectedLength = 0
|
||||
let root: FileSystemDirectoryHandle
|
||||
let draftHandle: FileSystemFileHandle
|
||||
let accessHandle: FileSystemSyncAccessHandle
|
||||
|
||||
enum Operation {
|
||||
WriteHeader = 1,
|
||||
WriteChunks,
|
||||
DeleteFiles,
|
||||
};
|
||||
}
|
||||
|
||||
onmessage = async function (event) {
|
||||
try {
|
||||
const { operation, arrayBuffer, fileName } = event.data;
|
||||
const { operation, arrayBuffer, fileName } = event.data
|
||||
|
||||
switch (operation) {
|
||||
case Operation.WriteHeader: {
|
||||
const dataView = new DataView(arrayBuffer);
|
||||
expectedLength = Number(dataView.getBigUint64(4, false));
|
||||
receivedLength = 0;
|
||||
const dataView = new DataView(arrayBuffer)
|
||||
expectedLength = Number(dataView.getBigUint64(4, false))
|
||||
receivedLength = 0
|
||||
|
||||
// Create a new temporary file
|
||||
root = await navigator.storage.getDirectory();
|
||||
draftHandle = await root.getFileHandle(fileName, { create: true });
|
||||
accessHandle = await draftHandle.createSyncAccessHandle();
|
||||
root = await navigator.storage.getDirectory()
|
||||
draftHandle = await root.getFileHandle(fileName, { create: true })
|
||||
accessHandle = await draftHandle.createSyncAccessHandle()
|
||||
|
||||
// Inform that file handle is created
|
||||
const dataChunk = arrayBuffer.slice(12);
|
||||
receivedLength += dataChunk.byteLength;
|
||||
accessHandle.write(dataChunk, { at: 0 });
|
||||
const progress = 'got handle';
|
||||
postMessage({ type: 1, progress: progress });
|
||||
break;
|
||||
const dataChunk = arrayBuffer.slice(12)
|
||||
receivedLength += dataChunk.byteLength
|
||||
accessHandle.write(dataChunk, { at: 0 })
|
||||
const progress = "got handle"
|
||||
postMessage({ type: 1, progress: progress })
|
||||
break
|
||||
}
|
||||
case Operation.WriteChunks: {
|
||||
if (!accessHandle) {
|
||||
throw new Error('accessHandle is undefined');
|
||||
throw new Error("accessHandle is undefined")
|
||||
}
|
||||
|
||||
const dataChunk = arrayBuffer;
|
||||
accessHandle.write(dataChunk, { at: receivedLength });
|
||||
receivedLength += dataChunk.byteLength;
|
||||
const dataChunk = arrayBuffer
|
||||
accessHandle.write(dataChunk, { at: receivedLength })
|
||||
receivedLength += dataChunk.byteLength
|
||||
|
||||
if (receivedLength === expectedLength) {
|
||||
accessHandle.flush();
|
||||
accessHandle.close();
|
||||
accessHandle.flush()
|
||||
accessHandle.close()
|
||||
|
||||
const fileBlob = await draftHandle.getFile();
|
||||
const blob = new Blob([fileBlob], { type: 'application/octet-stream' });
|
||||
const fileBlob = await draftHandle.getFile()
|
||||
const blob = new Blob([fileBlob], { type: "application/octet-stream" })
|
||||
|
||||
postMessage({ type: 2, blob: blob, fileName: fileName });
|
||||
postMessage({ type: 2, blob: blob, fileName: fileName })
|
||||
}
|
||||
break;
|
||||
break
|
||||
}
|
||||
case Operation.DeleteFiles: {
|
||||
for await (const [name, handle] of root.entries()) {
|
||||
if (handle.kind === 'file') {
|
||||
await root.removeEntry(name);
|
||||
} else if (handle.kind === 'directory') {
|
||||
await root.removeEntry(name, { recursive: true });
|
||||
if (handle.kind === "file") {
|
||||
await root.removeEntry(name)
|
||||
} else if (handle.kind === "directory") {
|
||||
await root.removeEntry(name, { recursive: true })
|
||||
}
|
||||
}
|
||||
break;
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error)
|
||||
postMessage({ type: 0, error: error.message });
|
||||
if (error instanceof Error) postMessage({ type: 0, error: error.message })
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import i18n from "i18next";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
import i18n from "i18next"
|
||||
import { initReactI18next } from "react-i18next"
|
||||
|
||||
import enTranslation from "../locales/en/translation.json";
|
||||
import itTranslation from "../locales/it/translation.json";
|
||||
import zhCNTranslation from "../locales/zh-CN/translation.json";
|
||||
import zhTWTranslation from "../locales/zh-TW/translation.json";
|
||||
import enTranslation from "../locales/en/translation.json"
|
||||
import itTranslation from "../locales/it/translation.json"
|
||||
import zhCNTranslation from "../locales/zh-CN/translation.json"
|
||||
import zhTWTranslation from "../locales/zh-TW/translation.json"
|
||||
|
||||
const resources = {
|
||||
en: {
|
||||
@@ -19,24 +19,23 @@ const resources = {
|
||||
"zh-TW": {
|
||||
translation: zhTWTranslation,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const getStoredLanguage = () => {
|
||||
return localStorage.getItem("language") || "zh-CN";
|
||||
};
|
||||
return localStorage.getItem("language") || "zh-CN"
|
||||
}
|
||||
|
||||
i18n.use(initReactI18next)
|
||||
.init({
|
||||
resources,
|
||||
lng: getStoredLanguage(), // 使用localStorage中存储的语言或默认值
|
||||
fallbackLng: "en", // 当前语言的翻译没有找到时,使用的备选语言
|
||||
interpolation: {
|
||||
escapeValue: false, // react已经安全地转义
|
||||
},
|
||||
});
|
||||
i18n.use(initReactI18next).init({
|
||||
resources,
|
||||
lng: getStoredLanguage(), // 使用localStorage中存储的语言或默认值
|
||||
fallbackLng: "en", // 当前语言的翻译没有找到时,使用的备选语言
|
||||
interpolation: {
|
||||
escapeValue: false, // react已经安全地转义
|
||||
},
|
||||
})
|
||||
|
||||
i18n.on("languageChanged", (lng) => {
|
||||
localStorage.setItem("language", lng);
|
||||
});
|
||||
localStorage.setItem("language", lng)
|
||||
})
|
||||
|
||||
export default i18n;
|
||||
export default i18n
|
||||
|
||||
424
src/lib/utils.ts
424
src/lib/utils.ts
@@ -1,262 +1,264 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { FMEntry, FMOpcode, ModelIP } from "@/types"
|
||||
import { type ClassValue, clsx } from "clsx"
|
||||
import copy from "copy-to-clipboard"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { z } from "zod"
|
||||
import { FMEntry, FMOpcode, ModelIP } from "@/types"
|
||||
|
||||
import FMWorker from "./fm?worker"
|
||||
import copy from "copy-to-clipboard"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
const emptyStringToUndefined = z.literal('').transform(() => undefined);
|
||||
const emptyStringToUndefined = z.literal("").transform(() => undefined)
|
||||
|
||||
export function asOptionalField<T extends z.ZodTypeAny>(schema: T) {
|
||||
return schema.optional().or(emptyStringToUndefined);
|
||||
return schema.optional().or(emptyStringToUndefined)
|
||||
}
|
||||
|
||||
export const conv = {
|
||||
recordToStr: (rec: Record<string, boolean>) => {
|
||||
const arr: string[] = [];
|
||||
for (const key in rec) {
|
||||
arr.push(key);
|
||||
}
|
||||
recordToStr: (rec: Record<string, boolean>) => {
|
||||
const arr: string[] = []
|
||||
for (const key in rec) {
|
||||
arr.push(key)
|
||||
}
|
||||
|
||||
return arr.join(',');
|
||||
},
|
||||
strToRecord: (str: string) => {
|
||||
const arr = str.split(',');
|
||||
return arr.reduce((acc, num) => {
|
||||
acc[num] = true;
|
||||
return acc;
|
||||
}, {} as Record<string, boolean>);
|
||||
},
|
||||
arrToStr: <T>(arr: T[]) => {
|
||||
return arr.join(',');
|
||||
},
|
||||
strToArr: (str: string) => {
|
||||
return str.split(',').filter(Boolean) || [];
|
||||
},
|
||||
recordToArr: <T>(rec: Record<string, T>) => {
|
||||
const arr: T[] = [];
|
||||
for (const val of Object.values(rec)) {
|
||||
arr.push(val);
|
||||
}
|
||||
return arr;
|
||||
},
|
||||
recordToStrArr: <T>(rec: Record<string, T>) => {
|
||||
const arr: string[] = [];
|
||||
for (const val of Object.keys(rec)) {
|
||||
arr.push(val);
|
||||
}
|
||||
return arr;
|
||||
},
|
||||
arrToRecord: (arr: string[]) => {
|
||||
const rec: Record<string, boolean> = {};
|
||||
for (const val of arr) {
|
||||
rec[val] = true;
|
||||
}
|
||||
return rec;
|
||||
}
|
||||
return arr.join(",")
|
||||
},
|
||||
strToRecord: (str: string) => {
|
||||
const arr = str.split(",")
|
||||
return arr.reduce(
|
||||
(acc, num) => {
|
||||
acc[num] = true
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, boolean>,
|
||||
)
|
||||
},
|
||||
arrToStr: <T>(arr: T[]) => {
|
||||
return arr.join(",")
|
||||
},
|
||||
strToArr: (str: string) => {
|
||||
return str.split(",").filter(Boolean) || []
|
||||
},
|
||||
recordToArr: <T>(rec: Record<string, T>) => {
|
||||
const arr: T[] = []
|
||||
for (const val of Object.values(rec)) {
|
||||
arr.push(val)
|
||||
}
|
||||
return arr
|
||||
},
|
||||
recordToStrArr: <T>(rec: Record<string, T>) => {
|
||||
const arr: string[] = []
|
||||
for (const val of Object.keys(rec)) {
|
||||
arr.push(val)
|
||||
}
|
||||
return arr
|
||||
},
|
||||
arrToRecord: (arr: string[]) => {
|
||||
const rec: Record<string, boolean> = {}
|
||||
for (const val of arr) {
|
||||
rec[val] = true
|
||||
}
|
||||
return rec
|
||||
},
|
||||
}
|
||||
|
||||
export const sleep = (ms: number) => {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
};
|
||||
|
||||
export const fm = {
|
||||
parseFMList: async (buf: ArrayBufferLike) => {
|
||||
const dataView = new DataView(buf);
|
||||
let offset = 4; // Identifier: 4 bytes (NZFN), not needed here
|
||||
|
||||
const pathLength = dataView.getUint32(offset);
|
||||
offset += 4; // File Path Length: 4 bytes
|
||||
|
||||
const pathBuf = new Uint8Array(buf, offset, pathLength);
|
||||
const path = new TextDecoder('utf-8').decode(pathBuf);
|
||||
offset += pathLength; // Path: N bytes
|
||||
|
||||
const fmList: FMEntry[] = [];
|
||||
while (offset < dataView.byteLength) {
|
||||
const fileType = dataView.getUint8(offset);
|
||||
offset += 1; // File Type: 1 byte
|
||||
|
||||
const nameLength = dataView.getUint8(offset);
|
||||
offset += 1; // File Name Length: 1 byte
|
||||
|
||||
const nameBuf = new Uint8Array(buf, offset, nameLength);
|
||||
const name = new TextDecoder('utf-8').decode(nameBuf);
|
||||
offset += nameLength; // File Name: N bytes
|
||||
|
||||
fmList.push({
|
||||
type: fileType,
|
||||
name: name,
|
||||
})
|
||||
}
|
||||
|
||||
return { path, fmList };
|
||||
},
|
||||
|
||||
buildUploadHeader: ({ path, file }: { path: string, file: File }) => {
|
||||
const filePath = `${path}/${file.name}`;
|
||||
|
||||
// Build header (opcode + file size + path)
|
||||
const filePathBytes = new TextEncoder().encode(filePath);
|
||||
const header = new ArrayBuffer(1 + 8 + filePathBytes.length);
|
||||
const headerView = new DataView(header);
|
||||
|
||||
headerView.setUint8(0, FMOpcode.Upload);
|
||||
headerView.setBigUint64(1, BigInt(file.size), false);
|
||||
|
||||
new Uint8Array(header, 9).set(filePathBytes);
|
||||
return header;
|
||||
},
|
||||
|
||||
readFileAsArrayBuffer: async (blob: Blob): Promise<string | ArrayBuffer | null> => {
|
||||
const reader = new FileReader();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsArrayBuffer(blob);
|
||||
});
|
||||
},
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
export const fmWorker = new FMWorker();
|
||||
export const fm = {
|
||||
parseFMList: async (buf: ArrayBufferLike) => {
|
||||
const dataView = new DataView(buf)
|
||||
let offset = 4 // Identifier: 4 bytes (NZFN), not needed here
|
||||
|
||||
const pathLength = dataView.getUint32(offset)
|
||||
offset += 4 // File Path Length: 4 bytes
|
||||
|
||||
const pathBuf = new Uint8Array(buf, offset, pathLength)
|
||||
const path = new TextDecoder("utf-8").decode(pathBuf)
|
||||
offset += pathLength // Path: N bytes
|
||||
|
||||
const fmList: FMEntry[] = []
|
||||
while (offset < dataView.byteLength) {
|
||||
const fileType = dataView.getUint8(offset)
|
||||
offset += 1 // File Type: 1 byte
|
||||
|
||||
const nameLength = dataView.getUint8(offset)
|
||||
offset += 1 // File Name Length: 1 byte
|
||||
|
||||
const nameBuf = new Uint8Array(buf, offset, nameLength)
|
||||
const name = new TextDecoder("utf-8").decode(nameBuf)
|
||||
offset += nameLength // File Name: N bytes
|
||||
|
||||
fmList.push({
|
||||
type: fileType,
|
||||
name: name,
|
||||
})
|
||||
}
|
||||
|
||||
return { path, fmList }
|
||||
},
|
||||
|
||||
buildUploadHeader: ({ path, file }: { path: string; file: File }) => {
|
||||
const filePath = `${path}/${file.name}`
|
||||
|
||||
// Build header (opcode + file size + path)
|
||||
const filePathBytes = new TextEncoder().encode(filePath)
|
||||
const header = new ArrayBuffer(1 + 8 + filePathBytes.length)
|
||||
const headerView = new DataView(header)
|
||||
|
||||
headerView.setUint8(0, FMOpcode.Upload)
|
||||
headerView.setBigUint64(1, BigInt(file.size), false)
|
||||
|
||||
new Uint8Array(header, 9).set(filePathBytes)
|
||||
return header
|
||||
},
|
||||
|
||||
readFileAsArrayBuffer: async (blob: Blob): Promise<string | ArrayBuffer | null> => {
|
||||
const reader = new FileReader()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
reader.onload = () => resolve(reader.result)
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsArrayBuffer(blob)
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export const fmWorker = new FMWorker()
|
||||
|
||||
export function formatPath(path: string) {
|
||||
return path.replace(/\/{2,}/g, '/');
|
||||
return path.replace(/\/{2,}/g, "/")
|
||||
}
|
||||
|
||||
export function joinIP(p?: ModelIP) {
|
||||
if (p) {
|
||||
if (p.ipv4_addr && p.ipv6_addr) {
|
||||
return `${p.ipv4_addr}/${p.ipv6_addr}`;
|
||||
} else if (p.ipv4_addr) {
|
||||
return p.ipv4_addr;
|
||||
if (p) {
|
||||
if (p.ipv4_addr && p.ipv6_addr) {
|
||||
return `${p.ipv4_addr}/${p.ipv6_addr}`
|
||||
} else if (p.ipv4_addr) {
|
||||
return p.ipv4_addr
|
||||
}
|
||||
return p.ipv6_addr
|
||||
}
|
||||
return p.ipv6_addr;
|
||||
}
|
||||
return '';
|
||||
return ""
|
||||
}
|
||||
|
||||
function base64toUint8Array(base64str: string) {
|
||||
const binary = atob(base64str);
|
||||
const len = binary.length;
|
||||
const buf = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
buf[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return buf;
|
||||
const binary = atob(base64str)
|
||||
const len = binary.length
|
||||
const buf = new Uint8Array(len)
|
||||
for (let i = 0; i < len; i++) {
|
||||
buf[i] = binary.charCodeAt(i)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
export function ip16Str(base64str: string) {
|
||||
const buf = base64toUint8Array(base64str);
|
||||
const ip4 = buf.slice(-6);
|
||||
if (ip4[0] === 255 && ip4[1] === 255) {
|
||||
return ip4.slice(2).join('.');
|
||||
}
|
||||
return ipv6BinaryToString(buf);
|
||||
const buf = base64toUint8Array(base64str)
|
||||
const ip4 = buf.slice(-6)
|
||||
if (ip4[0] === 255 && ip4[1] === 255) {
|
||||
return ip4.slice(2).join(".")
|
||||
}
|
||||
return ipv6BinaryToString(buf)
|
||||
}
|
||||
|
||||
const digits = '0123456789abcdef';
|
||||
const digits = "0123456789abcdef"
|
||||
|
||||
function appendHex(b: string[], x: number): void {
|
||||
if (x >= 0x1000) {
|
||||
b.push(digits[(x >> 12) & 0xf]);
|
||||
}
|
||||
if (x >= 0x100) {
|
||||
b.push(digits[(x >> 8) & 0xf]);
|
||||
}
|
||||
if (x >= 0x10) {
|
||||
b.push(digits[(x >> 4) & 0xf]);
|
||||
}
|
||||
b.push(digits[x & 0xf]);
|
||||
if (x >= 0x1000) {
|
||||
b.push(digits[(x >> 12) & 0xf])
|
||||
}
|
||||
if (x >= 0x100) {
|
||||
b.push(digits[(x >> 8) & 0xf])
|
||||
}
|
||||
if (x >= 0x10) {
|
||||
b.push(digits[(x >> 4) & 0xf])
|
||||
}
|
||||
b.push(digits[x & 0xf])
|
||||
}
|
||||
|
||||
function ipv6BinaryToString(ip: Uint8Array): string {
|
||||
let ipBytes: Uint8Array;
|
||||
let ipBytes: Uint8Array
|
||||
|
||||
if (ip.length !== 16) {
|
||||
ipBytes = new Uint8Array(16);
|
||||
const len = Math.min(ip.length, 16);
|
||||
ipBytes.set(ip.subarray(0, len));
|
||||
} else {
|
||||
ipBytes = ip;
|
||||
}
|
||||
|
||||
const hextets: number[] = [];
|
||||
for (let i = 0; i < 16; i += 2) {
|
||||
hextets.push((ipBytes[i] << 8) | ipBytes[i + 1]);
|
||||
}
|
||||
|
||||
let zeroStart = -1;
|
||||
let zeroLength = 0;
|
||||
|
||||
for (let i = 0; i <= hextets.length;) {
|
||||
let j = i;
|
||||
while (j < hextets.length && hextets[j] === 0) {
|
||||
j++;
|
||||
}
|
||||
const length = j - i;
|
||||
if (length >= 2 && length > zeroLength) {
|
||||
zeroStart = i;
|
||||
zeroLength = length;
|
||||
}
|
||||
if (j === i) {
|
||||
i++;
|
||||
if (ip.length !== 16) {
|
||||
ipBytes = new Uint8Array(16)
|
||||
const len = Math.min(ip.length, 16)
|
||||
ipBytes.set(ip.subarray(0, len))
|
||||
} else {
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
for (let i = 0; i < hextets.length; i++) {
|
||||
if (zeroLength > 0 && i === zeroStart) {
|
||||
parts.push('');
|
||||
i += zeroLength - 1;
|
||||
continue;
|
||||
ipBytes = ip
|
||||
}
|
||||
|
||||
if (parts.length > 0) {
|
||||
parts.push(':');
|
||||
const hextets: number[] = []
|
||||
for (let i = 0; i < 16; i += 2) {
|
||||
hextets.push((ipBytes[i] << 8) | ipBytes[i + 1])
|
||||
}
|
||||
|
||||
const b: string[] = [];
|
||||
appendHex(b, hextets[i]);
|
||||
parts.push(b.join(''));
|
||||
}
|
||||
let zeroStart = -1
|
||||
let zeroLength = 0
|
||||
|
||||
let ipv6 = parts.join('');
|
||||
for (let i = 0; i <= hextets.length; ) {
|
||||
let j = i
|
||||
while (j < hextets.length && hextets[j] === 0) {
|
||||
j++
|
||||
}
|
||||
const length = j - i
|
||||
if (length >= 2 && length > zeroLength) {
|
||||
zeroStart = i
|
||||
zeroLength = length
|
||||
}
|
||||
if (j === i) {
|
||||
i++
|
||||
} else {
|
||||
i = j
|
||||
}
|
||||
}
|
||||
|
||||
if (ipv6.startsWith('::')) {
|
||||
const parts: string[] = []
|
||||
for (let i = 0; i < hextets.length; i++) {
|
||||
if (zeroLength > 0 && i === zeroStart) {
|
||||
parts.push("")
|
||||
i += zeroLength - 1
|
||||
continue
|
||||
}
|
||||
|
||||
} else if (ipv6.startsWith(':')) {
|
||||
ipv6 = ':' + ipv6;
|
||||
}
|
||||
if (ipv6.endsWith('::')) {
|
||||
if (parts.length > 0) {
|
||||
parts.push(":")
|
||||
}
|
||||
|
||||
} else if (ipv6.endsWith(':')) {
|
||||
ipv6 = ipv6 + ':';
|
||||
}
|
||||
if (ipv6 === '') {
|
||||
ipv6 = '::';
|
||||
}
|
||||
const b: string[] = []
|
||||
appendHex(b, hextets[i])
|
||||
parts.push(b.join(""))
|
||||
}
|
||||
|
||||
return ipv6;
|
||||
let ipv6 = parts.join("")
|
||||
|
||||
if (ipv6.startsWith("::")) {
|
||||
} else if (ipv6.startsWith(":")) {
|
||||
ipv6 = ":" + ipv6
|
||||
}
|
||||
if (ipv6.endsWith("::")) {
|
||||
} else if (ipv6.endsWith(":")) {
|
||||
ipv6 = ipv6 + ":"
|
||||
}
|
||||
if (ipv6 === "") {
|
||||
ipv6 = "::"
|
||||
}
|
||||
|
||||
return ipv6
|
||||
}
|
||||
|
||||
export async function copyToClipboard(text: string) {
|
||||
try {
|
||||
return await navigator.clipboard.writeText(text);
|
||||
} catch (error) {
|
||||
console.error('navigator', error);
|
||||
}
|
||||
try {
|
||||
return copy(text)
|
||||
} catch (error) {
|
||||
console.error('copy', error);
|
||||
}
|
||||
throw new Error('Failed to copy text to clipboard');
|
||||
}
|
||||
try {
|
||||
return await navigator.clipboard.writeText(text)
|
||||
} catch (error) {
|
||||
console.error("navigator", error)
|
||||
}
|
||||
try {
|
||||
return copy(text)
|
||||
} catch (error) {
|
||||
console.error("copy", error)
|
||||
}
|
||||
throw new Error("Failed to copy text to clipboard")
|
||||
}
|
||||
|
||||
@@ -1,164 +1,166 @@
|
||||
{
|
||||
"nezha": "Nezha Monitoring",
|
||||
"theme": {
|
||||
"light": "Light",
|
||||
"dark": "Dark",
|
||||
"system": "Follow System"
|
||||
},
|
||||
"Username": "Username",
|
||||
"Password": "Password",
|
||||
"Results": {
|
||||
"UsernameMin": "Username must be at least {{number}} characters.",
|
||||
"PasswordRequired": "Password cannot be empty.",
|
||||
"ErrorFetchingResource": "Error Fetching Resource : {{error}}",
|
||||
"SelectAtLeastOneServer": "Please select at least one server.",
|
||||
"UnExpectedError": "UnExpected Error, Please see the console for details.",
|
||||
"ForceUpdate": "Forced upgrade:",
|
||||
"NoRowsAreSelected": "No rows are selected",
|
||||
"ThisOperationIsUnrecoverable": "This operation cannot be undone!",
|
||||
"TaskTriggeredSuccessfully": "The task triggered successfully",
|
||||
"TheServerDoesNotOnline": "The server does not exist or has not been connected yet",
|
||||
"InstallHostRequired": "The Agent docking address has not been filled in in the settings.",
|
||||
"UnknownIdentifier": "Unknown identifier"
|
||||
},
|
||||
"Login": "Log in",
|
||||
"Server": "Server",
|
||||
"Service": "Service",
|
||||
"Task": "Task",
|
||||
"Notification": "Notification",
|
||||
"DDNS": "Dynamic DNS",
|
||||
"NATT": "NAT Traversal",
|
||||
"Group": "Group",
|
||||
"Profile": "Profile",
|
||||
"Settings": "System settings",
|
||||
"Logout": "Log out",
|
||||
"NavigateTo": "Navigate to",
|
||||
"SelectAPageToNavigateTo": "Choose a page to jump to",
|
||||
"Close": "Close",
|
||||
"Error": "Error",
|
||||
"Name": "Name",
|
||||
"Version": "Version",
|
||||
"Unknown": "unknown",
|
||||
"Enable": "Enable",
|
||||
"HideForGuest": "Hidden from visitors",
|
||||
"InstallCommands": "Installation command",
|
||||
"Note": "Note",
|
||||
"Success": "Success",
|
||||
"Done": "Finish",
|
||||
"Offline": "Offline",
|
||||
"Failure": "Fail",
|
||||
"Loading": "Loading",
|
||||
"NoResults": "No results",
|
||||
"Actions": "Actions",
|
||||
"EditServer": "Edit server",
|
||||
"Weight": "Weight (the larger the number, the higher it is displayed)",
|
||||
"DDNSProfiles": "DDNS Profile IDs",
|
||||
"SeparateWithComma": "(Separate with comma)",
|
||||
"Public": "Public",
|
||||
"Private": "Private",
|
||||
"Submit": "Submit",
|
||||
"Target": "Target",
|
||||
"Coverage": "Coverage",
|
||||
"CoverAll": "Cover all",
|
||||
"IgnoreAll": "Ignore all",
|
||||
"SpecificServers": "Specific server",
|
||||
"Type": "Type",
|
||||
"Interval": "Interval",
|
||||
"NotifierGroupID": "Notification group ID",
|
||||
"Trigger": "On Trigger",
|
||||
"TasksToTriggerOnAlert": "The task that triggered the alert",
|
||||
"TasksToTriggerAfterRecovery": "Tasks to be triggered after recovery",
|
||||
"Confirm": "Confirm",
|
||||
"ConfirmDeletion": "Confirm deletion?",
|
||||
"Services": "Services",
|
||||
"ShowInService": "Show in Service",
|
||||
"Coverages": {
|
||||
"Excludes": "Excludes specific servers",
|
||||
"Only": "Only specific servers",
|
||||
"Alarmed": "Executed on the server that triggered the alarm"
|
||||
},
|
||||
"EnableFailureNotification": "Enable Failure Notification",
|
||||
"MaximumLatency": "Maximum Latency Time (ms)",
|
||||
"MinimumLatency": "Minimum delay time (milliseconds)",
|
||||
"EnableLatencyNotification": "Enable delayed notifications",
|
||||
"EnableTriggerTask": "Enable Trigger Task",
|
||||
"CronExpression": "Cron expression",
|
||||
"Command": "Order",
|
||||
"NotifierGroup": "Notification group",
|
||||
"SendSuccessNotification": "Send success notification",
|
||||
"LastExecution": "Last Execution",
|
||||
"Result": "Result",
|
||||
"Scheduled": "Scheduled tasks",
|
||||
"Notifier": "Notifier",
|
||||
"AlertRule": "Alert rules",
|
||||
"VerifyTLS": "Verify TLS",
|
||||
"TriggerMode": "Trigger mode",
|
||||
"Rules": "Rules",
|
||||
"RequestMethod": "Request method",
|
||||
"RequestHeader": "Request header",
|
||||
"DoNotSendTestMessage": "Do Not Send Test Message",
|
||||
"Always": "Always",
|
||||
"Once": "Once",
|
||||
"Provider": "Provider",
|
||||
"Domains": "domain name",
|
||||
"MaximumRetryAttempts": "Maximum number of retries",
|
||||
"Refresh": "Refresh",
|
||||
"CopyPath": "Copy path",
|
||||
"Goto": "Go to",
|
||||
"UpdateProfile": "Update profile",
|
||||
"NewUsername": "New username",
|
||||
"OriginalPassword": "Original password",
|
||||
"NewPassword": "New Password",
|
||||
"EditDDNS": "Edit DDNS",
|
||||
"CreateDDNS": "Create DDNS",
|
||||
"Credential": "Credential",
|
||||
"RequestType": "Request type",
|
||||
"RequestBody": "Request body",
|
||||
"FileManager": "Pseudo File Manager",
|
||||
"Downloading": "Downloading",
|
||||
"Uploading": "Uploading",
|
||||
"EditNAT": "Edit intranet penetration",
|
||||
"CreateNAT": "Create intranet penetration",
|
||||
"LocalService": "Local service",
|
||||
"BindHostname": "Bind domain name",
|
||||
"EditServerGroup": "Edit server group",
|
||||
"CreateServerGroup": "Create server group",
|
||||
"User": "User",
|
||||
"WAF": "Web application firewall",
|
||||
"SiteName": "Site name",
|
||||
"DashboardOriginalHost": "Agent docking address [domain name/IP:port]",
|
||||
"ConfigTLS": "Use TLS to connect Agent",
|
||||
"LoginFailed": "Login failed",
|
||||
"BruteForceAttackingToken": "Brute Force Attacking Token",
|
||||
"BruteForceAttackingAgentSecret": "Brute Force Attacking Agent Secret",
|
||||
"Language": "Language",
|
||||
"CustomCodes": "Custom Codes (Style and Script)",
|
||||
"CustomCodesDashboard": "Custom Codes for Dashboard",
|
||||
"CustomPublicDNSNameserversforDDNS": "Custom Public DNS Nameservers for DDNS",
|
||||
"RealIPHeader": "Real IP request header",
|
||||
"UseDirectConnectingIP": "Use direct connection IP",
|
||||
"IPChangeNotification": "IP Change notification",
|
||||
"FullIPNotification": "Show Full IP Address in Notification Messages",
|
||||
"EditService": "Edit service",
|
||||
"CreateService": "Create service",
|
||||
"EditTask": "Edit task",
|
||||
"CreateTask": "Create task",
|
||||
"CreateNotifier": "Create notification",
|
||||
"EditNotifier": "Edit notification",
|
||||
"EditAlertRule": "Edit alarm rules",
|
||||
"CreateAlertRule": "Create alert rules",
|
||||
"EditNotifierGroup": "Edit notification group",
|
||||
"CreateNotifierGroup": "Create notification group",
|
||||
"NewUser": "New user",
|
||||
"Count": "Count",
|
||||
"LastBlockReason": "Last Block Reason",
|
||||
"LastBlockTime": "Last ban time",
|
||||
"Theme": "Theme",
|
||||
"Author": "Author",
|
||||
"Repository": "Repository",
|
||||
"Community": "Community",
|
||||
"Official": "Official",
|
||||
"CommunityThemeWarning": "You are using a community theme",
|
||||
"CommunityThemeDescription": "This theme is provided by the community, use it at your own risk",
|
||||
"Cancel": "Cancel"
|
||||
"nezha": "Nezha Monitoring",
|
||||
"theme": {
|
||||
"light": "Light",
|
||||
"dark": "Dark",
|
||||
"system": "Follow System"
|
||||
},
|
||||
"Username": "Username",
|
||||
"Password": "Password",
|
||||
"LoginFirst": "Please log in first",
|
||||
"CurrentTime": "Current time",
|
||||
"Results": {
|
||||
"UsernameMin": "Username must be at least {{number}} characters.",
|
||||
"PasswordRequired": "Password cannot be empty.",
|
||||
"ErrorFetchingResource": "Error Fetching Resource : {{error}}",
|
||||
"SelectAtLeastOneServer": "Please select at least one server.",
|
||||
"UnExpectedError": "UnExpected Error, Please see the console for details.",
|
||||
"ForceUpdate": "Forced upgrade:",
|
||||
"NoRowsAreSelected": "No rows are selected",
|
||||
"ThisOperationIsUnrecoverable": "This operation cannot be undone!",
|
||||
"TaskTriggeredSuccessfully": "The task triggered successfully",
|
||||
"TheServerDoesNotOnline": "The server does not exist or has not been connected yet",
|
||||
"InstallHostRequired": "The Agent docking address has not been filled in in the settings.",
|
||||
"UnknownIdentifier": "Unknown identifier"
|
||||
},
|
||||
"Login": "Log in",
|
||||
"Server": "Server",
|
||||
"Service": "Service",
|
||||
"Task": "Task",
|
||||
"Notification": "Notification",
|
||||
"DDNS": "Dynamic DNS",
|
||||
"NATT": "NAT Traversal",
|
||||
"Group": "Group",
|
||||
"Profile": "Profile",
|
||||
"Settings": "System settings",
|
||||
"Logout": "Log out",
|
||||
"NavigateTo": "Navigate to",
|
||||
"SelectAPageToNavigateTo": "Choose a page to jump to",
|
||||
"Close": "Close",
|
||||
"Error": "Error",
|
||||
"Name": "Name",
|
||||
"Version": "Version",
|
||||
"Unknown": "unknown",
|
||||
"Enable": "Enable",
|
||||
"HideForGuest": "Hidden from visitors",
|
||||
"InstallCommands": "Installation command",
|
||||
"Note": "Note",
|
||||
"Success": "Success",
|
||||
"Done": "Finish",
|
||||
"Offline": "Offline",
|
||||
"Failure": "Fail",
|
||||
"Loading": "Loading",
|
||||
"NoResults": "No results",
|
||||
"Actions": "Actions",
|
||||
"EditServer": "Edit server",
|
||||
"Weight": "Weight (the larger the number, the higher it is displayed)",
|
||||
"DDNSProfiles": "DDNS Profile IDs",
|
||||
"SeparateWithComma": "(Separate with comma)",
|
||||
"Public": "Public",
|
||||
"Private": "Private",
|
||||
"Submit": "Submit",
|
||||
"Target": "Target",
|
||||
"Coverage": "Coverage",
|
||||
"CoverAll": "Cover all",
|
||||
"IgnoreAll": "Ignore all",
|
||||
"SpecificServers": "Specific server",
|
||||
"Type": "Type",
|
||||
"Interval": "Interval",
|
||||
"NotifierGroupID": "Notification group ID",
|
||||
"Trigger": "On Trigger",
|
||||
"TasksToTriggerOnAlert": "The task that triggered the alert",
|
||||
"TasksToTriggerAfterRecovery": "Tasks to be triggered after recovery",
|
||||
"Confirm": "Confirm",
|
||||
"ConfirmDeletion": "Confirm deletion?",
|
||||
"Services": "Services",
|
||||
"ShowInService": "Show in Service",
|
||||
"Coverages": {
|
||||
"Excludes": "Excludes specific servers",
|
||||
"Only": "Only specific servers",
|
||||
"Alarmed": "Executed on the server that triggered the alarm"
|
||||
},
|
||||
"EnableFailureNotification": "Enable Failure Notification",
|
||||
"MaximumLatency": "Maximum Latency Time (ms)",
|
||||
"MinimumLatency": "Minimum delay time (milliseconds)",
|
||||
"EnableLatencyNotification": "Enable delayed notifications",
|
||||
"EnableTriggerTask": "Enable Trigger Task",
|
||||
"CronExpression": "Cron expression",
|
||||
"Command": "Order",
|
||||
"NotifierGroup": "Notification group",
|
||||
"SendSuccessNotification": "Send success notification",
|
||||
"LastExecution": "Last Execution",
|
||||
"Result": "Result",
|
||||
"Scheduled": "Scheduled tasks",
|
||||
"Notifier": "Notifier",
|
||||
"AlertRule": "Alert rules",
|
||||
"VerifyTLS": "Verify TLS",
|
||||
"TriggerMode": "Trigger mode",
|
||||
"Rules": "Rules",
|
||||
"RequestMethod": "Request method",
|
||||
"RequestHeader": "Request header",
|
||||
"DoNotSendTestMessage": "Do Not Send Test Message",
|
||||
"Always": "Always",
|
||||
"Once": "Once",
|
||||
"Provider": "Provider",
|
||||
"Domains": "domain name",
|
||||
"MaximumRetryAttempts": "Maximum number of retries",
|
||||
"Refresh": "Refresh",
|
||||
"CopyPath": "Copy path",
|
||||
"Goto": "Go to",
|
||||
"UpdateProfile": "Update profile",
|
||||
"NewUsername": "New username",
|
||||
"OriginalPassword": "Original password",
|
||||
"NewPassword": "New Password",
|
||||
"EditDDNS": "Edit DDNS",
|
||||
"CreateDDNS": "Create DDNS",
|
||||
"Credential": "Credential",
|
||||
"RequestType": "Request type",
|
||||
"RequestBody": "Request body",
|
||||
"FileManager": "Pseudo File Manager",
|
||||
"Downloading": "Downloading",
|
||||
"Uploading": "Uploading",
|
||||
"EditNAT": "Edit intranet penetration",
|
||||
"CreateNAT": "Create intranet penetration",
|
||||
"LocalService": "Local service",
|
||||
"BindHostname": "Bind domain name",
|
||||
"EditServerGroup": "Edit server group",
|
||||
"CreateServerGroup": "Create server group",
|
||||
"User": "User",
|
||||
"WAF": "Web application firewall",
|
||||
"SiteName": "Site name",
|
||||
"DashboardOriginalHost": "Agent docking address [domain name/IP:port]",
|
||||
"ConfigTLS": "Use TLS to connect Agent",
|
||||
"LoginFailed": "Login failed",
|
||||
"BruteForceAttackingToken": "Brute Force Attacking Token",
|
||||
"BruteForceAttackingAgentSecret": "Brute Force Attacking Agent Secret",
|
||||
"Language": "Language",
|
||||
"CustomCodes": "Custom Codes (Style and Script)",
|
||||
"CustomCodesDashboard": "Custom Codes for Dashboard",
|
||||
"CustomPublicDNSNameserversforDDNS": "Custom Public DNS Nameservers for DDNS",
|
||||
"RealIPHeader": "Real IP request header",
|
||||
"UseDirectConnectingIP": "Use direct connection IP",
|
||||
"IPChangeNotification": "IP Change notification",
|
||||
"FullIPNotification": "Show Full IP Address in Notification Messages",
|
||||
"EditService": "Edit service",
|
||||
"CreateService": "Create service",
|
||||
"EditTask": "Edit task",
|
||||
"CreateTask": "Create task",
|
||||
"CreateNotifier": "Create notification",
|
||||
"EditNotifier": "Edit notification",
|
||||
"EditAlertRule": "Edit alarm rules",
|
||||
"CreateAlertRule": "Create alert rules",
|
||||
"EditNotifierGroup": "Edit notification group",
|
||||
"CreateNotifierGroup": "Create notification group",
|
||||
"NewUser": "New user",
|
||||
"Count": "Count",
|
||||
"LastBlockReason": "Last Block Reason",
|
||||
"LastBlockTime": "Last ban time",
|
||||
"Theme": "Theme",
|
||||
"Author": "Author",
|
||||
"Repository": "Repository",
|
||||
"Community": "Community",
|
||||
"Official": "Official",
|
||||
"CommunityThemeWarning": "You are using a community theme",
|
||||
"CommunityThemeDescription": "This theme is provided by the community, use it at your own risk",
|
||||
"Cancel": "Cancel"
|
||||
}
|
||||
|
||||
@@ -1,164 +1,166 @@
|
||||
{
|
||||
"nezha": "Monitoraggio Nezha",
|
||||
"theme": {
|
||||
"light": "Chiaro",
|
||||
"dark": "Scuro",
|
||||
"system": "Segui il sistema"
|
||||
},
|
||||
"Username": "Nome utente",
|
||||
"Password": "Password",
|
||||
"Results": {
|
||||
"UsernameMin": "Il nome utente deve contenere almeno {{number}} caratteri.",
|
||||
"PasswordRequired": "La password non può essere vuota.",
|
||||
"ErrorFetchingResource": "Errore nel recupero della risorsa: {{error}}",
|
||||
"SelectAtLeastOneServer": "Seleziona almeno un server.",
|
||||
"UnExpectedError": "Errore imprevisto. Controlla la console per i dettagli.",
|
||||
"ForceUpdate": "Aggiornamento forzato:",
|
||||
"NoRowsAreSelected": "Nessuna riga selezionata",
|
||||
"ThisOperationIsUnrecoverable": "Questa operazione non può essere annullata!",
|
||||
"TaskTriggeredSuccessfully": "Attività avviata correttamente",
|
||||
"TheServerDoesNotOnline": "Il server non esiste o non è stato ancora connesso",
|
||||
"InstallHostRequired": "L'indirizzo di aggancio dell'Agent non è stato inserito nelle impostazioni.",
|
||||
"UnknownIdentifier": "identificatore sconosciuto"
|
||||
},
|
||||
"Login": "Accedi",
|
||||
"Server": "Server",
|
||||
"Service": "Servizio",
|
||||
"Task": "Compito",
|
||||
"Notification": "Notifica",
|
||||
"DDNS": "DNS Dinamico",
|
||||
"NATT": "Traversata NAT",
|
||||
"Group": "Gruppo",
|
||||
"Profile": "Informazioni personali",
|
||||
"Settings": "Impostazioni di sistema",
|
||||
"Logout": "Esci",
|
||||
"NavigateTo": "Vai a",
|
||||
"SelectAPageToNavigateTo": "Scegli una pagina da visitare",
|
||||
"Close": "Chiudi",
|
||||
"Error": "Errore",
|
||||
"Name": "Nome",
|
||||
"Version": "Versione",
|
||||
"Unknown": "Sconosciuto",
|
||||
"Enable": "Abilita",
|
||||
"HideForGuest": "Nascosto ai visitatori",
|
||||
"InstallCommands": "Comando di installazione",
|
||||
"Note": "Osservazione",
|
||||
"Success": "Successo",
|
||||
"Done": "Fine",
|
||||
"Offline": "Non in linea",
|
||||
"Failure": "Fallire",
|
||||
"Loading": "Caricamento",
|
||||
"NoResults": "Nessun contenuto",
|
||||
"Actions": "Azione",
|
||||
"EditServer": "Modifica server",
|
||||
"Weight": "Peso (più grande è il numero, più alto sarà visualizzato)",
|
||||
"DDNSProfiles": "ID profilo DDNS",
|
||||
"SeparateWithComma": "(separati da virgole)",
|
||||
"Public": "Pubblico",
|
||||
"Private": "Privato",
|
||||
"Submit": "Invia",
|
||||
"Target": "Bersaglio",
|
||||
"Coverage": "Copertura",
|
||||
"CoverAll": "Copri tutto",
|
||||
"IgnoreAll": "Ignorare tutto",
|
||||
"SpecificServers": "Server specifico",
|
||||
"Type": "Tipo",
|
||||
"Interval": "Intervallo",
|
||||
"NotifierGroupID": "ID del gruppo di notifiche",
|
||||
"Trigger": "Grilletto",
|
||||
"TasksToTriggerOnAlert": "L'attività che ha attivato l'avviso",
|
||||
"TasksToTriggerAfterRecovery": "Attività da attivare dopo il ripristino",
|
||||
"Confirm": "Confermo",
|
||||
"ConfirmDeletion": "Confermi l'eliminazione?",
|
||||
"Services": "Servizi",
|
||||
"ShowInService": "Mostra in servizio",
|
||||
"Coverages": {
|
||||
"Only": "Solo server specifici",
|
||||
"Excludes": "Escludi server specifici",
|
||||
"Alarmed": "Eseguito sul server che ha attivato l'allarme"
|
||||
},
|
||||
"EnableFailureNotification": "Abilita la notifica di errore",
|
||||
"MaximumLatency": "Tempo di ritardo massimo (millisecondi)",
|
||||
"MinimumLatency": "Tempo di ritardo minimo (millisecondi)",
|
||||
"EnableLatencyNotification": "Abilita le notifiche ritardate",
|
||||
"EnableTriggerTask": "Abilita attività di attivazione",
|
||||
"CronExpression": "Espressione cron",
|
||||
"Command": "Ordine",
|
||||
"NotifierGroup": "Gruppo di notifica",
|
||||
"SendSuccessNotification": "Invia notifica di successo",
|
||||
"LastExecution": "Ultimo giustiziato",
|
||||
"Result": "Risultato",
|
||||
"Scheduled": "Attività pianificate",
|
||||
"Notifier": "Notifica",
|
||||
"AlertRule": "Regole di allerta",
|
||||
"VerifyTLS": "Verifica TLS",
|
||||
"TriggerMode": "Modalità di attivazione",
|
||||
"Rules": "Regola",
|
||||
"RequestMethod": "Metodo di richiesta",
|
||||
"RequestHeader": "Intestazione della richiesta",
|
||||
"DoNotSendTestMessage": "Non inviare messaggi di prova",
|
||||
"Always": "Sempre",
|
||||
"Once": "Solo una volta",
|
||||
"Provider": "Fornitore",
|
||||
"Domains": "Nome di dominio",
|
||||
"MaximumRetryAttempts": "Numero massimo di tentativi",
|
||||
"Refresh": "aggiornare",
|
||||
"CopyPath": "Percorso di copia",
|
||||
"Goto": "Vai a",
|
||||
"UpdateProfile": "Aggiorna il profilo",
|
||||
"NewUsername": "Nuovo nome utente",
|
||||
"OriginalPassword": "Password originale",
|
||||
"NewPassword": "Nuova parola d'ordine",
|
||||
"EditDDNS": "Modifica DDNS",
|
||||
"CreateDDNS": "Crea DDNS",
|
||||
"Credential": "Credenziale",
|
||||
"RequestType": "Tipo di richiesta",
|
||||
"RequestBody": "Richiedi corpo",
|
||||
"FileManager": "Gestore di File Pseudo",
|
||||
"Downloading": "Download in corso",
|
||||
"Uploading": "Caricamento",
|
||||
"EditNAT": "Modifica la penetrazione della intranet",
|
||||
"CreateNAT": "Creare penetrazione intranet",
|
||||
"LocalService": "servizio locale",
|
||||
"BindHostname": "Associa il nome di dominio",
|
||||
"EditServerGroup": "Modifica gruppo di server",
|
||||
"CreateServerGroup": "Crea gruppo di server",
|
||||
"EditService": "Servizi di editing",
|
||||
"CreateService": "Crea servizio",
|
||||
"EditTask": "Modifica attività",
|
||||
"CreateTask": "Crea attività",
|
||||
"CreateNotifier": "Crea notifica",
|
||||
"EditNotifier": "Modifica notifica",
|
||||
"EditAlertRule": "Modifica le regole degli allarmi",
|
||||
"CreateAlertRule": "Crea regole di avviso",
|
||||
"EditNotifierGroup": "Modifica gruppo di notifiche",
|
||||
"CreateNotifierGroup": "Crea gruppo di notifica",
|
||||
"User": "Utente",
|
||||
"WAF": "Firewall dell'applicazione Web",
|
||||
"SiteName": "Nome del sito",
|
||||
"Language": "Lingua",
|
||||
"CustomCodes": "Codice personalizzato (stili e script)",
|
||||
"CustomCodesDashboard": "Codice personalizzato per dashboard",
|
||||
"DashboardOriginalHost": "Indirizzo di ancoraggio dell'agente [nome dominio/IP:porta]",
|
||||
"ConfigTLS": "Usa TLS per connettere Agent",
|
||||
"CustomPublicDNSNameserversforDDNS": "Server dei nomi DNS pubblici personalizzati per DDNS",
|
||||
"RealIPHeader": "Intestazione della richiesta IP reale",
|
||||
"UseDirectConnectingIP": "Utilizzare l'IP di connessione diretta",
|
||||
"IPChangeNotification": "Notifica di modifica IP",
|
||||
"FullIPNotification": "Mostra l'indirizzo IP completo nei messaggi di notifica",
|
||||
"LoginFailed": "Accesso non riuscito",
|
||||
"BruteForceAttackingToken": "Segnalino di attacco di forza bruta",
|
||||
"BruteForceAttackingAgentSecret": "Segreti proxy dell'attacco di forza bruta",
|
||||
"NewUser": "Nuovo utente",
|
||||
"Count": "Contare",
|
||||
"LastBlockReason": "Motivo dell'ultimo divieto",
|
||||
"LastBlockTime": "L'ultima volta che è stato vietato",
|
||||
"Theme": "Tema",
|
||||
"Author": "Autore",
|
||||
"Repository": "Repository",
|
||||
"Community": "Comunità",
|
||||
"Official": "Ufficiale",
|
||||
"CommunityThemeWarning": "Questo tema appartiene alla comunità",
|
||||
"CommunityThemeDescription": "Questo tema viene fornito dalla comunità, utilizzalo a tuo rischio e pericolo",
|
||||
"Cancel": "Annulla"
|
||||
"nezha": "Monitoraggio Nezha",
|
||||
"theme": {
|
||||
"light": "Chiaro",
|
||||
"dark": "Scuro",
|
||||
"system": "Segui il sistema"
|
||||
},
|
||||
"Username": "Nome utente",
|
||||
"Password": "Password",
|
||||
"LoginFirst": "Effettua prima il login",
|
||||
"CurrentTime": "Ora attuale",
|
||||
"Results": {
|
||||
"UsernameMin": "Il nome utente deve contenere almeno {{number}} caratteri.",
|
||||
"PasswordRequired": "La password non può essere vuota.",
|
||||
"ErrorFetchingResource": "Errore nel recupero della risorsa: {{error}}",
|
||||
"SelectAtLeastOneServer": "Seleziona almeno un server.",
|
||||
"UnExpectedError": "Errore imprevisto. Controlla la console per i dettagli.",
|
||||
"ForceUpdate": "Aggiornamento forzato:",
|
||||
"NoRowsAreSelected": "Nessuna riga selezionata",
|
||||
"ThisOperationIsUnrecoverable": "Questa operazione non può essere annullata!",
|
||||
"TaskTriggeredSuccessfully": "Attività avviata correttamente",
|
||||
"TheServerDoesNotOnline": "Il server non esiste o non è stato ancora connesso",
|
||||
"InstallHostRequired": "L'indirizzo di aggancio dell'Agent non è stato inserito nelle impostazioni.",
|
||||
"UnknownIdentifier": "identificatore sconosciuto"
|
||||
},
|
||||
"Login": "Accedi",
|
||||
"Server": "Server",
|
||||
"Service": "Servizio",
|
||||
"Task": "Compito",
|
||||
"Notification": "Notifica",
|
||||
"DDNS": "DNS Dinamico",
|
||||
"NATT": "Traversata NAT",
|
||||
"Group": "Gruppo",
|
||||
"Profile": "Informazioni personali",
|
||||
"Settings": "Impostazioni di sistema",
|
||||
"Logout": "Esci",
|
||||
"NavigateTo": "Vai a",
|
||||
"SelectAPageToNavigateTo": "Scegli una pagina da visitare",
|
||||
"Close": "Chiudi",
|
||||
"Error": "Errore",
|
||||
"Name": "Nome",
|
||||
"Version": "Versione",
|
||||
"Unknown": "Sconosciuto",
|
||||
"Enable": "Abilita",
|
||||
"HideForGuest": "Nascosto ai visitatori",
|
||||
"InstallCommands": "Comando di installazione",
|
||||
"Note": "Osservazione",
|
||||
"Success": "Successo",
|
||||
"Done": "Fine",
|
||||
"Offline": "Non in linea",
|
||||
"Failure": "Fallire",
|
||||
"Loading": "Caricamento",
|
||||
"NoResults": "Nessun contenuto",
|
||||
"Actions": "Azione",
|
||||
"EditServer": "Modifica server",
|
||||
"Weight": "Peso (più grande è il numero, più alto sarà visualizzato)",
|
||||
"DDNSProfiles": "ID profilo DDNS",
|
||||
"SeparateWithComma": "(separati da virgole)",
|
||||
"Public": "Pubblico",
|
||||
"Private": "Privato",
|
||||
"Submit": "Invia",
|
||||
"Target": "Bersaglio",
|
||||
"Coverage": "Copertura",
|
||||
"CoverAll": "Copri tutto",
|
||||
"IgnoreAll": "Ignorare tutto",
|
||||
"SpecificServers": "Server specifico",
|
||||
"Type": "Tipo",
|
||||
"Interval": "Intervallo",
|
||||
"NotifierGroupID": "ID del gruppo di notifiche",
|
||||
"Trigger": "Grilletto",
|
||||
"TasksToTriggerOnAlert": "L'attività che ha attivato l'avviso",
|
||||
"TasksToTriggerAfterRecovery": "Attività da attivare dopo il ripristino",
|
||||
"Confirm": "Confermo",
|
||||
"ConfirmDeletion": "Confermi l'eliminazione?",
|
||||
"Services": "Servizi",
|
||||
"ShowInService": "Mostra in servizio",
|
||||
"Coverages": {
|
||||
"Only": "Solo server specifici",
|
||||
"Excludes": "Escludi server specifici",
|
||||
"Alarmed": "Eseguito sul server che ha attivato l'allarme"
|
||||
},
|
||||
"EnableFailureNotification": "Abilita la notifica di errore",
|
||||
"MaximumLatency": "Tempo di ritardo massimo (millisecondi)",
|
||||
"MinimumLatency": "Tempo di ritardo minimo (millisecondi)",
|
||||
"EnableLatencyNotification": "Abilita le notifiche ritardate",
|
||||
"EnableTriggerTask": "Abilita attività di attivazione",
|
||||
"CronExpression": "Espressione cron",
|
||||
"Command": "Ordine",
|
||||
"NotifierGroup": "Gruppo di notifica",
|
||||
"SendSuccessNotification": "Invia notifica di successo",
|
||||
"LastExecution": "Ultimo giustiziato",
|
||||
"Result": "Risultato",
|
||||
"Scheduled": "Attività pianificate",
|
||||
"Notifier": "Notifica",
|
||||
"AlertRule": "Regole di allerta",
|
||||
"VerifyTLS": "Verifica TLS",
|
||||
"TriggerMode": "Modalità di attivazione",
|
||||
"Rules": "Regola",
|
||||
"RequestMethod": "Metodo di richiesta",
|
||||
"RequestHeader": "Intestazione della richiesta",
|
||||
"DoNotSendTestMessage": "Non inviare messaggi di prova",
|
||||
"Always": "Sempre",
|
||||
"Once": "Solo una volta",
|
||||
"Provider": "Fornitore",
|
||||
"Domains": "Nome di dominio",
|
||||
"MaximumRetryAttempts": "Numero massimo di tentativi",
|
||||
"Refresh": "aggiornare",
|
||||
"CopyPath": "Percorso di copia",
|
||||
"Goto": "Vai a",
|
||||
"UpdateProfile": "Aggiorna il profilo",
|
||||
"NewUsername": "Nuovo nome utente",
|
||||
"OriginalPassword": "Password originale",
|
||||
"NewPassword": "Nuova parola d'ordine",
|
||||
"EditDDNS": "Modifica DDNS",
|
||||
"CreateDDNS": "Crea DDNS",
|
||||
"Credential": "Credenziale",
|
||||
"RequestType": "Tipo di richiesta",
|
||||
"RequestBody": "Richiedi corpo",
|
||||
"FileManager": "Gestore di File Pseudo",
|
||||
"Downloading": "Download in corso",
|
||||
"Uploading": "Caricamento",
|
||||
"EditNAT": "Modifica la penetrazione della intranet",
|
||||
"CreateNAT": "Creare penetrazione intranet",
|
||||
"LocalService": "servizio locale",
|
||||
"BindHostname": "Associa il nome di dominio",
|
||||
"EditServerGroup": "Modifica gruppo di server",
|
||||
"CreateServerGroup": "Crea gruppo di server",
|
||||
"EditService": "Servizi di editing",
|
||||
"CreateService": "Crea servizio",
|
||||
"EditTask": "Modifica attività",
|
||||
"CreateTask": "Crea attività",
|
||||
"CreateNotifier": "Crea notifica",
|
||||
"EditNotifier": "Modifica notifica",
|
||||
"EditAlertRule": "Modifica le regole degli allarmi",
|
||||
"CreateAlertRule": "Crea regole di avviso",
|
||||
"EditNotifierGroup": "Modifica gruppo di notifiche",
|
||||
"CreateNotifierGroup": "Crea gruppo di notifica",
|
||||
"User": "Utente",
|
||||
"WAF": "Firewall dell'applicazione Web",
|
||||
"SiteName": "Nome del sito",
|
||||
"Language": "Lingua",
|
||||
"CustomCodes": "Codice personalizzato (stili e script)",
|
||||
"CustomCodesDashboard": "Codice personalizzato per dashboard",
|
||||
"DashboardOriginalHost": "Indirizzo di ancoraggio dell'agente [nome dominio/IP:porta]",
|
||||
"ConfigTLS": "Usa TLS per connettere Agent",
|
||||
"CustomPublicDNSNameserversforDDNS": "Server dei nomi DNS pubblici personalizzati per DDNS",
|
||||
"RealIPHeader": "Intestazione della richiesta IP reale",
|
||||
"UseDirectConnectingIP": "Utilizzare l'IP di connessione diretta",
|
||||
"IPChangeNotification": "Notifica di modifica IP",
|
||||
"FullIPNotification": "Mostra l'indirizzo IP completo nei messaggi di notifica",
|
||||
"LoginFailed": "Accesso non riuscito",
|
||||
"BruteForceAttackingToken": "Segnalino di attacco di forza bruta",
|
||||
"BruteForceAttackingAgentSecret": "Segreti proxy dell'attacco di forza bruta",
|
||||
"NewUser": "Nuovo utente",
|
||||
"Count": "Contare",
|
||||
"LastBlockReason": "Motivo dell'ultimo divieto",
|
||||
"LastBlockTime": "L'ultima volta che è stato vietato",
|
||||
"Theme": "Tema",
|
||||
"Author": "Autore",
|
||||
"Repository": "Repository",
|
||||
"Community": "Comunità",
|
||||
"Official": "Ufficiale",
|
||||
"CommunityThemeWarning": "Questo tema appartiene alla comunità",
|
||||
"CommunityThemeDescription": "Questo tema viene fornito dalla comunità, utilizzalo a tuo rischio e pericolo",
|
||||
"Cancel": "Annulla"
|
||||
}
|
||||
|
||||
@@ -1,164 +1,166 @@
|
||||
{
|
||||
"nezha": "哪吒监控",
|
||||
"theme": {
|
||||
"light": "亮色",
|
||||
"dark": "暗色",
|
||||
"system": "跟随系统"
|
||||
},
|
||||
"Username": "用户名",
|
||||
"Password": "密码",
|
||||
"Results": {
|
||||
"UsernameMin": "用户名必须至少有 {{number}} 个字符。",
|
||||
"PasswordRequired": "密码不能为空。",
|
||||
"ErrorFetchingResource": "获取资源时出错:{{error}}",
|
||||
"SelectAtLeastOneServer": "请至少选择一台服务器。",
|
||||
"UnExpectedError": "意外错误,请查看控制台了解详细信息。",
|
||||
"ForceUpdate": "强制升级:",
|
||||
"NoRowsAreSelected": "未选择任何行",
|
||||
"ThisOperationIsUnrecoverable": "这个操作将无法恢复!",
|
||||
"TaskTriggeredSuccessfully": "任务触发成功",
|
||||
"TheServerDoesNotOnline": "服务器不存在或者还未连接",
|
||||
"InstallHostRequired": "设置中尚未填写Agent对接地址。",
|
||||
"UnknownIdentifier": "未知标识符"
|
||||
},
|
||||
"Login": "登录",
|
||||
"Server": "服务器",
|
||||
"Service": "服务",
|
||||
"Task": "任务",
|
||||
"Notification": "通知",
|
||||
"DDNS": "动态域名解析",
|
||||
"NATT": "内网穿透",
|
||||
"Group": "分组",
|
||||
"Profile": "个人信息",
|
||||
"Settings": "系统设置",
|
||||
"Logout": "登出",
|
||||
"NavigateTo": "导航至",
|
||||
"SelectAPageToNavigateTo": "选择一个页面跳转",
|
||||
"Close": "关闭",
|
||||
"Error": "错误",
|
||||
"Name": "名称",
|
||||
"Version": "版本",
|
||||
"Unknown": "未知",
|
||||
"Enable": "启用",
|
||||
"HideForGuest": "对游客隐藏",
|
||||
"InstallCommands": "安装命令",
|
||||
"Note": "备注",
|
||||
"Success": "成功",
|
||||
"Done": "完成",
|
||||
"Offline": "离线",
|
||||
"Failure": "失败",
|
||||
"Loading": "加载中",
|
||||
"NoResults": "没有内容",
|
||||
"Actions": "操作",
|
||||
"EditServer": "编辑服务器",
|
||||
"Weight": "权重(数字越大,显示越靠前)",
|
||||
"DDNSProfiles": "DDNS 配置文件 ID",
|
||||
"SeparateWithComma": "(以英文逗号分隔)",
|
||||
"Public": "公开",
|
||||
"Private": "私有",
|
||||
"Submit": "提交",
|
||||
"Target": "目标",
|
||||
"Coverage": "覆盖范围",
|
||||
"CoverAll": "覆盖全部",
|
||||
"IgnoreAll": "忽略全部",
|
||||
"SpecificServers": "特定服务器",
|
||||
"Type": "类型",
|
||||
"Interval": "间隔",
|
||||
"NotifierGroupID": "通知组ID",
|
||||
"Trigger": "触发",
|
||||
"TasksToTriggerOnAlert": "触发警报的任务",
|
||||
"TasksToTriggerAfterRecovery": "恢复后要触发的任务",
|
||||
"Confirm": "确认",
|
||||
"ConfirmDeletion": "确认删除?",
|
||||
"Services": "服务",
|
||||
"ShowInService": "服务中显示",
|
||||
"Coverages": {
|
||||
"Excludes": "排除特定服务器",
|
||||
"Only": "仅特定服务器",
|
||||
"Alarmed": "在触发报警的服务器上执行"
|
||||
},
|
||||
"EnableFailureNotification": "启用失败通知",
|
||||
"MaximumLatency": "最大延迟时间(毫秒)",
|
||||
"MinimumLatency": "最小延迟时间(毫秒)",
|
||||
"EnableLatencyNotification": "启用延迟通知",
|
||||
"EnableTriggerTask": "启用触发任务",
|
||||
"CronExpression": "Cron表达式",
|
||||
"Command": "命令",
|
||||
"NotifierGroup": "通知组",
|
||||
"SendSuccessNotification": "发送成功通知",
|
||||
"LastExecution": "最后执行",
|
||||
"Result": "结果",
|
||||
"Scheduled": "计划任务",
|
||||
"AlertRule": "警报规则",
|
||||
"Notifier": "通知",
|
||||
"VerifyTLS": "验证 TLS",
|
||||
"TriggerMode": "触发模式",
|
||||
"Rules": "规则",
|
||||
"RequestMethod": "请求方式",
|
||||
"RequestHeader": "请求头",
|
||||
"DoNotSendTestMessage": "不发送测试消息",
|
||||
"Always": "总是",
|
||||
"Once": "仅一次",
|
||||
"Provider": "提供商",
|
||||
"Domains": "域名",
|
||||
"MaximumRetryAttempts": "最大重试次数",
|
||||
"Refresh": "刷新",
|
||||
"CopyPath": "复制路径",
|
||||
"Goto": "前往",
|
||||
"UpdateProfile": "更新个人资料",
|
||||
"NewUsername": "新用户名",
|
||||
"OriginalPassword": "原始密码",
|
||||
"NewPassword": "新密码",
|
||||
"EditDDNS": "编辑DDNS",
|
||||
"CreateDDNS": "创建DDNS",
|
||||
"Credential": "凭据",
|
||||
"RequestType": "请求类型",
|
||||
"RequestBody": "请求主体",
|
||||
"FileManager": "文件列表",
|
||||
"Downloading": "下载中",
|
||||
"Uploading": "上传中",
|
||||
"EditNAT": "编辑内网穿透",
|
||||
"CreateNAT": "创建内网穿透",
|
||||
"LocalService": "本地服务",
|
||||
"BindHostname": "绑定域名",
|
||||
"EditServerGroup": "编辑服务器分组",
|
||||
"CreateServerGroup": "创建服务器分组",
|
||||
"EditService": "编辑服务",
|
||||
"CreateService": "创建服务",
|
||||
"EditTask": "编辑任务",
|
||||
"CreateTask": "创建任务",
|
||||
"EditNotifier": "编辑通知",
|
||||
"CreateNotifier": "创建通知",
|
||||
"EditAlertRule": "编辑报警规则",
|
||||
"CreateAlertRule": "创建报警规则",
|
||||
"EditNotifierGroup": "编辑通知分组",
|
||||
"CreateNotifierGroup": "创建通知分组",
|
||||
"User": "用户",
|
||||
"WAF": "Web应用防火墙",
|
||||
"SiteName": "站点名称",
|
||||
"Language": "语言",
|
||||
"CustomCodes": "自定义代码(样式和脚本)",
|
||||
"CustomCodesDashboard": "仪表板的自定义代码",
|
||||
"DashboardOriginalHost": "Agent对接地址【域名/IP:端口】",
|
||||
"ConfigTLS": "Agent 使用 TLS 连接",
|
||||
"CustomPublicDNSNameserversforDDNS": "DDNS 的自定义公共 DNS 名称服务器",
|
||||
"RealIPHeader": "真实IP请求头",
|
||||
"UseDirectConnectingIP": "使用直连 IP",
|
||||
"IPChangeNotification": "IP变更通知",
|
||||
"FullIPNotification": "在通知消息中显示完整的 IP 地址",
|
||||
"LoginFailed": "登录失败",
|
||||
"BruteForceAttackingToken": "暴力攻击令牌",
|
||||
"BruteForceAttackingAgentSecret": "暴力攻击代理秘密",
|
||||
"NewUser": "新用户",
|
||||
"Count": "计数",
|
||||
"LastBlockReason": "最后封禁原因",
|
||||
"LastBlockTime": "最后封禁时间",
|
||||
"Theme": "主题",
|
||||
"Author": "作者",
|
||||
"Repository": "仓库",
|
||||
"Community": "社区",
|
||||
"Official": "官方",
|
||||
"CommunityThemeWarning": "正在使用社区主题",
|
||||
"CommunityThemeDescription": "社区主题未经官方审计,需自行甄别风险",
|
||||
"Cancel": "取消"
|
||||
"nezha": "哪吒监控",
|
||||
"theme": {
|
||||
"light": "亮色",
|
||||
"dark": "暗色",
|
||||
"system": "跟随系统"
|
||||
},
|
||||
"Username": "用户名",
|
||||
"Password": "密码",
|
||||
"LoginFirst": "请先登录",
|
||||
"CurrentTime": "当前时间",
|
||||
"Results": {
|
||||
"UsernameMin": "用户名必须至少有 {{number}} 个字符。",
|
||||
"PasswordRequired": "密码不能为空。",
|
||||
"ErrorFetchingResource": "获取资源时出错:{{error}}",
|
||||
"SelectAtLeastOneServer": "请至少选择一台服务器。",
|
||||
"UnExpectedError": "意外错误,请查看控制台了解详细信息。",
|
||||
"ForceUpdate": "强制升级:",
|
||||
"NoRowsAreSelected": "未选择任何行",
|
||||
"ThisOperationIsUnrecoverable": "这个操作将无法恢复!",
|
||||
"TaskTriggeredSuccessfully": "任务触发成功",
|
||||
"TheServerDoesNotOnline": "服务器不存在或者还未连接",
|
||||
"InstallHostRequired": "设置中尚未填写Agent对接地址。",
|
||||
"UnknownIdentifier": "未知标识符"
|
||||
},
|
||||
"Login": "登录",
|
||||
"Server": "服务器",
|
||||
"Service": "服务",
|
||||
"Task": "任务",
|
||||
"Notification": "通知",
|
||||
"DDNS": "动态域名解析",
|
||||
"NATT": "内网穿透",
|
||||
"Group": "分组",
|
||||
"Profile": "个人信息",
|
||||
"Settings": "系统设置",
|
||||
"Logout": "登出",
|
||||
"NavigateTo": "导航至",
|
||||
"SelectAPageToNavigateTo": "选择一个页面跳转",
|
||||
"Close": "关闭",
|
||||
"Error": "错误",
|
||||
"Name": "名称",
|
||||
"Version": "版本",
|
||||
"Unknown": "未知",
|
||||
"Enable": "启用",
|
||||
"HideForGuest": "对游客隐藏",
|
||||
"InstallCommands": "安装命令",
|
||||
"Note": "备注",
|
||||
"Success": "成功",
|
||||
"Done": "完成",
|
||||
"Offline": "离线",
|
||||
"Failure": "失败",
|
||||
"Loading": "加载中",
|
||||
"NoResults": "没有内容",
|
||||
"Actions": "操作",
|
||||
"EditServer": "编辑服务器",
|
||||
"Weight": "权重(数字越大,显示越靠前)",
|
||||
"DDNSProfiles": "DDNS 配置文件 ID",
|
||||
"SeparateWithComma": "(以英文逗号分隔)",
|
||||
"Public": "公开",
|
||||
"Private": "私有",
|
||||
"Submit": "提交",
|
||||
"Target": "目标",
|
||||
"Coverage": "覆盖范围",
|
||||
"CoverAll": "覆盖全部",
|
||||
"IgnoreAll": "忽略全部",
|
||||
"SpecificServers": "特定服务器",
|
||||
"Type": "类型",
|
||||
"Interval": "间隔",
|
||||
"NotifierGroupID": "通知组ID",
|
||||
"Trigger": "触发",
|
||||
"TasksToTriggerOnAlert": "触发警报的任务",
|
||||
"TasksToTriggerAfterRecovery": "恢复后要触发的任务",
|
||||
"Confirm": "确认",
|
||||
"ConfirmDeletion": "确认删除?",
|
||||
"Services": "服务",
|
||||
"ShowInService": "服务中显示",
|
||||
"Coverages": {
|
||||
"Excludes": "排除特定服务器",
|
||||
"Only": "仅特定服务器",
|
||||
"Alarmed": "在触发报警的服务器上执行"
|
||||
},
|
||||
"EnableFailureNotification": "启用失败通知",
|
||||
"MaximumLatency": "最大延迟时间(毫秒)",
|
||||
"MinimumLatency": "最小延迟时间(毫秒)",
|
||||
"EnableLatencyNotification": "启用延迟通知",
|
||||
"EnableTriggerTask": "启用触发任务",
|
||||
"CronExpression": "Cron表达式",
|
||||
"Command": "命令",
|
||||
"NotifierGroup": "通知组",
|
||||
"SendSuccessNotification": "发送成功通知",
|
||||
"LastExecution": "最后执行",
|
||||
"Result": "结果",
|
||||
"Scheduled": "计划任务",
|
||||
"AlertRule": "警报规则",
|
||||
"Notifier": "通知",
|
||||
"VerifyTLS": "验证 TLS",
|
||||
"TriggerMode": "触发模式",
|
||||
"Rules": "规则",
|
||||
"RequestMethod": "请求方式",
|
||||
"RequestHeader": "请求头",
|
||||
"DoNotSendTestMessage": "不发送测试消息",
|
||||
"Always": "总是",
|
||||
"Once": "仅一次",
|
||||
"Provider": "提供商",
|
||||
"Domains": "域名",
|
||||
"MaximumRetryAttempts": "最大重试次数",
|
||||
"Refresh": "刷新",
|
||||
"CopyPath": "复制路径",
|
||||
"Goto": "前往",
|
||||
"UpdateProfile": "更新个人资料",
|
||||
"NewUsername": "新用户名",
|
||||
"OriginalPassword": "原始密码",
|
||||
"NewPassword": "新密码",
|
||||
"EditDDNS": "编辑DDNS",
|
||||
"CreateDDNS": "创建DDNS",
|
||||
"Credential": "凭据",
|
||||
"RequestType": "请求类型",
|
||||
"RequestBody": "请求主体",
|
||||
"FileManager": "文件列表",
|
||||
"Downloading": "下载中",
|
||||
"Uploading": "上传中",
|
||||
"EditNAT": "编辑内网穿透",
|
||||
"CreateNAT": "创建内网穿透",
|
||||
"LocalService": "本地服务",
|
||||
"BindHostname": "绑定域名",
|
||||
"EditServerGroup": "编辑服务器分组",
|
||||
"CreateServerGroup": "创建服务器分组",
|
||||
"EditService": "编辑服务",
|
||||
"CreateService": "创建服务",
|
||||
"EditTask": "编辑任务",
|
||||
"CreateTask": "创建任务",
|
||||
"EditNotifier": "编辑通知",
|
||||
"CreateNotifier": "创建通知",
|
||||
"EditAlertRule": "编辑报警规则",
|
||||
"CreateAlertRule": "创建报警规则",
|
||||
"EditNotifierGroup": "编辑通知分组",
|
||||
"CreateNotifierGroup": "创建通知分组",
|
||||
"User": "用户",
|
||||
"WAF": "Web应用防火墙",
|
||||
"SiteName": "站点名称",
|
||||
"Language": "语言",
|
||||
"CustomCodes": "自定义代码(样式和脚本)",
|
||||
"CustomCodesDashboard": "仪表板的自定义代码",
|
||||
"DashboardOriginalHost": "Agent对接地址【域名/IP:端口】",
|
||||
"ConfigTLS": "Agent 使用 TLS 连接",
|
||||
"CustomPublicDNSNameserversforDDNS": "DDNS 的自定义公共 DNS 名称服务器",
|
||||
"RealIPHeader": "真实IP请求头",
|
||||
"UseDirectConnectingIP": "使用直连 IP",
|
||||
"IPChangeNotification": "IP变更通知",
|
||||
"FullIPNotification": "在通知消息中显示完整的 IP 地址",
|
||||
"LoginFailed": "登录失败",
|
||||
"BruteForceAttackingToken": "暴力攻击令牌",
|
||||
"BruteForceAttackingAgentSecret": "暴力攻击代理秘密",
|
||||
"NewUser": "新用户",
|
||||
"Count": "计数",
|
||||
"LastBlockReason": "最后封禁原因",
|
||||
"LastBlockTime": "最后封禁时间",
|
||||
"Theme": "主题",
|
||||
"Author": "作者",
|
||||
"Repository": "仓库",
|
||||
"Community": "社区",
|
||||
"Official": "官方",
|
||||
"CommunityThemeWarning": "正在使用社区主题",
|
||||
"CommunityThemeDescription": "社区主题未经官方审计,需自行甄别风险",
|
||||
"Cancel": "取消"
|
||||
}
|
||||
|
||||
@@ -1,164 +1,166 @@
|
||||
{
|
||||
"nezha": "哪吒監控",
|
||||
"theme": {
|
||||
"light": "亮色",
|
||||
"dark": "暗色",
|
||||
"system": "跟隨系統"
|
||||
},
|
||||
"Username": "用戶名",
|
||||
"Password": "密碼",
|
||||
"Results": {
|
||||
"UsernameMin": "使用者名稱必須至少有 {{number}} 個字元。",
|
||||
"PasswordRequired": "密碼不能為空。",
|
||||
"ErrorFetchingResource": "取得資源時發生錯誤:{{error}}",
|
||||
"SelectAtLeastOneServer": "請至少選擇一台伺服器。",
|
||||
"UnExpectedError": "意外錯誤,請查看控制台以了解詳細資訊。",
|
||||
"ForceUpdate": "強制升級:",
|
||||
"NoRowsAreSelected": "未選擇任何行",
|
||||
"ThisOperationIsUnrecoverable": "這個操作將無法恢復!",
|
||||
"TaskTriggeredSuccessfully": "任務觸發成功",
|
||||
"TheServerDoesNotOnline": "伺服器不存在或尚未連接",
|
||||
"InstallHostRequired": "設定中尚未填寫Agent對接位址。",
|
||||
"UnknownIdentifier": "未知標識符"
|
||||
},
|
||||
"Login": "登入",
|
||||
"Server": "伺服器",
|
||||
"Service": "服務",
|
||||
"Task": "任務",
|
||||
"Notification": "通知",
|
||||
"DDNS": "動態網域解析",
|
||||
"NATT": "內網穿透",
|
||||
"Group": "分組",
|
||||
"Profile": "個人資訊",
|
||||
"Settings": "系統設定",
|
||||
"Logout": "登出",
|
||||
"NavigateTo": "導航至",
|
||||
"SelectAPageToNavigateTo": "選擇一個頁面跳轉",
|
||||
"Close": "關閉",
|
||||
"Error": "錯誤",
|
||||
"Name": "名稱",
|
||||
"Version": "版本",
|
||||
"Unknown": "未知",
|
||||
"Enable": "啟用",
|
||||
"HideForGuest": "對遊客隱藏",
|
||||
"InstallCommands": "安裝命令",
|
||||
"Note": "備註",
|
||||
"Success": "成功",
|
||||
"Done": "完成",
|
||||
"Offline": "離線",
|
||||
"Failure": "失敗",
|
||||
"NoResults": "沒有內容",
|
||||
"Loading": "載入中",
|
||||
"Actions": "操作",
|
||||
"EditServer": "編輯伺服器",
|
||||
"Weight": "權重(數字越大,顯示越前)",
|
||||
"DDNSProfiles": "DDNS 設定檔 ID",
|
||||
"SeparateWithComma": "(以英文逗號分隔)",
|
||||
"Public": "公開",
|
||||
"Private": "私人",
|
||||
"Submit": "提交",
|
||||
"Target": "目標",
|
||||
"Coverage": "覆蓋範圍",
|
||||
"CoverAll": "覆蓋全部",
|
||||
"IgnoreAll": "忽略全部",
|
||||
"SpecificServers": "特定伺服器",
|
||||
"Type": "類型",
|
||||
"Interval": "間隔",
|
||||
"NotifierGroupID": "通知群組ID",
|
||||
"Trigger": "觸發",
|
||||
"TasksToTriggerOnAlert": "觸發警報的任務",
|
||||
"TasksToTriggerAfterRecovery": "恢復後要觸發的任務",
|
||||
"Confirm": "確認",
|
||||
"ConfirmDeletion": "確認刪除?",
|
||||
"Services": "服務",
|
||||
"ShowInService": "服務中顯示",
|
||||
"Coverages": {
|
||||
"Only": "僅特定伺服器",
|
||||
"Excludes": "排除特定伺服器",
|
||||
"Alarmed": "在觸發警報的伺服器上執行"
|
||||
},
|
||||
"EnableFailureNotification": "啟用失敗通知",
|
||||
"MaximumLatency": "最大延遲時間(毫秒)",
|
||||
"MinimumLatency": "最小延遲時間(毫秒)",
|
||||
"EnableLatencyNotification": "啟用延遲通知",
|
||||
"EnableTriggerTask": "啟用觸發任務",
|
||||
"CronExpression": "Cron表達式",
|
||||
"Command": "命令",
|
||||
"NotifierGroup": "通知群組",
|
||||
"SendSuccessNotification": "發送成功通知",
|
||||
"LastExecution": "最後執行",
|
||||
"Result": "結果",
|
||||
"Scheduled": "計劃任務",
|
||||
"AlertRule": "警報規則",
|
||||
"Notifier": "通知",
|
||||
"VerifyTLS": "驗證 TLS",
|
||||
"TriggerMode": "觸發模式",
|
||||
"Rules": "規則",
|
||||
"RequestMethod": "請求方式",
|
||||
"RequestHeader": "請求頭",
|
||||
"DoNotSendTestMessage": "不發送測試訊息",
|
||||
"Always": "總是",
|
||||
"Once": "僅一次",
|
||||
"Provider": "提供者",
|
||||
"Domains": "網域",
|
||||
"MaximumRetryAttempts": "最大重試次數",
|
||||
"Refresh": "刷新",
|
||||
"CopyPath": "複製路徑",
|
||||
"Goto": "前往",
|
||||
"UpdateProfile": "更新個人資料",
|
||||
"NewUsername": "新用戶名",
|
||||
"OriginalPassword": "原始密碼",
|
||||
"NewPassword": "新密碼",
|
||||
"EditDDNS": "編輯DDNS",
|
||||
"CreateDDNS": "建立DDNS",
|
||||
"Credential": "憑證",
|
||||
"RequestType": "請求類型",
|
||||
"RequestBody": "請求主體",
|
||||
"FileManager": "檔案列表",
|
||||
"Downloading": "下載中",
|
||||
"Uploading": "上傳中",
|
||||
"EditNAT": "編輯內網穿透",
|
||||
"CreateNAT": "創建內網穿透",
|
||||
"LocalService": "本地服務",
|
||||
"BindHostname": "綁定域名",
|
||||
"EditServerGroup": "編輯伺服器分組",
|
||||
"CreateServerGroup": "建立伺服器分組",
|
||||
"EditService": "編輯服務",
|
||||
"CreateService": "創建服務",
|
||||
"EditTask": "編輯任務",
|
||||
"CreateTask": "創建任務",
|
||||
"CreateNotifier": "建立通知",
|
||||
"EditNotifier": "編輯通知",
|
||||
"EditAlertRule": "編輯警報規則",
|
||||
"CreateAlertRule": "建立警報規則",
|
||||
"EditNotifierGroup": "編輯通知分組",
|
||||
"CreateNotifierGroup": "建立通知分組",
|
||||
"User": "使用者",
|
||||
"WAF": "Web應用防火牆",
|
||||
"SiteName": "網站名稱",
|
||||
"Language": "語言",
|
||||
"CustomCodes": "自訂程式碼(樣式和腳本)",
|
||||
"CustomCodesDashboard": "儀表板的自訂程式碼",
|
||||
"DashboardOriginalHost": "Agent對接位址【網域名稱/IP:連接埠】",
|
||||
"ConfigTLS": "Agent 使用 TLS 連線",
|
||||
"CustomPublicDNSNameserversforDDNS": "DDNS 的自訂公共 DNS 名稱伺服器",
|
||||
"RealIPHeader": "真實IP請求頭",
|
||||
"UseDirectConnectingIP": "使用直連 IP",
|
||||
"IPChangeNotification": "IP變更通知",
|
||||
"FullIPNotification": "在通知訊息中顯示完整的 IP 位址",
|
||||
"LoginFailed": "登入失敗",
|
||||
"BruteForceAttackingToken": "暴力攻擊令牌",
|
||||
"BruteForceAttackingAgentSecret": "暴力攻擊代理秘密",
|
||||
"NewUser": "新用戶",
|
||||
"Count": "計數",
|
||||
"LastBlockReason": "最後封鎖原因",
|
||||
"LastBlockTime": "最後封鎖時間",
|
||||
"Theme": "主題",
|
||||
"Author": "作者",
|
||||
"Repository": "仓库",
|
||||
"Community": "社群",
|
||||
"Official": "官方",
|
||||
"CommunityThemeWarning": "正在使用社區主題",
|
||||
"CommunityThemeDescription": "社群主題未經官方審計,需自行甄別風險",
|
||||
"Cancel": "取消"
|
||||
"nezha": "哪吒監控",
|
||||
"theme": {
|
||||
"light": "亮色",
|
||||
"dark": "暗色",
|
||||
"system": "跟隨系統"
|
||||
},
|
||||
"Username": "用戶名",
|
||||
"Password": "密碼",
|
||||
"LoginFirst": "請先登錄",
|
||||
"CurrentTime": "當前時間",
|
||||
"Results": {
|
||||
"UsernameMin": "使用者名稱必須至少有 {{number}} 個字元。",
|
||||
"PasswordRequired": "密碼不能為空。",
|
||||
"ErrorFetchingResource": "取得資源時發生錯誤:{{error}}",
|
||||
"SelectAtLeastOneServer": "請至少選擇一台伺服器。",
|
||||
"UnExpectedError": "意外錯誤,請查看控制台以了解詳細資訊。",
|
||||
"ForceUpdate": "強制升級:",
|
||||
"NoRowsAreSelected": "未選擇任何行",
|
||||
"ThisOperationIsUnrecoverable": "這個操作將無法恢復!",
|
||||
"TaskTriggeredSuccessfully": "任務觸發成功",
|
||||
"TheServerDoesNotOnline": "伺服器不存在或尚未連接",
|
||||
"InstallHostRequired": "設定中尚未填寫Agent對接位址。",
|
||||
"UnknownIdentifier": "未知標識符"
|
||||
},
|
||||
"Login": "登入",
|
||||
"Server": "伺服器",
|
||||
"Service": "服務",
|
||||
"Task": "任務",
|
||||
"Notification": "通知",
|
||||
"DDNS": "動態網域解析",
|
||||
"NATT": "內網穿透",
|
||||
"Group": "分組",
|
||||
"Profile": "個人資訊",
|
||||
"Settings": "系統設定",
|
||||
"Logout": "登出",
|
||||
"NavigateTo": "導航至",
|
||||
"SelectAPageToNavigateTo": "選擇一個頁面跳轉",
|
||||
"Close": "關閉",
|
||||
"Error": "錯誤",
|
||||
"Name": "名稱",
|
||||
"Version": "版本",
|
||||
"Unknown": "未知",
|
||||
"Enable": "啟用",
|
||||
"HideForGuest": "對遊客隱藏",
|
||||
"InstallCommands": "安裝命令",
|
||||
"Note": "備註",
|
||||
"Success": "成功",
|
||||
"Done": "完成",
|
||||
"Offline": "離線",
|
||||
"Failure": "失敗",
|
||||
"NoResults": "沒有內容",
|
||||
"Loading": "載入中",
|
||||
"Actions": "操作",
|
||||
"EditServer": "編輯伺服器",
|
||||
"Weight": "權重(數字越大,顯示越前)",
|
||||
"DDNSProfiles": "DDNS 設定檔 ID",
|
||||
"SeparateWithComma": "(以英文逗號分隔)",
|
||||
"Public": "公開",
|
||||
"Private": "私人",
|
||||
"Submit": "提交",
|
||||
"Target": "目標",
|
||||
"Coverage": "覆蓋範圍",
|
||||
"CoverAll": "覆蓋全部",
|
||||
"IgnoreAll": "忽略全部",
|
||||
"SpecificServers": "特定伺服器",
|
||||
"Type": "類型",
|
||||
"Interval": "間隔",
|
||||
"NotifierGroupID": "通知群組ID",
|
||||
"Trigger": "觸發",
|
||||
"TasksToTriggerOnAlert": "觸發警報的任務",
|
||||
"TasksToTriggerAfterRecovery": "恢復後要觸發的任務",
|
||||
"Confirm": "確認",
|
||||
"ConfirmDeletion": "確認刪除?",
|
||||
"Services": "服務",
|
||||
"ShowInService": "服務中顯示",
|
||||
"Coverages": {
|
||||
"Only": "僅特定伺服器",
|
||||
"Excludes": "排除特定伺服器",
|
||||
"Alarmed": "在觸發警報的伺服器上執行"
|
||||
},
|
||||
"EnableFailureNotification": "啟用失敗通知",
|
||||
"MaximumLatency": "最大延遲時間(毫秒)",
|
||||
"MinimumLatency": "最小延遲時間(毫秒)",
|
||||
"EnableLatencyNotification": "啟用延遲通知",
|
||||
"EnableTriggerTask": "啟用觸發任務",
|
||||
"CronExpression": "Cron表達式",
|
||||
"Command": "命令",
|
||||
"NotifierGroup": "通知群組",
|
||||
"SendSuccessNotification": "發送成功通知",
|
||||
"LastExecution": "最後執行",
|
||||
"Result": "結果",
|
||||
"Scheduled": "計劃任務",
|
||||
"AlertRule": "警報規則",
|
||||
"Notifier": "通知",
|
||||
"VerifyTLS": "驗證 TLS",
|
||||
"TriggerMode": "觸發模式",
|
||||
"Rules": "規則",
|
||||
"RequestMethod": "請求方式",
|
||||
"RequestHeader": "請求頭",
|
||||
"DoNotSendTestMessage": "不發送測試訊息",
|
||||
"Always": "總是",
|
||||
"Once": "僅一次",
|
||||
"Provider": "提供者",
|
||||
"Domains": "網域",
|
||||
"MaximumRetryAttempts": "最大重試次數",
|
||||
"Refresh": "刷新",
|
||||
"CopyPath": "複製路徑",
|
||||
"Goto": "前往",
|
||||
"UpdateProfile": "更新個人資料",
|
||||
"NewUsername": "新用戶名",
|
||||
"OriginalPassword": "原始密碼",
|
||||
"NewPassword": "新密碼",
|
||||
"EditDDNS": "編輯DDNS",
|
||||
"CreateDDNS": "建立DDNS",
|
||||
"Credential": "憑證",
|
||||
"RequestType": "請求類型",
|
||||
"RequestBody": "請求主體",
|
||||
"FileManager": "檔案列表",
|
||||
"Downloading": "下載中",
|
||||
"Uploading": "上傳中",
|
||||
"EditNAT": "編輯內網穿透",
|
||||
"CreateNAT": "創建內網穿透",
|
||||
"LocalService": "本地服務",
|
||||
"BindHostname": "綁定域名",
|
||||
"EditServerGroup": "編輯伺服器分組",
|
||||
"CreateServerGroup": "建立伺服器分組",
|
||||
"EditService": "編輯服務",
|
||||
"CreateService": "創建服務",
|
||||
"EditTask": "編輯任務",
|
||||
"CreateTask": "創建任務",
|
||||
"CreateNotifier": "建立通知",
|
||||
"EditNotifier": "編輯通知",
|
||||
"EditAlertRule": "編輯警報規則",
|
||||
"CreateAlertRule": "建立警報規則",
|
||||
"EditNotifierGroup": "編輯通知分組",
|
||||
"CreateNotifierGroup": "建立通知分組",
|
||||
"User": "使用者",
|
||||
"WAF": "Web應用防火牆",
|
||||
"SiteName": "網站名稱",
|
||||
"Language": "語言",
|
||||
"CustomCodes": "自訂程式碼(樣式和腳本)",
|
||||
"CustomCodesDashboard": "儀表板的自訂程式碼",
|
||||
"DashboardOriginalHost": "Agent對接位址【網域名稱/IP:連接埠】",
|
||||
"ConfigTLS": "Agent 使用 TLS 連線",
|
||||
"CustomPublicDNSNameserversforDDNS": "DDNS 的自訂公共 DNS 名稱伺服器",
|
||||
"RealIPHeader": "真實IP請求頭",
|
||||
"UseDirectConnectingIP": "使用直連 IP",
|
||||
"IPChangeNotification": "IP變更通知",
|
||||
"FullIPNotification": "在通知訊息中顯示完整的 IP 位址",
|
||||
"LoginFailed": "登入失敗",
|
||||
"BruteForceAttackingToken": "暴力攻擊令牌",
|
||||
"BruteForceAttackingAgentSecret": "暴力攻擊代理秘密",
|
||||
"NewUser": "新用戶",
|
||||
"Count": "計數",
|
||||
"LastBlockReason": "最後封鎖原因",
|
||||
"LastBlockTime": "最後封鎖時間",
|
||||
"Theme": "主題",
|
||||
"Author": "作者",
|
||||
"Repository": "仓库",
|
||||
"Community": "社群",
|
||||
"Official": "官方",
|
||||
"CommunityThemeWarning": "正在使用社區主題",
|
||||
"CommunityThemeDescription": "社群主題未經官方審計,需自行甄別風險",
|
||||
"Cancel": "取消"
|
||||
}
|
||||
|
||||
100
src/main.tsx
100
src/main.tsx
@@ -1,34 +1,30 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import {
|
||||
createBrowserRouter,
|
||||
RouterProvider,
|
||||
} from "react-router-dom";
|
||||
import { StrictMode } from "react"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { RouterProvider, createBrowserRouter } from "react-router-dom"
|
||||
|
||||
import './index.css'
|
||||
import './lib/i18n';
|
||||
|
||||
import Root from "./routes/root";
|
||||
import ErrorPage from "./error-page";
|
||||
import ProtectedRoute from './routes/protect';
|
||||
import LoginPage from './routes/login';
|
||||
import ServerPage from './routes/server';
|
||||
import ServicePage from './routes/service';
|
||||
import { AuthProvider } from './hooks/useAuth';
|
||||
import { TerminalPage } from './components/terminal';
|
||||
import DDNSPage from './routes/ddns';
|
||||
import NATPage from './routes/nat';
|
||||
import ServerGroupPage from './routes/server-group';
|
||||
import NotificationGroupPage from './routes/notification-group';
|
||||
import { ServerProvider } from './hooks/useServer';
|
||||
import { NotificationProvider } from './hooks/useNotfication';
|
||||
import CronPage from './routes/cron';
|
||||
import NotificationPage from './routes/notification';
|
||||
import AlertRulePage from './routes/alert-rule';
|
||||
import SettingsPage from './routes/settings';
|
||||
import UserPage from './routes/user';
|
||||
import WAFPage from './routes/waf';
|
||||
import ProfilePage from './routes/profile';
|
||||
import { TerminalPage } from "./components/terminal"
|
||||
import ErrorPage from "./error-page"
|
||||
import { AuthProvider } from "./hooks/useAuth"
|
||||
import { NotificationProvider } from "./hooks/useNotfication"
|
||||
import { ServerProvider } from "./hooks/useServer"
|
||||
import "./index.css"
|
||||
import "./lib/i18n"
|
||||
import AlertRulePage from "./routes/alert-rule"
|
||||
import CronPage from "./routes/cron"
|
||||
import DDNSPage from "./routes/ddns"
|
||||
import LoginPage from "./routes/login"
|
||||
import NATPage from "./routes/nat"
|
||||
import NotificationPage from "./routes/notification"
|
||||
import NotificationGroupPage from "./routes/notification-group"
|
||||
import ProfilePage from "./routes/profile"
|
||||
import ProtectedRoute from "./routes/protect"
|
||||
import Root from "./routes/root"
|
||||
import ServerPage from "./routes/server"
|
||||
import ServerGroupPage from "./routes/server-group"
|
||||
import ServicePage from "./routes/service"
|
||||
import SettingsPage from "./routes/settings"
|
||||
import UserPage from "./routes/user"
|
||||
import WAFPage from "./routes/waf"
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
@@ -48,7 +44,11 @@ const router = createBrowserRouter([
|
||||
},
|
||||
{
|
||||
path: "/dashboard",
|
||||
element: <ServerProvider withServerGroup><ServerPage /></ServerProvider>,
|
||||
element: (
|
||||
<ServerProvider withServerGroup>
|
||||
<ServerPage />
|
||||
</ServerProvider>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/dashboard/service",
|
||||
@@ -72,11 +72,19 @@ const router = createBrowserRouter([
|
||||
},
|
||||
{
|
||||
path: "/dashboard/notification",
|
||||
element: <NotificationProvider withNotifierGroup><NotificationPage /></NotificationProvider>,
|
||||
element: (
|
||||
<NotificationProvider withNotifierGroup>
|
||||
<NotificationPage />
|
||||
</NotificationProvider>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/dashboard/alert-rule",
|
||||
element: <NotificationProvider withNotifierGroup><AlertRulePage /></NotificationProvider>,
|
||||
element: (
|
||||
<NotificationProvider withNotifierGroup>
|
||||
<AlertRulePage />
|
||||
</NotificationProvider>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/dashboard/ddns",
|
||||
@@ -88,11 +96,19 @@ const router = createBrowserRouter([
|
||||
},
|
||||
{
|
||||
path: "/dashboard/server-group",
|
||||
element: <ServerProvider withServer><ServerGroupPage /></ServerProvider>,
|
||||
element: (
|
||||
<ServerProvider withServer>
|
||||
<ServerGroupPage />
|
||||
</ServerProvider>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/dashboard/notification-group",
|
||||
element: <NotificationProvider withNotifier><NotificationGroupPage /></NotificationProvider>,
|
||||
element: (
|
||||
<NotificationProvider withNotifier>
|
||||
<NotificationGroupPage />
|
||||
</NotificationProvider>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/dashboard/terminal/:id",
|
||||
@@ -100,7 +116,11 @@ const router = createBrowserRouter([
|
||||
},
|
||||
{
|
||||
path: "/dashboard/profile",
|
||||
element: <ServerProvider withServer withServerGroup><ProfilePage /></ServerProvider>,
|
||||
element: (
|
||||
<ServerProvider withServer withServerGroup>
|
||||
<ProfilePage />
|
||||
</ServerProvider>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: "/dashboard/settings",
|
||||
@@ -114,10 +134,8 @@ const router = createBrowserRouter([
|
||||
path: "/dashboard/settings/waf",
|
||||
element: <WAFPage />,
|
||||
},
|
||||
]
|
||||
],
|
||||
},
|
||||
]);
|
||||
])
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<RouterProvider router={router} />
|
||||
)
|
||||
createRoot(document.getElementById("root")!).render(<RouterProvider router={router} />)
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { deleteAlertRules } from "@/api/alert-rule"
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { AlertRuleCard } from "@/components/alert-rule"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { NotificationTab } from "@/components/notification-tab"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -7,35 +12,29 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { toast } from "sonner";
|
||||
import { ModelAlertRule, triggerModes } from "@/types";
|
||||
import { deleteAlertRules } from "@/api/alert-rule";
|
||||
import { NotificationTab } from "@/components/notification-tab";
|
||||
import { AlertRuleCard } from "@/components/alert-rule";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
} from "@/components/ui/table"
|
||||
import { ModelAlertRule, triggerModes } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function AlertRulePage() {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelAlertRule[]>(
|
||||
"/api/v1/alert-rule",
|
||||
swrFetcher
|
||||
);
|
||||
swrFetcher,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<ModelAlertRule>[] = [
|
||||
{
|
||||
@@ -70,8 +69,8 @@ export default function AlertRulePage() {
|
||||
accessorKey: "name",
|
||||
accessorFn: (row) => row.name,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -87,8 +86,12 @@ export default function AlertRulePage() {
|
||||
{
|
||||
header: t("Rules"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-48 whitespace-normal break-words">{JSON.stringify(s.rules)}</div>;
|
||||
const s = row.original
|
||||
return (
|
||||
<div className="max-w-48 whitespace-normal break-words">
|
||||
{JSON.stringify(s.rules)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -110,7 +113,7 @@ export default function AlertRulePage() {
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
@@ -122,25 +125,25 @@ export default function AlertRulePage() {
|
||||
>
|
||||
<AlertRuleCard mutate={mutate} data={s} />
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<NotificationTab className="flex-1 mr-4 sm:max-w-[40%]" />
|
||||
<HeaderButtonGroup
|
||||
@@ -164,9 +167,12 @@ export default function AlertRulePage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -198,5 +204,5 @@ export default function AlertRulePage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { deleteCron, runCron } from "@/api/cron"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { CronCard } from "@/components/cron"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -7,32 +11,29 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ModelCron } from "@/types";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { toast } from "sonner";
|
||||
import { deleteCron, runCron } from "@/api/cron";
|
||||
import { CronCard } from "@/components/cron";
|
||||
import { cronTypes } from "@/types";
|
||||
import { IconButton } from "@/components/xui/icon-button";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
} from "@/components/ui/table"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { ModelCron } from "@/types"
|
||||
import { cronTypes } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function CronPage() {
|
||||
const { t } = useTranslation();
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelCron[]>("/api/v1/cron", swrFetcher);
|
||||
const { t } = useTranslation()
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelCron[]>("/api/v1/cron", swrFetcher)
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
description: t("Results.ErrorFetchingResource", {
|
||||
error: error.message,
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<ModelCron>[] = [
|
||||
{
|
||||
@@ -41,7 +42,7 @@ export default function CronPage() {
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label="Select all"
|
||||
@@ -66,8 +67,8 @@ export default function CronPage() {
|
||||
header: t("Name"),
|
||||
accessorKey: "name",
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -84,8 +85,8 @@ export default function CronPage() {
|
||||
header: t("Command"),
|
||||
accessorKey: "command",
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-48 whitespace-normal break-words">{s.command}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-48 whitespace-normal break-words">{s.command}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -103,24 +104,24 @@ export default function CronPage() {
|
||||
accessorKey: "cover",
|
||||
accessorFn: (row) => row.cover,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<div className="max-w-48 whitespace-normal break-words">
|
||||
{(() => {
|
||||
switch (s.cover) {
|
||||
case 0: {
|
||||
return <span>Ignore All</span>;
|
||||
}
|
||||
case 1: {
|
||||
return <span>Cover All</span>;
|
||||
}
|
||||
case 2: {
|
||||
return <span>On alert</span>;
|
||||
}
|
||||
case 0: {
|
||||
return <span>Ignore All</span>
|
||||
}
|
||||
case 1: {
|
||||
return <span>Cover All</span>
|
||||
}
|
||||
case 2: {
|
||||
return <span>On alert</span>
|
||||
}
|
||||
}
|
||||
})()}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -133,8 +134,12 @@ export default function CronPage() {
|
||||
accessorKey: "lastExecution",
|
||||
accessorFn: (row) => row.last_executed_at,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-24 whitespace-normal break-words">{s.last_executed_at}</div>;
|
||||
const s = row.original
|
||||
return (
|
||||
<div className="max-w-24 whitespace-normal break-words">
|
||||
{s.last_executed_at}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -146,7 +151,7 @@ export default function CronPage() {
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
@@ -158,43 +163,43 @@ export default function CronPage() {
|
||||
icon="play"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await runCron(s.id);
|
||||
await runCron(s.id)
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
console.error(e)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.UnExpectedError"),
|
||||
});
|
||||
await mutate();
|
||||
return;
|
||||
})
|
||||
await mutate()
|
||||
return
|
||||
}
|
||||
toast(t("Success"), {
|
||||
description: t("Results.TaskTriggeredSuccessfully"),
|
||||
});
|
||||
await mutate();
|
||||
})
|
||||
await mutate()
|
||||
}}
|
||||
/>
|
||||
<CronCard mutate={mutate} data={s} />
|
||||
</>
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<h1 className="flex-1 text-3xl font-bold tracking-tight">{t("Task")}</h1>
|
||||
<HeaderButtonGroup
|
||||
@@ -218,9 +223,12 @@ export default function CronPage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -252,5 +260,5 @@ export default function CronPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { DDNSCard } from "@/components/ddns";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { deleteDDNSProfiles, getDDNSProviders } from "@/api/ddns"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { DDNSCard } from "@/components/ddns"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -8,38 +11,39 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ModelDDNSProfile } from "@/types";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useState, useMemo } from "react";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { toast } from "sonner";
|
||||
import { deleteDDNSProfiles, getDDNSProviders } from "@/api/ddns";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
} from "@/components/ui/table"
|
||||
import { ModelDDNSProfile } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function DDNSPage() {
|
||||
const { t } = useTranslation();
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelDDNSProfile[]>("/api/v1/ddns", swrFetcher);
|
||||
const [providers, setProviders] = useState<string[]>([]);
|
||||
const { t } = useTranslation()
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelDDNSProfile[]>(
|
||||
"/api/v1/ddns",
|
||||
swrFetcher,
|
||||
)
|
||||
const [providers, setProviders] = useState<string[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProviders = async () => {
|
||||
const fetchedProviders = await getDDNSProviders();
|
||||
setProviders(fetchedProviders);
|
||||
};
|
||||
fetchProviders();
|
||||
}, []);
|
||||
const fetchedProviders = await getDDNSProviders()
|
||||
setProviders(fetchedProviders)
|
||||
}
|
||||
fetchProviders()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
description: t("Results.ErrorFetchingResource", {
|
||||
error: error.message,
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<ModelDDNSProfile>[] = [
|
||||
{
|
||||
@@ -48,7 +52,7 @@ export default function DDNSPage() {
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label="Select all"
|
||||
@@ -74,8 +78,8 @@ export default function DDNSPage() {
|
||||
accessorKey: "name",
|
||||
accessorFn: (row) => row.name,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-24 whitespace-normal break-words">{s.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-24 whitespace-normal break-words">{s.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -94,12 +98,12 @@ export default function DDNSPage() {
|
||||
accessorFn: (row) => row.provider,
|
||||
},
|
||||
{
|
||||
header: t('Domains'),
|
||||
header: t("Domains"),
|
||||
accessorKey: "domains",
|
||||
accessorFn: (row) => row.domains,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-24 whitespace-normal break-words">{s.domains}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-24 whitespace-normal break-words">{s.domains}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -111,33 +115,37 @@ export default function DDNSPage() {
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
delete={{ fn: deleteDDNSProfiles, id: s.id, mutate: mutate }}
|
||||
delete={{
|
||||
fn: deleteDDNSProfiles,
|
||||
id: s.id,
|
||||
mutate: mutate,
|
||||
}}
|
||||
>
|
||||
<DDNSCard mutate={mutate} data={s} providers={providers} />
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<h1 className="flex-1 text-3xl font-bold tracking-tight">{t("DDNS")}</h1>
|
||||
<HeaderButtonGroup
|
||||
@@ -161,9 +169,12 @@ export default function DDNSPage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -195,5 +206,5 @@ export default function DDNSPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Form,
|
||||
@@ -13,9 +9,11 @@ import {
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import i18next from "i18next"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import i18next from "i18next";
|
||||
import { z } from "zod"
|
||||
|
||||
const formSchema = z.object({
|
||||
username: z.string().min(2, {
|
||||
@@ -23,10 +21,9 @@ const formSchema = z.object({
|
||||
}),
|
||||
password: z.string().min(1, {
|
||||
message: i18next.t("Results.PasswordRequired"),
|
||||
})
|
||||
}),
|
||||
})
|
||||
|
||||
|
||||
function Login() {
|
||||
const { login } = useAuth()
|
||||
|
||||
@@ -42,10 +39,10 @@ function Login() {
|
||||
login(values.username, values.password)
|
||||
}
|
||||
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<div className="my-8 max-w-xl m-auto">
|
||||
<div className="mt-28 max-w-sm m-auto">
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
||||
<FormField
|
||||
@@ -68,7 +65,12 @@ function Login() {
|
||||
<FormItem>
|
||||
<FormLabel>{t("Password")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="password" placeholder="admin" autoComplete="current-password" {...field} />
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="admin"
|
||||
autoComplete="current-password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -81,4 +83,4 @@ function Login() {
|
||||
)
|
||||
}
|
||||
|
||||
export default Login;
|
||||
export default Login
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { NATCard } from "@/components/nat";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { deleteNAT } from "@/api/nat"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { NATCard } from "@/components/nat"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -8,29 +11,27 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ModelNAT } from "@/types";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { toast } from "sonner";
|
||||
import { deleteNAT } from "@/api/nat";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
} from "@/components/ui/table"
|
||||
import { ModelNAT } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function NATPage() {
|
||||
const { t } = useTranslation();
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelNAT[]>("/api/v1/nat", swrFetcher);
|
||||
const { t } = useTranslation()
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelNAT[]>("/api/v1/nat", swrFetcher)
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
description: t("Results.ErrorFetchingResource", {
|
||||
error: error.message,
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<ModelNAT>[] = [
|
||||
{
|
||||
@@ -39,7 +40,7 @@ export default function NATPage() {
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label="Select all"
|
||||
@@ -65,12 +66,12 @@ export default function NATPage() {
|
||||
accessorKey: "name",
|
||||
accessorFn: (row) => row.name,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
header: t("Server")+" ID",
|
||||
header: t("Server") + " ID",
|
||||
accessorKey: "serverID",
|
||||
accessorFn: (row) => row.server_id,
|
||||
},
|
||||
@@ -79,8 +80,8 @@ export default function NATPage() {
|
||||
accessorKey: "host",
|
||||
accessorFn: (row) => row.host,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.host}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.host}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -88,15 +89,15 @@ export default function NATPage() {
|
||||
accessorKey: "domain",
|
||||
accessorFn: (row) => row.domain,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.domain}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.domain}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
@@ -104,25 +105,25 @@ export default function NATPage() {
|
||||
>
|
||||
<NATCard mutate={mutate} data={s} />
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<h1 className="flex-1 text-3xl font-bold tracking-tight"> {t("NATT")}</h1>
|
||||
<HeaderButtonGroup
|
||||
@@ -146,9 +147,12 @@ export default function NATPage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -180,5 +184,5 @@ export default function NATPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { deleteNotificationGroups } from "@/api/notification-group"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { GroupTab } from "@/components/group-tab"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { NotificationGroupCard } from "@/components/notification-group"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -7,34 +12,30 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { toast } from "sonner";
|
||||
import { ModelNotificationGroupResponseItem } from "@/types";
|
||||
import { deleteNotificationGroups } from "@/api/notification-group";
|
||||
import { GroupTab } from "@/components/group-tab";
|
||||
import { NotificationGroupCard } from "@/components/notification-group";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
} from "@/components/ui/table"
|
||||
import { ModelNotificationGroupResponseItem } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function NotificationGroupPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelNotificationGroupResponseItem[]>(
|
||||
"/api/v1/notification-group",
|
||||
swrFetcher
|
||||
);
|
||||
swrFetcher,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
description: t("Results.ErrorFetchingResource", {
|
||||
error: error.message,
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<ModelNotificationGroupResponseItem>[] = [
|
||||
{
|
||||
@@ -43,7 +44,7 @@ export default function NotificationGroupPage() {
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label="Select all"
|
||||
@@ -69,12 +70,12 @@ export default function NotificationGroupPage() {
|
||||
accessorKey: "name",
|
||||
accessorFn: (row) => row.group.name,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-48 whitespace-normal break-words">{s.group.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-48 whitespace-normal break-words">{s.group.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
header: t("Notifier")+"(ID)",
|
||||
header: t("Notifier") + "(ID)",
|
||||
accessorKey: "notifications",
|
||||
accessorFn: (row) => row.notifications,
|
||||
},
|
||||
@@ -82,7 +83,7 @@ export default function NotificationGroupPage() {
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
@@ -94,25 +95,25 @@ export default function NotificationGroupPage() {
|
||||
>
|
||||
<NotificationGroupCard mutate={mutate} data={s} />
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<GroupTab className="flex-1 mr-4 sm:max-w-[40%]" />
|
||||
<HeaderButtonGroup
|
||||
@@ -136,9 +137,12 @@ export default function NotificationGroupPage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -170,5 +174,5 @@ export default function NotificationGroupPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { deleteNotification } from "@/api/notification"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { NotificationTab } from "@/components/notification-tab"
|
||||
import { NotifierCard } from "@/components/notifier"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -7,37 +12,32 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { toast } from "sonner";
|
||||
import { ModelNotification } from "@/types";
|
||||
import { deleteNotification } from "@/api/notification";
|
||||
import { NotificationTab } from "@/components/notification-tab";
|
||||
import { NotifierCard } from "@/components/notifier";
|
||||
import { useNotification } from "@/hooks/useNotfication";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
} from "@/components/ui/table"
|
||||
import { useNotification } from "@/hooks/useNotfication"
|
||||
import { ModelNotification } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function NotificationPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelNotification[]>(
|
||||
"/api/v1/notification",
|
||||
swrFetcher
|
||||
);
|
||||
const { notifierGroup } = useNotification();
|
||||
swrFetcher,
|
||||
)
|
||||
const { notifierGroup } = useNotification()
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
description: t("Results.ErrorFetchingResource", {
|
||||
error: error.message,
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<ModelNotification>[] = [
|
||||
{
|
||||
@@ -46,7 +46,7 @@ export default function NotificationPage() {
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label="Select all"
|
||||
@@ -72,8 +72,8 @@ export default function NotificationPage() {
|
||||
accessorKey: "name",
|
||||
accessorFn: (row) => row.name,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-32 whitespace-normal break-words">{s.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -84,7 +84,7 @@ export default function NotificationPage() {
|
||||
notifierGroup
|
||||
?.filter((ng) => ng.notifications?.includes(row.id))
|
||||
.map((ng) => ng.group.id) || []
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -92,8 +92,8 @@ export default function NotificationPage() {
|
||||
accessorKey: "url",
|
||||
accessorFn: (row) => row.url,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-64 whitespace-normal break-words">{s.url}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-64 whitespace-normal break-words">{s.url}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -105,7 +105,7 @@ export default function NotificationPage() {
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
@@ -117,25 +117,25 @@ export default function NotificationPage() {
|
||||
>
|
||||
<NotifierCard mutate={mutate} data={s} />
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<NotificationTab className="flex-1 mr-4 sm:max-w-[40%]" />
|
||||
<HeaderButtonGroup
|
||||
@@ -159,9 +159,12 @@ export default function NotificationPage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -193,5 +196,5 @@ export default function NotificationPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,40 +1,45 @@
|
||||
import { ProfileCard } from "@/components/profile"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { useMainStore } from "@/hooks/useMainStore"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card"
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery";
|
||||
import { Server, Boxes } from "lucide-react";
|
||||
import { useServer } from "@/hooks/useServer";
|
||||
import { ProfileCard } from "@/components/profile";
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery"
|
||||
import { useServer } from "@/hooks/useServer"
|
||||
import { Boxes, Server } from "lucide-react"
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { profile } = useMainStore();
|
||||
const { servers, serverGroups } = useServer();
|
||||
const { profile } = useMainStore()
|
||||
const { servers, serverGroups } = useServer()
|
||||
const isDesktop = useMediaQuery("(min-width: 890px)")
|
||||
|
||||
return (
|
||||
profile && (
|
||||
<div className={`flex p-8 gap-4 ${isDesktop ? 'ml-6' : 'flex-col'}`}>
|
||||
<div className={`flex ${isDesktop ? 'flex-col mr-6' : 'gap-4 w-full items-center'}`}>
|
||||
<Avatar className={`${isDesktop ? 'h-[300px] w-[300px]' : 'h-[150px] w-[150px]'} border-foreground border-[1px]`}>
|
||||
<AvatarImage src={'https://api.dicebear.com/7.x/notionists/svg?seed=' + profile.username} alt={profile.username} />
|
||||
<div className={`flex p-8 gap-4 ${isDesktop ? "ml-6" : "flex-col"}`}>
|
||||
<div
|
||||
className={`flex ${isDesktop ? "flex-col mr-6" : "gap-4 w-full items-center"}`}
|
||||
>
|
||||
<Avatar
|
||||
className={`${isDesktop ? "h-[300px] w-[300px]" : "h-[150px] w-[150px]"} border-foreground border-[1px]`}
|
||||
>
|
||||
<AvatarImage
|
||||
src={
|
||||
"https://api.dicebear.com/7.x/notionists/svg?seed=" +
|
||||
profile.username
|
||||
}
|
||||
alt={profile.username}
|
||||
/>
|
||||
<AvatarFallback>{profile.username}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="justify-center text-3xl font-semibold">{profile.username}</p>
|
||||
<p className="text-gray-400">IP: {profile.login_ip || 'Unknown'}</p>
|
||||
<p className="text-gray-400">IP: {profile.login_ip || "Unknown"}</p>
|
||||
</div>
|
||||
{isDesktop &&
|
||||
{isDesktop && (
|
||||
<ProfileCard className="flex mt-4 justify-center items-center max-w-[300px] rounded-lg" />
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
{!isDesktop &&
|
||||
{!isDesktop && (
|
||||
<ProfileCard className="flex justify-center items-center max-w-full rounded-lg" />
|
||||
}
|
||||
)}
|
||||
<div className="w-full">
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card className="w-full">
|
||||
@@ -61,5 +66,5 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import { Navigate } from "react-router-dom";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { Navigate } from "react-router-dom"
|
||||
|
||||
export const ProtectedRoute = ({ children }: {
|
||||
children: React.ReactNode;
|
||||
}) => {
|
||||
const { profile } = useAuth();
|
||||
export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
|
||||
const { profile } = useAuth()
|
||||
|
||||
if (!profile && window.location.pathname !== "/dashboard/login") {
|
||||
return <><Navigate to="/dashboard/login" />{children}</>;
|
||||
return (
|
||||
<>
|
||||
<Navigate to="/dashboard/login" />
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
return children
|
||||
}
|
||||
|
||||
export default ProtectedRoute;
|
||||
export default ProtectedRoute
|
||||
|
||||
@@ -1,34 +1,33 @@
|
||||
import { Outlet } from "react-router-dom";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import Header from "@/components/header";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useSetting from "@/hooks/useSetting";
|
||||
import Header from "@/components/header"
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import useSetting from "@/hooks/useSetting"
|
||||
import { useEffect } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { Outlet } from "react-router-dom"
|
||||
|
||||
export default function Root() {
|
||||
const { t } = useTranslation();
|
||||
const settings = useSetting();
|
||||
const { t } = useTranslation()
|
||||
const settings = useSetting()
|
||||
|
||||
useEffect(() => {
|
||||
document.title = settings?.site_name || "哪吒监控 Nezha Monitoring";
|
||||
}, [settings]);
|
||||
document.title = settings?.site_name || "哪吒监控 Nezha Monitoring"
|
||||
}, [settings])
|
||||
|
||||
return (
|
||||
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
|
||||
<Card className="text-sm max-w-7xl mx-auto mt-5 min-h-[90%] flex flex-col justify-between">
|
||||
<section className="text-sm mx-auto h-full flex flex-col justify-between">
|
||||
<div>
|
||||
<Header />
|
||||
<Outlet />
|
||||
<div className="max-w-5xl mx-auto">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
<footer className="mx-5 pb-5 text-foreground/60 font-thin text-center">
|
||||
© 2019-2024 {t('nezha')} {settings?.version}
|
||||
<footer className="mx-5 pb-5 text-foreground/50 font-light text-xs text-center">
|
||||
© 2019-2024 {t("nezha")} {settings?.version}
|
||||
</footer>
|
||||
</Card>
|
||||
</section>
|
||||
<Toaster />
|
||||
</ThemeProvider>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { deleteServerGroups } from "@/api/server-group"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { GroupTab } from "@/components/group-tab"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { ServerGroupCard } from "@/components/server-group"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -7,34 +12,30 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { toast } from "sonner";
|
||||
import { ModelServerGroupResponseItem } from "@/types";
|
||||
import { deleteServerGroups } from "@/api/server-group";
|
||||
import { GroupTab } from "@/components/group-tab";
|
||||
import { ServerGroupCard } from "@/components/server-group";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
} from "@/components/ui/table"
|
||||
import { ModelServerGroupResponseItem } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function ServerGroupPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t } = useTranslation()
|
||||
const { data, mutate, error, isLoading } = useSWR<ModelServerGroupResponseItem[]>(
|
||||
"/api/v1/server-group",
|
||||
swrFetcher
|
||||
);
|
||||
swrFetcher,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
description: t("Results.ErrorFetchingResource", {
|
||||
error: error.message,
|
||||
}),
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<ModelServerGroupResponseItem>[] = [
|
||||
{
|
||||
@@ -43,7 +44,7 @@ export default function ServerGroupPage() {
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
(table.getIsSomePageRowsSelected() && "indeterminate")
|
||||
}
|
||||
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label="Select all"
|
||||
@@ -69,12 +70,12 @@ export default function ServerGroupPage() {
|
||||
accessorKey: "name",
|
||||
accessorFn: (row) => row.group.name,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-48 whitespace-normal break-words">{s.group.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-48 whitespace-normal break-words">{s.group.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
header: t("Server")+"(ID)",
|
||||
header: t("Server") + "(ID)",
|
||||
accessorKey: "servers",
|
||||
accessorFn: (row) => row.servers,
|
||||
},
|
||||
@@ -82,7 +83,7 @@ export default function ServerGroupPage() {
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
@@ -94,25 +95,25 @@ export default function ServerGroupPage() {
|
||||
>
|
||||
<ServerGroupCard mutate={mutate} data={s} />
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<GroupTab className="flex-1 mr-4 sm:max-w-[40%]" />
|
||||
<HeaderButtonGroup
|
||||
@@ -135,9 +136,12 @@ export default function ServerGroupPage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -169,5 +173,5 @@ export default function ServerGroupPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { swrFetcher } from "@/api/api";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { deleteServer, forceUpdateServer } from "@/api/server"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { InstallCommandsMenu } from "@/components/install-commands"
|
||||
import { NoteMenu } from "@/components/note-menu"
|
||||
import { ServerCard } from "@/components/server"
|
||||
import { TerminalButton } from "@/components/terminal"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -7,37 +14,29 @@ import {
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ModelServer as Server, ModelForceUpdateResponse } from "@/types";
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
|
||||
import useSWR from "swr";
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group";
|
||||
import { deleteServer, forceUpdateServer } from "@/api/server";
|
||||
import { ServerCard } from "@/components/server";
|
||||
import { ActionButtonGroup } from "@/components/action-button-group";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { IconButton } from "@/components/xui/icon-button";
|
||||
import { InstallCommandsMenu } from "@/components/install-commands";
|
||||
import { NoteMenu } from "@/components/note-menu";
|
||||
import { TerminalButton } from "@/components/terminal";
|
||||
import { useServer } from "@/hooks/useServer";
|
||||
import { joinIP } from "@/lib/utils";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
} from "@/components/ui/table"
|
||||
import { IconButton } from "@/components/xui/icon-button"
|
||||
import { useServer } from "@/hooks/useServer"
|
||||
import { joinIP } from "@/lib/utils"
|
||||
import { ModelForceUpdateResponse, ModelServer as Server } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import { useEffect, useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import useSWR from "swr"
|
||||
|
||||
export default function ServerPage() {
|
||||
const { t } = useTranslation();
|
||||
const { data, mutate, error, isLoading } = useSWR<Server[]>("/api/v1/server", swrFetcher);
|
||||
const { serverGroups } = useServer();
|
||||
const { t } = useTranslation()
|
||||
const { data, mutate, error, isLoading } = useSWR<Server[]>("/api/v1/server", swrFetcher)
|
||||
const { serverGroups } = useServer()
|
||||
|
||||
useEffect(() => {
|
||||
if (error)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.ErrorFetchingResource", { error: error.message }),
|
||||
});
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [error]);
|
||||
}, [error])
|
||||
|
||||
const columns: ColumnDef<Server>[] = [
|
||||
{
|
||||
@@ -72,8 +71,8 @@ export default function ServerPage() {
|
||||
accessorKey: "name",
|
||||
accessorFn: (row) => row.name,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-24 whitespace-normal break-words">{s.name}</div>;
|
||||
const s = row.original
|
||||
return <div className="max-w-24 whitespace-normal break-words">{s.name}</div>
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -81,16 +80,22 @@ export default function ServerPage() {
|
||||
accessorKey: "groups",
|
||||
accessorFn: (row) => {
|
||||
return (
|
||||
serverGroups?.filter((sg) => sg.servers?.includes(row.id)).map((sg) => sg.group.id) || []
|
||||
);
|
||||
serverGroups
|
||||
?.filter((sg) => sg.servers?.includes(row.id))
|
||||
.map((sg) => sg.group.id) || []
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "ip",
|
||||
header: "IP",
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <div className="max-w-24 whitespace-normal break-words">{joinIP(s.geoip?.ip)}</div>;
|
||||
const s = row.original
|
||||
return (
|
||||
<div className="max-w-24 whitespace-normal break-words">
|
||||
{joinIP(s.geoip?.ip)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -112,15 +117,15 @@ export default function ServerPage() {
|
||||
id: "note",
|
||||
header: t("Note"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
return <NoteMenu note={{ private: s.note, public: s.public_note }} />;
|
||||
const s = row.original
|
||||
return <NoteMenu note={{ private: s.note, public: s.public_note }} />
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: t("Actions"),
|
||||
cell: ({ row }) => {
|
||||
const s = row.original;
|
||||
const s = row.original
|
||||
return (
|
||||
<ActionButtonGroup
|
||||
className="flex gap-2"
|
||||
@@ -131,25 +136,25 @@ export default function ServerPage() {
|
||||
<ServerCard mutate={mutate} data={s} />
|
||||
</>
|
||||
</ActionButtonGroup>
|
||||
);
|
||||
)
|
||||
},
|
||||
},
|
||||
];
|
||||
]
|
||||
|
||||
const dataCache = useMemo(() => {
|
||||
return data ?? [];
|
||||
}, [data]);
|
||||
return data ?? []
|
||||
}, [data])
|
||||
|
||||
const table = useReactTable({
|
||||
data: dataCache,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
})
|
||||
|
||||
const selectedRows = table.getSelectedRowModel().rows;
|
||||
const selectedRows = table.getSelectedRowModel().rows
|
||||
|
||||
return (
|
||||
<div className="px-8">
|
||||
<div className="px-3">
|
||||
<div className="flex mt-6 mb-4">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{t("Server")}</h1>
|
||||
<HeaderButtonGroup
|
||||
@@ -163,33 +168,40 @@ export default function ServerPage() {
|
||||
<IconButton
|
||||
icon="update"
|
||||
onClick={async () => {
|
||||
const id = selectedRows.map((r) => r.original.id);
|
||||
const id = selectedRows.map((r) => r.original.id)
|
||||
if (id.length < 1) {
|
||||
toast(t("Error"), {
|
||||
description: t("Results.SelectAtLeastOneServer"),
|
||||
});
|
||||
return;
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
let resp: ModelForceUpdateResponse = {};
|
||||
let resp: ModelForceUpdateResponse = {}
|
||||
try {
|
||||
resp = await forceUpdateServer(id);
|
||||
resp = await forceUpdateServer(id)
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
console.error(e)
|
||||
toast(t("Error"), {
|
||||
description: t("Results.UnExpectedError"),
|
||||
});
|
||||
return;
|
||||
})
|
||||
return
|
||||
}
|
||||
toast(t("Done"), {
|
||||
description: t("Results.ForceUpdate")
|
||||
+ (resp.success?.length ? t(`Success`) + ` [${resp.success.join(",")}]` : "")
|
||||
+ (resp.failure?.length ? t(`Failure`) + ` [${resp.failure.join(",")}]` : "")
|
||||
+ (resp.offline?.length ? t(`Offline`) + ` [${resp.offline.join(",")}]` : "")
|
||||
});
|
||||
description:
|
||||
t("Results.ForceUpdate") +
|
||||
(resp.success?.length
|
||||
? t(`Success`) + ` [${resp.success.join(",")}]`
|
||||
: "") +
|
||||
(resp.failure?.length
|
||||
? t(`Failure`) + ` [${resp.failure.join(",")}]`
|
||||
: "") +
|
||||
(resp.offline?.length
|
||||
? t(`Offline`) + ` [${resp.offline.join(",")}]`
|
||||
: ""),
|
||||
})
|
||||
}}
|
||||
/>
|
||||
<InstallCommandsMenu className="bg-blue-700" />
|
||||
<InstallCommandsMenu className="shadow-[inset_0_1px_0_rgba(255,255,255,0.2)] bg-blue-700 text-white hover:bg-blue-600 dark:hover:bg-blue-800 rounded-lg" />
|
||||
</HeaderButtonGroup>
|
||||
</div>
|
||||
<Table>
|
||||
@@ -201,9 +213,12 @@ export default function ServerPage() {
|
||||
<TableHead key={header.id} className="text-sm">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
@@ -235,5 +250,5 @@ export default function ServerPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user