answer/ui/src/pages/Admin/Login/index.tsx

102 lines
2.6 KiB
TypeScript
Raw Normal View History

2022-12-07 18:15:27 +08:00
import { FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type * as Type from '@/common/interface';
import { getLoginSetting, putLoginSetting } from '@/services';
2022-12-07 18:15:27 +08:00
import { SchemaForm, JSONSchema, initFormData, UISchema } from '@/components';
import { useToast } from '@/hooks';
import { handleFormError } from '@/utils';
import { loginSettingStore } from '@/stores';
2022-12-07 18:15:27 +08:00
const Index: FC = () => {
const { t } = useTranslation('translation', {
keyPrefix: 'admin.login',
});
const Toast = useToast();
const schema: JSONSchema = {
title: t('page_title'),
properties: {
allow_new_registrations: {
2022-12-07 18:15:27 +08:00
type: 'boolean',
title: t('membership.title'),
label: t('membership.label'),
2022-12-07 18:15:27 +08:00
description: t('membership.text'),
default: true,
},
login_required: {
type: 'boolean',
title: t('private.title'),
label: t('private.label'),
2022-12-07 18:15:27 +08:00
description: t('private.text'),
default: false,
2022-12-07 18:15:27 +08:00
},
},
};
const uiSchema: UISchema = {
allow_new_registrations: {
2022-12-07 18:15:27 +08:00
'ui:widget': 'switch',
},
login_required: {
2022-12-07 18:15:27 +08:00
'ui:widget': 'switch',
},
};
const [formData, setFormData] = useState(initFormData(schema));
const { update: updateLoginSetting } = loginSettingStore((_) => _);
2022-12-07 18:15:27 +08:00
const onSubmit = (evt) => {
evt.preventDefault();
evt.stopPropagation();
const reqParams: Type.AdminSettingsLogin = {
allow_new_registrations: formData.allow_new_registrations.value,
login_required: formData.login_required.value,
2022-12-07 18:15:27 +08:00
};
putLoginSetting(reqParams)
2022-12-07 18:15:27 +08:00
.then(() => {
Toast.onShow({
msg: t('update', { keyPrefix: 'toast' }),
variant: 'success',
});
updateLoginSetting(reqParams);
2022-12-07 18:15:27 +08:00
})
.catch((err) => {
if (err.isError) {
const data = handleFormError(err, formData);
setFormData({ ...data });
}
});
};
useEffect(() => {
getLoginSetting().then((setting) => {
2022-12-07 18:15:27 +08:00
if (setting) {
const formMeta = { ...formData };
formMeta.allow_new_registrations.value =
setting.allow_new_registrations;
formMeta.login_required.value = setting.login_required;
setFormData({ ...formMeta });
2022-12-07 18:15:27 +08:00
}
});
}, []);
const handleOnChange = (data) => {
setFormData(data);
};
return (
<>
<h3 className="mb-4">{t('page_title')}</h3>
<SchemaForm
schema={schema}
formData={formData}
onSubmit={onSubmit}
uiSchema={uiSchema}
onChange={handleOnChange}
/>
</>
);
};
export default Index;