Compare commits

...

4 Commits

Author SHA1 Message Date
Fu Diwei
c40de5d3b2 build: vite.config.ts 2024-12-18 13:24:35 +08:00
Fu Diwei
2b1da81b98 chore 2024-12-18 13:19:55 +08:00
Fu Diwei
d693d26323 refactor: clean code 2024-12-18 10:27:55 +08:00
Fu Diwei
2374bb56fa refactor: clean code 2024-12-18 10:20:32 +08:00
32 changed files with 102 additions and 114 deletions

6
.gitignore vendored
View File

@ -15,8 +15,6 @@ vendor
pb_data
build
main
/ui/dist/*
!/ui/dist/.gitkeep
./dist
./certimate
/dist
/docker/data
/certimate

10
ui/.gitignore vendored
View File

@ -1,3 +1,8 @@
node_modules
dist
dist-ssr
!dist/.gitkeep
# Logs
logs
*.log
@ -6,10 +11,6 @@ yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
./ui/.env
node_modules
dist-ssr
*.local
# Editor directories and files
.vscode/*
@ -22,4 +23,5 @@ dist-ssr
*.sln
*.sw?
*.local
.env

View File

@ -1,30 +0,0 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level `parserOptions` property like this:
```js
export default {
// other rules...
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
project: ["./tsconfig.json", "./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: __dirname,
},
};
```
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list

View File

@ -12,6 +12,6 @@
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils"
"utils": "@/components/ui/utils"
}
}

View File

@ -1,6 +1,7 @@
import { useEffect, useLayoutEffect, useState } from "react";
import { RouterProvider } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useCreation } from "ahooks";
import { App, ConfigProvider, theme, type ThemeConfig } from "antd";
import { type Locale } from "antd/es/locale";
import AntdLocaleEnUs from "antd/locale/en_US";
@ -9,30 +10,36 @@ import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import { localeNames } from "./i18n";
import { useTheme } from "./hooks";
import { useBrowserTheme } from "./hooks";
import { router } from "./router.tsx";
const RootApp = () => {
const { i18n } = useTranslation();
const { theme: browserTheme } = useTheme();
const { theme: browserTheme } = useBrowserTheme();
const antdLocalesMap: Record<string, Locale> = {
[localeNames.ZH]: AntdLocaleZhCN,
[localeNames.EN]: AntdLocaleEnUs,
};
const antdLocalesMap: Record<string, Locale> = useCreation(
() => ({
[localeNames.ZH]: AntdLocaleZhCN,
[localeNames.EN]: AntdLocaleEnUs,
}),
[]
);
const [antdLocale, setAntdLocale] = useState(antdLocalesMap[i18n.language]);
const handleLanguageChanged = () => {
setAntdLocale(antdLocalesMap[i18n.language]);
dayjs.locale(i18n.language);
};
i18n.on("languageChanged", handleLanguageChanged);
useLayoutEffect(handleLanguageChanged, [i18n]);
useLayoutEffect(handleLanguageChanged, [antdLocalesMap, i18n]);
const antdThemesMap: Record<string, ThemeConfig> = {
["light"]: { algorithm: theme.defaultAlgorithm },
["dark"]: { algorithm: theme.darkAlgorithm },
};
const antdThemesMap: Record<string, ThemeConfig> = useCreation(
() => ({
["light"]: { algorithm: theme.defaultAlgorithm },
["dark"]: { algorithm: theme.darkAlgorithm },
}),
[]
);
const [antdTheme, setAntdTheme] = useState(antdThemesMap[browserTheme]);
useEffect(() => {
setAntdTheme(antdThemesMap[browserTheme]);
@ -40,7 +47,7 @@ const RootApp = () => {
const root = window.document.documentElement;
root.classList.remove("light", "dark");
root.classList.add(browserTheme);
}, [browserTheme]);
}, [antdThemesMap, browserTheme]);
return (
<ConfigProvider

View File

@ -46,7 +46,7 @@ import AccessEditFormTencentCloudConfig from "./AccessEditFormTencentCloudConfig
import AccessEditFormVolcEngineConfig from "./AccessEditFormVolcEngineConfig";
import AccessEditFormWebhookConfig from "./AccessEditFormWebhookConfig";
type AccessEditFormModelType = Partial<Omit<AccessModel, "id" | "created" | "updated" | "deleted">>;
type AccessEditFormModelType = Partial<MaybeModelRecord<AccessModel>>;
export type AccessEditFormProps = {
className?: string;
@ -79,9 +79,9 @@ const AccessEditForm = forwardRef<AccessEditFormInstance, AccessEditFormProps>((
const formRule = createSchemaFieldRule(formSchema);
const [form] = Form.useForm<z.infer<typeof formSchema>>();
const [initialValues, setInitialValues] = useState<Partial<z.infer<typeof formSchema>>>(model ?? {});
const [initialValues, setInitialValues] = useState<Partial<z.infer<typeof formSchema>>>(model as Partial<z.infer<typeof formSchema>>);
useEffect(() => {
setInitialValues(model ?? {});
setInitialValues(model as Partial<z.infer<typeof formSchema>>);
}, [model]);
const [configType, setConfigType] = useState(model?.configType);

View File

@ -5,10 +5,11 @@ import { Modal, notification } from "antd";
import { type AccessModel } from "@/domain/access";
import { useAccessStore } from "@/stores/access";
import { getErrMsg } from "@/utils/error";
import AccessEditForm, { type AccessEditFormInstance } from "./AccessEditForm";
export type AccessEditModalProps = {
data?: Partial<AccessModel>;
data?: Partial<MaybeModelRecord<AccessModel>>;
loading?: boolean;
mode: "add" | "edit" | "copy";
open?: boolean;
@ -72,7 +73,7 @@ const AccessEditModal = ({ data, loading, mode, trigger, ...props }: AccessEditM
setOpen(false);
} catch (err) {
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
throw err;
} finally {

View File

@ -1,4 +0,0 @@
declare module "antd/locale/zh_CN" {
import zhCN from "antd/locale/zh_CN";
export default zhCN;
}

View File

@ -1,5 +1,3 @@
import { type BaseModel } from "pocketbase";
/*
ASCII
NOTICE: If you add new constant, please keep ASCII order.

View File

@ -1,8 +1,6 @@
import { type BaseModel } from "pocketbase";
import { type WorkflowModel } from "./workflow";
import { WorkflowModel } from "./workflow";
export interface CertificateModel extends Omit<BaseModel, "created" | "updated"> {
export interface CertificateModel extends BaseModel {
san: string;
certificate: string;
privateKey: string;

View File

@ -1,6 +1,4 @@
import { type BaseModel } from "pocketbase";
export interface SettingsModel<T> extends Omit<BaseModel, "created" | "updated"> {
export interface SettingsModel<T> extends BaseModel {
name: string;
content: T;
}

View File

@ -1,6 +1,5 @@
import { produce } from "immer";
import { nanoid } from "nanoid";
import { type BaseModel } from "pocketbase";
import i18n from "@/i18n";
import { deployTargets, KVType } from "./domain";
@ -28,7 +27,7 @@ export type WorkflowOutput = {
error: string;
};
export interface WorkflowModel extends Omit<BaseModel, "created" | "updated"> {
export interface WorkflowModel extends BaseModel {
name: string;
description?: string;
type: string;
@ -152,6 +151,8 @@ export const initWorkflow = (): WorkflowModel => {
crontab: "0 0 * * *",
enabled: false,
draft: rs,
created: new Date().toUTCString(),
updated: new Date().toUTCString(),
};
};

View File

@ -24,11 +24,6 @@
--input: 20 5.9% 90%;
--ring: 24.6 95% 53.1%;
--radius: 0.5rem;
--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 {
@ -51,10 +46,5 @@
--border: 12 6.5% 15.1%;
--input: 12 6.5% 15.1%;
--ring: 20.5 90.2% 48.2%;
--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%;
}
}

13
ui/src/global.d.ts vendored Normal file
View File

@ -0,0 +1,13 @@
import { type BaseModel as PbBaseModel } from "pocketbase";
declare global {
declare interface BaseModel extends PbBaseModel {
deleted?: string;
}
declare type MaybeModelRecord<T extends BaseModel = BaseModel> = T | Omit<T, "id" | "created" | "updated" | "deleted">;
declare type MaybeModelRecordWithId<T extends BaseModel = BaseModel> = T | Pick<T, "id">;
}
export {};

View File

@ -1,3 +1,3 @@
import useTheme from "./useTheme";
import useBrowserTheme from "./useBrowserTheme";
export { useTheme };
export { useBrowserTheme };

View File

@ -16,7 +16,7 @@ import {
} from "lucide-react";
import Version from "@/components/Version";
import { useTheme } from "@/hooks";
import { useBrowserTheme } from "@/hooks";
import { getPocketBase } from "@/repository/pocketbase";
const ConsoleLayout = () => {
@ -182,7 +182,7 @@ const SiderMenu = memo(({ onSelect }: { onSelect?: (key: string) => void }) => {
const ThemeToggleButton = memo(({ size }: { size?: ButtonProps["size"] }) => {
const { t } = useTranslation();
const { theme, setThemeMode } = useTheme();
const { theme, setThemeMode } = useBrowserTheme();
const items: Required<MenuProps>["items"] = [
["light", t("common.theme.light")],

View File

@ -9,6 +9,7 @@ import { ClientResponseError } from "pocketbase";
import AccessEditModal from "@/components/access/AccessEditModal";
import { accessProvidersMap, type AccessModel } from "@/domain/access";
import { useAccessStore } from "@/stores/access";
import { getErrMsg } from "@/utils/error";
const AccessList = () => {
const { t } = useTranslation();
@ -119,7 +120,7 @@ const AccessList = () => {
}
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
});
}, []);
@ -140,7 +141,7 @@ const AccessList = () => {
}
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
} finally {
setLoading(false);
}
@ -160,7 +161,7 @@ const AccessList = () => {
await deleteAccess(data);
} catch (err) {
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
}
},
});

View File

@ -10,6 +10,7 @@ import { ClientResponseError } from "pocketbase";
import CertificateDetailDrawer from "@/components/certificate/CertificateDetailDrawer";
import { CertificateModel } from "@/domain/certificate";
import { list as listCertificate, type CertificateListReq } from "@/repository/certificate";
import { getErrMsg } from "@/utils/error";
const CertificateList = () => {
const navigate = useNavigate();
@ -195,7 +196,7 @@ const CertificateList = () => {
}
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
} finally {
setLoading(false);
}

View File

@ -14,6 +14,7 @@ import { ClientResponseError } from "pocketbase";
import { type Statistics } from "@/domain/statistics";
import { get as getStatistics } from "@/api/statistics";
import { getErrMsg } from "@/utils/error";
const Dashboard = () => {
const navigate = useNavigate();
@ -49,7 +50,7 @@ const Dashboard = () => {
}
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
} finally {
setLoading(false);
}

View File

@ -6,6 +6,7 @@ import { createSchemaFieldRule } from "antd-zod";
import { z } from "zod";
import { getPocketBase } from "@/repository/pocketbase";
import { getErrMsg } from "@/utils/error";
const Login = () => {
const navigage = useNavigate();
@ -29,7 +30,7 @@ const Login = () => {
await getPocketBase().admins.authWithPassword(fields.username, fields.password);
navigage("/");
} catch (err) {
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
} finally {
setFormPending(false);
}

View File

@ -25,6 +25,7 @@ import { ClientResponseError } from "pocketbase";
import { WorkflowModel } from "@/domain/workflow";
import { list as listWorkflow, remove as removeWorkflow, save as saveWorkflow } from "@/repository/workflow";
import { getErrMsg } from "@/utils/error";
const WorkflowList = () => {
const navigate = useNavigate();
@ -227,7 +228,7 @@ const WorkflowList = () => {
}
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
} finally {
setLoading(false);
}
@ -255,7 +256,7 @@ const WorkflowList = () => {
}
} catch (err) {
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
}
};
@ -271,7 +272,7 @@ const WorkflowList = () => {
}
} catch (err) {
console.error(err);
notificationApi.error({ message: t("common.text.request_error"), description: <>{String(err)}</> });
notificationApi.error({ message: t("common.text.request_error"), description: <>{getErrMsg(err)}</> });
}
},
});

View File

@ -12,7 +12,7 @@ export const list = async () => {
});
};
export const save = async (record: AccessModel | Omit<AccessModel, "id" | "created" | "updated" | "deleted">) => {
export const save = async (record: MaybeModelRecord<AccessModel>) => {
if (record.id) {
return await getPocketBase().collection(COLLECTION_NAME).update<AccessModel>(record.id, record);
}
@ -20,7 +20,7 @@ export const save = async (record: AccessModel | Omit<AccessModel, "id" | "creat
return await getPocketBase().collection(COLLECTION_NAME).create<AccessModel>(record);
};
export const remove = async (record: AccessModel) => {
export const remove = async (record: MaybeModelRecordWithId<AccessModel>) => {
record = { ...record, deleted: dayjs.utc().format("YYYY-MM-DD HH:mm:ss") };
await getPocketBase().collection(COLLECTION_NAME).update<AccessModel>(record.id!, record);
};

View File

@ -1,4 +1,4 @@
import { SettingsModel } from "@/domain/settings";
import { type SettingsModel } from "@/domain/settings";
import { getPocketBase } from "./pocketbase";
export const get = async <T>(name: string) => {
@ -13,7 +13,7 @@ export const get = async <T>(name: string) => {
}
};
export const save = async <T>(record: SettingsModel<T>) => {
export const save = async <T>(record: MaybeModelRecordWithId<SettingsModel<T>>) => {
if (record.id) {
return await getPocketBase().collection("settings").update<SettingsModel<T>>(record.id, record);
}

View File

@ -39,7 +39,7 @@ export const save = async (record: Record<string, string | boolean | WorkflowNod
return await getPocketBase().collection(COLLECTION_NAME).create<WorkflowModel>(record);
};
export const remove = async (record: WorkflowModel) => {
export const remove = async (record: MaybeModelRecordWithId<WorkflowModel>) => {
return await getPocketBase().collection(COLLECTION_NAME).delete(record.id);
};

View File

@ -6,9 +6,9 @@ import { list as listAccess, save as saveAccess, remove as removeAccess } from "
export interface AccessState {
accesses: AccessModel[];
createAccess: (access: Omit<AccessModel, "id" | "created" | "udpated" | "deleted">) => void;
updateAccess: (access: AccessModel) => void;
deleteAccess: (access: AccessModel) => void;
createAccess: (access: MaybeModelRecord<AccessModel>) => void;
updateAccess: (access: MaybeModelRecordWithId<AccessModel>) => void;
deleteAccess: (access: MaybeModelRecordWithId<AccessModel>) => void;
fetchAccesses: () => Promise<void>;
}

View File

@ -36,14 +36,14 @@ export const useWorkflowStore = create<WorkflowState>((set, get) => ({
id: "",
name: "placeholder",
type: WorkflowNodeType.Start,
},
} as WorkflowModel,
initialized: false,
init: async (id?: string) => {
let data: WorkflowModel = {
let data = {
id: "",
name: "placeholder",
type: "auto",
};
} as WorkflowModel;
if (!id) {
data = initWorkflow();

View File

@ -11,5 +11,5 @@ export const getErrMsg = (error: unknown): string => {
return error;
}
return "Something went wrong";
return String(error ?? "Unknown error");
};

View File

@ -4,12 +4,18 @@
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
"@/*": [
"./src/*"
]
},
/* Bundler mode */
"moduleResolution": "bundler",
@ -25,5 +31,7 @@
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "src/declarations.d.ts"]
"include": [
"src"
]
}

View File

@ -11,8 +11,9 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
"@/*": [
"./src/*"
]
}
}
}

View File

@ -9,5 +9,7 @@
"strict": true,
"noEmit": true
},
"include": ["vite.config.ts"]
"include": [
"vite.config.ts"
]
}

View File

@ -12,7 +12,7 @@ const preserveFilesPlugin = (filesToPreserve: string[]): Plugin => {
// 在构建开始时将要保留的文件或目录移动到临时位置
filesToPreserve.forEach((file) => {
const srcPath = path.resolve(__dirname, file);
const tempPath = path.resolve(__dirname, `temp_${file}`);
const tempPath = path.resolve(__dirname, `node_modules`, `.tmp`, `build_${file}`);
if (fs.existsSync(srcPath)) {
fs.moveSync(srcPath, tempPath, { overwrite: true });
}
@ -22,7 +22,7 @@ const preserveFilesPlugin = (filesToPreserve: string[]): Plugin => {
// 在构建完成后将临时位置的文件或目录移回原来的位置
filesToPreserve.forEach((file) => {
const srcPath = path.resolve(__dirname, file);
const tempPath = path.resolve(__dirname, `temp_${file}`);
const tempPath = path.resolve(__dirname, `node_modules`, `.tmp`, `build_${file}`);
if (fs.existsSync(tempPath)) {
fs.moveSync(tempPath, srcPath, { overwrite: true });
}