Skip to content

A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.

feat(SchemaForm): `UIAction` support for refreshing form configuration functions

haitaoo9afb26fcba9f
diff --git a/ui/src/common/interface.ts b/ui/src/common/interface.ts
index cafbee2f..e1dda5e5 100644
--- a/ui/src/common/interface.ts
+++ b/ui/src/common/interface.ts
@@ -1,5 +1,3 @@
-import { UIOptions, UIWidget } from '@/components/SchemaForm';
-
export interface FormValue<T = any> {
value: T;
isInvalid: boolean;
@@ -565,27 +563,6 @@ export interface UserOauthConnectorItem extends OauthConnectorItem {
binding: boolean;
external_id: string;
}
-export interface PluginOption {
- label: string;
- value: string;
-}
-
-export interface PluginItem {
- name: string;
- type: UIWidget;
- title: string;
- description: string;
- ui_options?: UIOptions;
- options?: PluginOption[];
- value?: string;
- required?: boolean;
-}
-
-export interface PluginConfig {
- name: string;
- slug_name: string;
- config_fields: PluginItem[];
-}
export interface QuestionOperationReq {
id: string;
diff --git a/ui/src/components/SchemaForm/components/Button.tsx b/ui/src/components/SchemaForm/components/Button.tsx
index 8ae3b704..0440e5ce 100644
--- a/ui/src/components/SchemaForm/components/Button.tsx
+++ b/ui/src/components/SchemaForm/components/Button.tsx
@@ -2,15 +2,14 @@ import React, { FC, useLayoutEffect, useState } from 'react';
import { Button, ButtonProps, Spinner } from 'react-bootstrap';
import { request } from '@/utils';
-import type * as Type from '@/common/interface';
-import type { UIAction } from '../types';
+import type { UIAction, FormKit } from '../types';
import { useToast } from '@/hooks';
interface Props {
fieldName: string;
text: string;
action: UIAction | undefined;
- formData: Type.FormDataType;
+ formKit: FormKit;
readOnly: boolean;
variant?: ButtonProps['variant'];
size?: ButtonProps['size'];
@@ -18,8 +17,7 @@ interface Props {
const Index: FC<Props> = ({
fieldName,
action,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- formData,
+ formKit,
text = '',
readOnly = false,
variant = 'primary',
@@ -27,8 +25,8 @@ const Index: FC<Props> = ({
}) => {
const Toast = useToast();
const [isLoading, setLoading] = useState(false);
- const handleNotify = (msg, type: 'success' | 'danger' = 'success') => {
- const tm = action?.toastMessage;
+ const handleToast = (msg, type: 'success' | 'danger' = 'success') => {
+ const tm = action?.on_complete?.toast_return_message;
if (tm === false || !msg) {
return;
}
@@ -37,6 +35,13 @@ const Index: FC<Props> = ({
variant: type,
});
};
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const handleCallback = (resp) => {
+ const callback = action?.on_complete;
+ if (callback?.refresh_form_config) {
+ formKit.refreshConfig();
+ }
+ };
const handleAction = () => {
if (!action) {
return;
@@ -50,12 +55,13 @@ const Index: FC<Props> = ({
})
.then((resp) => {
if ('message' in resp) {
- handleNotify(resp.message, 'success');
+ handleToast(resp.message, 'success');
}
+ handleCallback(resp);
})
.catch((ex) => {
if (ex && 'msg' in ex) {
- handleNotify(ex.msg, 'danger');
+ handleToast(ex.msg, 'danger');
}
})
.finally(() => {
diff --git a/ui/src/components/SchemaForm/index.tsx b/ui/src/components/SchemaForm/index.tsx
index b7d13112..2fec88e0 100644
--- a/ui/src/components/SchemaForm/index.tsx
+++ b/ui/src/components/SchemaForm/index.tsx
@@ -4,14 +4,15 @@ import React, {
useImperativeHandle,
useEffect,
} from 'react';
-import { Form, Button, ButtonProps } from 'react-bootstrap';
+import { Form, Button } from 'react-bootstrap';
import { useTranslation } from 'react-i18next';
+import { isEmpty } from 'lodash';
import classnames from 'classnames';
import type * as Type from '@/common/interface';
-import type { UIAction } from './types';
+import type { JSONSchema, UISchema, BaseUIOptions, FormKit } from './types';
import {
Legend,
Select,
@@ -21,122 +22,16 @@ import {
Upload,
Textarea,
Input,
- Button as CtrlButton,
+ Button as SfButton,
} from './components';
-export interface JSONSchema {
- title: string;
- description?: string;
- required?: string[];
- properties: {
- [key: string]: {
- type: 'string' | 'boolean' | 'number';
- title: string;
- description?: string;
- enum?: Array<string | boolean | number>;
- enumNames?: string[];
- default?: string | boolean | number;
- };
- };
-}
-
-export interface BaseUIOptions {
- empty?: string;
- // Will be appended to the className of the form component itself
- className?: classnames.Argument;
- // The className that will be attached to a form field container
- fieldClassName?: classnames.Argument;
- // Make a form component render into simplified mode
- readOnly?: boolean;
- simplify?: boolean;
- validator?: (
- value,
- formData?,
- ) => Promise<string | true | void> | true | string;
-}
-
-export interface InputOptions extends BaseUIOptions {
- placeholder?: string;
- inputType?:
- | 'color'
- | 'date'
- | 'datetime-local'
- | 'email'
- | 'month'
- | 'number'
- | 'password'
- | 'range'
- | 'search'
- | 'tel'
- | 'text'
- | 'time'
- | 'url'
- | 'week';
-}
-export interface SelectOptions extends BaseUIOptions {}
-export interface UploadOptions extends BaseUIOptions {
- acceptType?: string;
- imageType?: Type.UploadType;
-}
-
-export interface SwitchOptions extends BaseUIOptions {
- label?: string;
-}
-
-export interface TimezoneOptions extends BaseUIOptions {
- placeholder?: string;
-}
-
-export interface CheckboxOptions extends BaseUIOptions {}
-
-export interface RadioOptions extends BaseUIOptions {}
-
-export interface TextareaOptions extends BaseUIOptions {
- placeholder?: string;
- rows?: number;
-}
-
-export interface ButtonOptions extends BaseUIOptions {
- text: string;
- icon?: string;
- action?: UIAction;
- variant?: ButtonProps['variant'];
- size?: ButtonProps['size'];
-}
-
-export type UIOptions =
- | InputOptions
- | SelectOptions
- | UploadOptions
- | SwitchOptions
- | TimezoneOptions
- | CheckboxOptions
- | RadioOptions
- | TextareaOptions
- | ButtonOptions;
-
-export type UIWidget =
- | 'textarea'
- | 'input'
- | 'checkbox'
- | 'radio'
- | 'select'
- | 'upload'
- | 'timezone'
- | 'switch'
- | 'legend'
- | 'button';
-export interface UISchema {
- [key: string]: {
- 'ui:widget'?: UIWidget;
- 'ui:options'?: UIOptions;
- };
-}
+export * from './types';
interface IProps {
- schema: JSONSchema;
+ schema: JSONSchema | null;
+ formData: Type.FormDataType | null;
uiSchema?: UISchema;
- formData?: Type.FormDataType;
+ refreshConfig?: FormKit['refreshConfig'];
hiddenSubmit?: boolean;
onChange?: (data: Type.FormDataType) => void;
onSubmit?: (e: React.FormEvent) => void;
@@ -148,6 +43,7 @@ interface IRef {
/**
* TODO:
+ * - [!] Standardised `Admin/Plugins/Config/index.tsx` method for generating dynamic form configurations.
* - Normalize and document `formData[key].hidden && 'd-none'`
* - Normalize and document `hiddenSubmit`
* - Improving field hints for `formData`
@@ -168,7 +64,8 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
{
schema,
uiSchema = {},
- formData = {},
+ refreshConfig,
+ formData,
onChange,
onSubmit,
hiddenSubmit = false,
@@ -181,11 +78,10 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
const { required = [], properties = {} } = schema || {};
// check required field
const excludes = required.filter((key) => !properties[key]);
-
if (excludes.length > 0) {
console.error(t('not_found_props', { key: excludes.join(', ') }));
}
-
+ formData ||= {};
const keys = Object.keys(properties);
/**
* Prevent components such as `select` from having default values,
@@ -193,14 +89,14 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
*/
const setDefaultValueAsDomBehaviour = () => {
keys.forEach((k) => {
- const fieldVal = formData[k]?.value;
+ const fieldVal = formData![k]?.value;
const metaProp = properties[k];
const uiCtrl = uiSchema[k]?.['ui:widget'];
if (!metaProp || !uiCtrl || fieldVal !== undefined) {
return;
}
if (uiCtrl === 'select' && metaProp.enum?.[0] !== undefined) {
- formData[k] = {
+ formData![k] = {
errorMsg: '',
isInvalid: false,
value: metaProp.enum?.[0],
@@ -212,10 +108,22 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
setDefaultValueAsDomBehaviour();
}, [formData]);
+ const formKitWithContext: FormKit = {
+ refreshConfig() {
+ if (typeof refreshConfig === 'function') {
+ refreshConfig();
+ }
+ },
+ };
+
+ /**
+ * Form validation
+ * - Currently only dynamic forms are in use, the business form validation has been handed over to the server
+ */
const requiredValidator = () => {
const errors: string[] = [];
required.forEach((key) => {
- if (!formData[key] || !formData[key].value) {
+ if (!formData![key] || !formData![key].value) {
errors.push(key);
}
});
@@ -231,7 +139,7 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
keys.forEach((key) => {
const { validator } = uiSchema[key]?.['ui:options'] || {};
if (validator instanceof Function) {
- const value = formData[key]?.value;
+ const value = formData![key]?.value;
promises.push({
key,
promise: validator(value, formData),
@@ -269,14 +177,14 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
if (errors.length > 0) {
formData = errors.reduce((acc, cur) => {
acc[cur] = {
- ...formData[cur],
+ ...formData![cur],
isInvalid: true,
errorMsg:
uiSchema[cur]?.['ui:options']?.empty ||
- `${schema.properties[cur]?.title} ${t('empty')}`,
+ `${properties[cur]?.title} ${t('empty')}`,
};
return acc;
- }, formData);
+ }, formData || {});
if (onChange instanceof Function) {
onChange({ ...formData });
}
@@ -286,13 +194,12 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
if (syncErrors.length > 0) {
formData = syncErrors.reduce((acc, cur) => {
acc[cur.key] = {
- ...formData[cur.key],
+ ...formData![cur.key],
isInvalid: true,
- errorMsg:
- cur.msg || `${schema.properties[cur.key].title} ${t('invalid')}`,
+ errorMsg: cur.msg || `${properties[cur.key].title} ${t('invalid')}`,
};
return acc;
- }, formData);
+ }, formData || {});
if (onChange instanceof Function) {
onChange({ ...formData });
}
@@ -308,12 +215,12 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
return;
}
- Object.keys(formData).forEach((key) => {
- formData[key].isInvalid = false;
- formData[key].errorMsg = '';
+ Object.keys(formData!).forEach((key) => {
+ formData![key].isInvalid = false;
+ formData![key].errorMsg = '';
});
if (onChange instanceof Function) {
- onChange(formData);
+ onChange(formData!);
}
if (onSubmit instanceof Function) {
onSubmit(e);
@@ -323,9 +230,10 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
useImperativeHandle(ref, () => ({
validator,
}));
- if (!formData || !schema || !schema.properties) {
+ if (!formData || !schema || isEmpty(schema.properties)) {
return null;
}
+
return (
<Form noValidate onSubmit={handleSubmit}>
{keys.map((key) => {
@@ -336,7 +244,8 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
enumNames = [],
} = properties[key];
const { 'ui:widget': widget = 'input', 'ui:options': uiOpt } =
- uiSchema[key] || {};
+ uiSchema?.[key] || {};
+ formData ||= {};
const fieldState = formData[key];
const uiSimplify = widget === 'legend' || uiOpt?.simplify;
let groupClassName: BaseUIOptions['fieldClassName'] = uiOpt?.simplify
@@ -441,11 +350,11 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
/>
) : null}
{widget === 'button' ? (
- <CtrlButton
+ <SfButton
fieldName={key}
text={uiOpt && 'text' in uiOpt ? uiOpt.text : ''}
action={uiOpt && 'action' in uiOpt ? uiOpt.action : undefined}
- formData={formData}
+ formKit={formKitWithContext}
readOnly={readOnly}
variant={
uiOpt && 'variant' in uiOpt ? uiOpt.variant : undefined
@@ -473,8 +382,9 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
};
export const initFormData = (schema: JSONSchema): Type.FormDataType => {
const formData: Type.FormDataType = {};
- Object.keys(schema.properties).forEach((key) => {
- const prop = schema.properties[key];
+ const props: JSONSchema['properties'] = schema?.properties || {};
+ Object.keys(props).forEach((key) => {
+ const prop = props[key];
const defaultVal = prop?.default;
formData[key] = {
@@ -486,4 +396,27 @@ export const initFormData = (schema: JSONSchema): Type.FormDataType => {
return formData;
};
+export const mergeFormData = (
+ target: Type.FormDataType | null,
+ origin: Type.FormDataType | null,
+) => {
+ if (!target) {
+ return origin;
+ }
+ if (!origin) {
+ return target;
+ }
+ Object.keys(target).forEach((k) => {
+ const oi = origin[k];
+ if (oi && oi.value !== undefined) {
+ target[k] = {
+ value: oi.value,
+ isInvalid: false,
+ errorMsg: '',
+ };
+ }
+ });
+ return target;
+};
+
export default forwardRef(SchemaForm);
diff --git a/ui/src/components/SchemaForm/types.ts b/ui/src/components/SchemaForm/types.ts
index 80d62986..a6eed6ef 100644
--- a/ui/src/components/SchemaForm/types.ts
+++ b/ui/src/components/SchemaForm/types.ts
@@ -1,3 +1,118 @@
+import { ButtonProps } from 'react-bootstrap';
+
+import classnames from 'classnames';
+
+import * as Type from '@/common/interface';
+
+export interface JSONSchema {
+ title: string;
+ description?: string;
+ required?: string[];
+ properties: {
+ [key: string]: {
+ type: 'string' | 'boolean' | 'number';
+ title: string;
+ description?: string;
+ enum?: Array<string | boolean | number>;
+ enumNames?: string[];
+ default?: string | boolean | number;
+ };
+ };
+}
+
+export interface BaseUIOptions {
+ empty?: string;
+ // Will be appended to the className of the form component itself
+ className?: classnames.Argument;
+ // The className that will be attached to a form field container
+ fieldClassName?: classnames.Argument;
+ // Make a form component render into simplified mode
+ readOnly?: boolean;
+ simplify?: boolean;
+ validator?: (
+ value,
+ formData?,
+ ) => Promise<string | true | void> | true | string;
+}
+
+export interface InputOptions extends BaseUIOptions {
+ placeholder?: string;
+ inputType?:
+ | 'color'
+ | 'date'
+ | 'datetime-local'
+ | 'email'
+ | 'month'
+ | 'number'
+ | 'password'
+ | 'range'
+ | 'search'
+ | 'tel'
+ | 'text'
+ | 'time'
+ | 'url'
+ | 'week';
+}
+export interface SelectOptions extends BaseUIOptions {}
+export interface UploadOptions extends BaseUIOptions {
+ acceptType?: string;
+ imageType?: Type.UploadType;
+}
+
+export interface SwitchOptions extends BaseUIOptions {
+ label?: string;
+}
+
+export interface TimezoneOptions extends BaseUIOptions {
+ placeholder?: string;
+}
+
+export interface CheckboxOptions extends BaseUIOptions {}
+
+export interface RadioOptions extends BaseUIOptions {}
+
+export interface TextareaOptions extends BaseUIOptions {
+ placeholder?: string;
+ rows?: number;
+}
+
+export interface ButtonOptions extends BaseUIOptions {
+ text: string;
+ icon?: string;
+ action?: UIAction;
+ variant?: ButtonProps['variant'];
+ size?: ButtonProps['size'];
+}
+
+export type UIOptions =
+ | InputOptions
+ | SelectOptions
+ | UploadOptions
+ | SwitchOptions
+ | TimezoneOptions
+ | CheckboxOptions
+ | RadioOptions
+ | TextareaOptions
+ | ButtonOptions;
+
+export type UIWidget =
+ | 'textarea'
+ | 'input'
+ | 'checkbox'
+ | 'radio'
+ | 'select'
+ | 'upload'
+ | 'timezone'
+ | 'switch'
+ | 'legend'
+ | 'button';
+export interface UISchema {
+ [key: string]: {
+ 'ui:widget'?: UIWidget;
+ 'ui:options'?: UIOptions;
+ };
+}
+
/**
* A few notes on button control:
* - Mainly used to send a request and notify the result of the request, and to update the data as required
@@ -9,20 +124,29 @@
* @field callback: Button event handler function that will fully take over the button events when this field is configured
* *** Incomplete, DO NOT USE ***
* @field loading: Set button loading information
- * @field notify: Configure how button action processing results are prompted
- */
-
-/**
- * TODO:
- * - Refining the type of `notify.options`
+ * @field on_complete: What needs to be done when the `Action` completes
+ * @field on_complete.toast_return_message: Does toast show the returned message
+ * @field on_complete.refresh_form_config: Whether to refresh the form configuration (configuration only, no data included)
*/
export interface UIAction {
url: string;
method?: 'get' | 'post' | 'put' | 'delete';
- callback?: () => Promise<void>;
loading?: {
text: string;
- state?: 'none' | 'pending' | 'completed';
- }
- toastMessage?: boolean;
+ state?: 'none' | 'pending' | 'completed';
+ };
+ on_complete?: {
+ toast_return_message?: boolean;
+ refresh_form_config?: boolean;
+ };
+}
+
+/**
+ * Form tools
+ * - Used to get or set the configuration of forms and form items, the value of a form item
+ * * @method refreshConfig(): void
+ */
+
+export interface FormKit {
+ refreshConfig(): void;
}
diff --git a/ui/src/pages/Admin/Plugins/Config/index.tsx b/ui/src/pages/Admin/Plugins/Config/index.tsx
index 2a5bc0c1..4ed58d4e 100644
--- a/ui/src/pages/Admin/Plugins/Config/index.tsx
+++ b/ui/src/pages/Admin/Plugins/Config/index.tsx
@@ -2,18 +2,23 @@ import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
-import { isEmpty } from 'lodash';
-
import { useToast } from '@/hooks';
import type * as Types from '@/common/interface';
-import { SchemaForm, JSONSchema, initFormData, UISchema } from '@/components';
+import { SchemaForm, JSONSchema, UISchema } from '@/components';
import { useQueryPluginConfig, updatePluginConfig } from '@/services';
-import { InputOptions } from '@/components/SchemaForm';
+import {
+ InputOptions,
+ FormKit,
+ initFormData,
+ mergeFormData,
+} from '@/components/SchemaForm';
const Config = () => {
const { t } = useTranslation('translation');
const { slug_name } = useParams<{ slug_name: string }>();
- const { data } = useQueryPluginConfig({ plugin_slug_name: slug_name });
+ const { data, mutate: refreshPluginConfig } = useQueryPluginConfig({
+ plugin_slug_name: slug_name,
+ });
const Toast = useToast();
const [schema, setSchema] = useState<JSONSchema | null>(null);
const [uiSchema, setUISchema] = useState<UISchema>();
@@ -62,7 +67,7 @@ const Config = () => {
};
setSchema(result);
setUISchema(uiConf);
- setFormData(initFormData(result));
+ setFormData(mergeFormData(initFormData(result), formData));
}, [data?.config_fields]);
const onSubmit = (evt) => {
@@ -86,24 +91,19 @@ const Config = () => {
});
});
};
-
+ const refreshConfig: FormKit['refreshConfig'] = async () => {
+ refreshPluginConfig();
+ };
const handleOnChange = (form) => {
setFormData(form);
};
-
- if (!data || !schema || !formData) {
- return null;
- }
-
- if (isEmpty(schema.properties)) {
- return <h3 className="mb-4">{data?.name}</h3>;
- }
return (
<>
<h3 className="mb-4">{data?.name}</h3>
<SchemaForm
schema={schema}
uiSchema={uiSchema}
+ refreshConfig={refreshConfig}
formData={formData}
onSubmit={onSubmit}
onChange={handleOnChange}
diff --git a/ui/src/plugins/types.ts b/ui/src/plugins/types.ts
new file mode 100644
index 00000000..faca6ad0
--- /dev/null
+++ b/ui/src/plugins/types.ts
@@ -0,0 +1,23 @@
+import { UIOptions, UIWidget } from '@/components/SchemaForm';
+
+export interface PluginOption {
+ label: string;
+ value: string;
+}
+
+export interface PluginItem {
+ name: string;
+ type: UIWidget;
+ title: string;
+ description: string;
+ ui_options?: UIOptions;
+ options?: PluginOption[];
+ value?: string;
+ required?: boolean;
+}
+
+export interface PluginConfig {
+ name: string;
+ slug_name: string;
+ config_fields: PluginItem[];
+}
diff --git a/ui/src/services/admin/plugins.ts b/ui/src/services/admin/plugins.ts
index 8ff94458..e58acb02 100644
--- a/ui/src/services/admin/plugins.ts
+++ b/ui/src/services/admin/plugins.ts
@@ -1,8 +1,8 @@
import qs from 'qs';
import useSWR from 'swr';
-import type * as Types from '@/common/interface';
import request from '@/utils/request';
+import type { PluginConfig } from '@/plugins/types';
export const useQueryPlugins = (params) => {
const apiUrl = `/answer/admin/api/plugins?${qs.stringify(params)}`;
@@ -24,7 +24,7 @@ export const updatePluginStatus = (params) => {
export const useQueryPluginConfig = (params) => {
const apiUrl = `/answer/admin/api/plugin/config?${qs.stringify(params)}`;
- const { data, error, mutate } = useSWR<Types.PluginConfig, Error>(
+ const { data, error, mutate } = useSWR<PluginConfig, Error>(
apiUrl,
request.instance.get,
);
diff --git a/ui/src/utils/request.ts b/ui/src/utils/request.ts
index 6a6ae194..e8cd3b6e 100644
--- a/ui/src/utils/request.ts
+++ b/ui/src/utils/request.ts
@@ -57,10 +57,10 @@ class Request {
(error) => {
const {
status,
- data: errModel,
+ data: errBody,
config: errConfig,
} = error.response || {};
- const { data = {}, msg = '' } = errModel || {};
+ const { data = {}, msg = '' } = errBody || {};
const errorObject: {
code: any;
msg: string;