update components to use react-hook-form

This commit is contained in:
dmitrii 2024-12-24 13:55:54 +03:00
parent da808bfcbc
commit 914affe0c0
8 changed files with 830 additions and 615 deletions

View file

@ -424,10 +424,9 @@ export const testUpstream =
}
};
export const testUpstreamWithFormValues = () => async (dispatch: any, getState: any) => {
export const testUpstreamWithFormValues = (formValues: any) => async (dispatch: any, getState: any) => {
const { upstream_dns_file } = getState().dnsConfig;
const { bootstrap_dns, upstream_dns, local_ptr_upstreams, fallback_dns } =
getState().form[FORM_NAME.UPSTREAM].values;
const { bootstrap_dns, upstream_dns, local_ptr_upstreams, fallback_dns } = formValues;
return dispatch(
testUpstream(

View file

@ -1,28 +1,32 @@
import React, { useCallback } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import React from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { renderInputField, toNumber } from '../../../helpers/form';
import { FORM_NAME, UINT32_RANGE } from '../../../helpers/constants';
import { UINT32_RANGE } from '../../../helpers/constants';
import {
validateIpv4,
validateRequiredValue,
validateIpv4RangeEnd,
validateGatewaySubnetMask,
validateIpForGatewaySubnetMask,
validateIpv4,
validateIpv4RangeEnd,
validateNotInRange,
validateRequiredValue,
} from '../../../helpers/validators';
import { RootState } from '../../../initialState';
interface FormDHCPv4Props {
handleSubmit: (...args: unknown[]) => string;
submitting: boolean;
initialValues: { v4?: any };
type FormValues = {
v4?: {
gateway_ip?: string;
subnet_mask?: string;
range_start?: string;
range_end?: string;
lease_duration?: number;
};
}
type FormDHCPv4Props = {
processingConfig?: boolean;
change: (field: string, value: any) => void;
reset: () => void;
initialValues?: FormValues;
ipv4placeholders?: {
gateway_ip: string;
subnet_mask: string;
@ -30,70 +34,96 @@ interface FormDHCPv4Props {
range_end: string;
lease_duration: string;
};
onSubmit?: (data: FormValues) => Promise<void> | void;
}
const FormDHCPv4 = ({ handleSubmit, submitting, processingConfig, ipv4placeholders }: FormDHCPv4Props) => {
const FormDHCPv4 = ({
processingConfig,
initialValues,
ipv4placeholders,
onSubmit
}: FormDHCPv4Props) => {
const { t } = useTranslation();
const dhcp = useSelector((state: RootState) => state.form[FORM_NAME.DHCPv4], shallowEqual);
const interfaces = useSelector((state: RootState) => state.form[FORM_NAME.DHCP_INTERFACES], shallowEqual);
const interfaces = useSelector((state: RootState) => state.form.DHCP_INTERFACES);
const interface_name = interfaces?.values?.interface_name;
const isInterfaceIncludesIpv4 = useSelector(
(state: RootState) => !!state.dhcp?.interfaces?.[interface_name]?.ipv4_addresses,
);
const isEmptyConfig = !Object.values(dhcp?.values?.v4 ?? {}).some(Boolean);
const invalid =
dhcp?.syncErrors ||
interfaces?.syncErrors ||
!isInterfaceIncludesIpv4 ||
isEmptyConfig ||
submitting ||
processingConfig;
const validateRequired = useCallback(
(value) => {
if (isEmptyConfig) {
return undefined;
}
return validateRequiredValue(value);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
watch,
} = useForm<FormValues>({
mode: 'onChange',
defaultValues: {
v4: initialValues?.v4 || {
gateway_ip: '',
subnet_mask: '',
range_start: '',
range_end: '',
lease_duration: 0,
},
},
[isEmptyConfig],
);
});
const formValues = watch('v4');
const isEmptyConfig = !Object.values(formValues || {}).some(Boolean);
const handleFormSubmit = async (data: FormValues) => {
if (onSubmit) {
await onSubmit(data);
}
};
return (
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(handleFormSubmit)}>
<div className="row">
<div className="col-lg-6">
<div className="form__group form__group--settings">
<label>{t('dhcp_form_gateway_input')}</label>
<Field
name="v4.gateway_ip"
component={renderInputField}
<input
type="text"
className="form-control"
placeholder={t(ipv4placeholders.gateway_ip)}
validate={[validateIpv4, validateRequired, validateNotInRange]}
placeholder={t(ipv4placeholders?.gateway_ip || '')}
disabled={!isInterfaceIncludesIpv4}
{...register('v4.gateway_ip', {
validate: {
ipv4: validateIpv4,
required: (value) => isEmptyConfig ? undefined : validateRequiredValue(value),
notInRange: validateNotInRange,
}
})}
/>
{errors.v4?.gateway_ip && (
<div className="form__message form__message--error">
{t(errors.v4.gateway_ip.message)}
</div>
)}
</div>
<div className="form__group form__group--settings">
<label>{t('dhcp_form_subnet_input')}</label>
<Field
name="v4.subnet_mask"
component={renderInputField}
<input
type="text"
className="form-control"
placeholder={t(ipv4placeholders.subnet_mask)}
validate={[validateRequired, validateGatewaySubnetMask]}
placeholder={t(ipv4placeholders?.subnet_mask || '')}
disabled={!isInterfaceIncludesIpv4}
{...register('v4.subnet_mask', {
validate: {
required: (value) => isEmptyConfig ? undefined : validateRequiredValue(value),
subnet: validateGatewaySubnetMask,
}
})}
/>
{errors.v4?.subnet_mask && (
<div className="form__message form__message--error">
{t(errors.v4.subnet_mask.message)}
</div>
)}
</div>
</div>
@ -105,52 +135,79 @@ const FormDHCPv4 = ({ handleSubmit, submitting, processingConfig, ipv4placeholde
</div>
<div className="col">
<Field
name="v4.range_start"
component={renderInputField}
<input
type="text"
className="form-control"
placeholder={t(ipv4placeholders.range_start)}
validate={[validateIpv4, validateIpForGatewaySubnetMask]}
placeholder={t(ipv4placeholders?.range_start || '')}
disabled={!isInterfaceIncludesIpv4}
{...register('v4.range_start', {
validate: {
ipv4: validateIpv4,
gateway: validateIpForGatewaySubnetMask,
}
})}
/>
{errors.v4?.range_start && (
<div className="form__message form__message--error">
{t(errors.v4.range_start.message)}
</div>
)}
</div>
<div className="col">
<Field
name="v4.range_end"
component={renderInputField}
<input
type="text"
className="form-control"
placeholder={t(ipv4placeholders.range_end)}
validate={[validateIpv4, validateIpv4RangeEnd, validateIpForGatewaySubnetMask]}
placeholder={t(ipv4placeholders?.range_end || '')}
disabled={!isInterfaceIncludesIpv4}
{...register('v4.range_end', {
validate: {
ipv4: validateIpv4,
rangeEnd: validateIpv4RangeEnd,
gateway: validateIpForGatewaySubnetMask,
}
})}
/>
{errors.v4?.range_end && (
<div className="form__message form__message--error">
{errors.v4.range_end.message}
</div>
)}
</div>
</div>
</div>
<div className="form__group form__group--settings">
<label>{t('dhcp_form_lease_title')}</label>
<Field
name="v4.lease_duration"
component={renderInputField}
<input
type="number"
className="form-control"
placeholder={t(ipv4placeholders.lease_duration)}
validate={validateRequired}
normalize={toNumber}
placeholder={t(ipv4placeholders?.lease_duration || '')}
disabled={!isInterfaceIncludesIpv4}
min={1}
max={UINT32_RANGE.MAX}
disabled={!isInterfaceIncludesIpv4}
{...register('v4.lease_duration', {
valueAsNumber: true,
validate: {
required: (value) => isEmptyConfig ? undefined : validateRequiredValue(value),
}
})}
/>
{errors.v4?.lease_duration && (
<div className="form__message form__message--error">
{t(errors.v4.lease_duration.message)}
</div>
)}
</div>
</div>
</div>
<div className="btn-list">
<button type="submit" className="btn btn-success btn-standard" disabled={invalid}>
<button
type="submit"
className="btn btn-success btn-standard"
disabled={isSubmitting || processingConfig || !isInterfaceIncludesIpv4 || isEmptyConfig || Object.keys(errors).length > 0}
>
{t('save_config')}
</button>
</div>
@ -158,9 +215,4 @@ const FormDHCPv4 = ({ handleSubmit, submitting, processingConfig, ipv4placeholde
);
};
export default reduxForm<
Record<string, any>,
Omit<FormDHCPv4Props, 'submitting' | 'handleSubmit' | 'reset' | 'change'>
>({
form: FORM_NAME.DHCPv4,
})(FormDHCPv4);
export default FormDHCPv4;

View file

@ -1,64 +1,73 @@
import React, { useCallback } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import React from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { renderInputField, toNumber } from '../../../helpers/form';
import { FORM_NAME, UINT32_RANGE } from '../../../helpers/constants';
import { UINT32_RANGE } from '../../../helpers/constants';
import { validateIpv6, validateRequiredValue } from '../../../helpers/validators';
import { RootState } from '../../../initialState';
interface FormDHCPv6Props {
handleSubmit: (...args: unknown[]) => string;
submitting: boolean;
initialValues: {
v6?: any;
type FormValues = {
v6?: {
range_start?: string;
range_end?: string;
lease_duration?: number;
};
change: (field: string, value: any) => void;
reset: () => void;
}
type FormDHCPv6Props = {
processingConfig?: boolean;
initialValues?: FormValues;
ipv6placeholders?: {
range_start: string;
range_end: string;
lease_duration: string;
};
onSubmit?: (data: FormValues) => Promise<void> | void;
}
const FormDHCPv6 = ({ handleSubmit, submitting, processingConfig, ipv6placeholders }: FormDHCPv6Props) => {
const FormDHCPv6 = ({
processingConfig,
initialValues,
ipv6placeholders,
onSubmit,
}: FormDHCPv6Props) => {
const { t } = useTranslation();
const dhcp = useSelector((state: RootState) => state.form[FORM_NAME.DHCPv6], shallowEqual);
const interfaces = useSelector((state: RootState) => state.form[FORM_NAME.DHCP_INTERFACES], shallowEqual);
const interfaces = useSelector((state: RootState) => state.form.DHCP_INTERFACES);
const interface_name = interfaces?.values?.interface_name;
const isInterfaceIncludesIpv6 = useSelector(
(state: RootState) => !!state.dhcp?.interfaces?.[interface_name]?.ipv6_addresses,
);
const isEmptyConfig = !Object.values(dhcp?.values?.v6 ?? {}).some(Boolean);
const invalid =
dhcp?.syncErrors ||
interfaces?.syncErrors ||
!isInterfaceIncludesIpv6 ||
isEmptyConfig ||
submitting ||
processingConfig;
const validateRequired = useCallback(
(value) => {
if (isEmptyConfig) {
return undefined;
}
return validateRequiredValue(value);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
watch,
} = useForm<FormValues>({
mode: 'onChange',
defaultValues: {
v6: initialValues?.v6 || {
range_start: '',
range_end: '',
lease_duration: 0,
},
},
[isEmptyConfig],
);
});
const formValues = watch('v6');
const isEmptyConfig = !Object.values(formValues || {}).some(Boolean);
const handleFormSubmit = async (data: FormValues) => {
if (onSubmit) {
await onSubmit(data);
}
};
return (
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(handleFormSubmit)}>
<div className="row">
<div className="col-lg-6">
<div className="form__group form__group--settings">
@ -68,27 +77,43 @@ const FormDHCPv6 = ({ handleSubmit, submitting, processingConfig, ipv6placeholde
</div>
<div className="col">
<Field
name="v6.range_start"
component={renderInputField}
<input
type="text"
className="form-control"
placeholder={t(ipv6placeholders.range_start)}
validate={[validateIpv6, validateRequired]}
placeholder={t(ipv6placeholders?.range_start || '')}
disabled={!isInterfaceIncludesIpv6}
{...register('v6.range_start', {
validate: {
ipv6: validateIpv6,
required: (value) => isEmptyConfig ? undefined : validateRequiredValue(value),
}
})}
/>
{errors.v6?.range_start && (
<div className="form__message form__message--error">
{t(errors.v6.range_start.message)}
</div>
)}
</div>
<div className="col">
<Field
name="v6.range_end"
component="input"
<input
type="text"
className="form-control disabled cursor--not-allowed"
placeholder={t(ipv6placeholders.range_end)}
value={t(ipv6placeholders.range_end)}
disabled
className="form-control"
placeholder={t(ipv6placeholders?.range_end || '')}
disabled={!isInterfaceIncludesIpv6}
{...register('v6.range_end', {
validate: {
ipv6: validateIpv6,
required: (value) => isEmptyConfig ? undefined : validateRequiredValue(value),
}
})}
/>
{errors.v6?.range_end && (
<div className="form__message form__message--error">
{t(errors.v6.range_end.message)}
</div>
)}
</div>
</div>
</div>
@ -98,24 +123,34 @@ const FormDHCPv6 = ({ handleSubmit, submitting, processingConfig, ipv6placeholde
<div className="row">
<div className="col-lg-6 form__group form__group--settings">
<label>{t('dhcp_form_lease_title')}</label>
<Field
name="v6.lease_duration"
component={renderInputField}
<input
type="number"
className="form-control"
placeholder={t(ipv6placeholders.lease_duration)}
validate={validateRequired}
normalizeOnBlur={toNumber}
placeholder={t(ipv6placeholders?.lease_duration || '')}
disabled={!isInterfaceIncludesIpv6}
min={1}
max={UINT32_RANGE.MAX}
disabled={!isInterfaceIncludesIpv6}
{...register('v6.lease_duration', {
valueAsNumber: true,
validate: {
required: (value) => isEmptyConfig ? undefined : validateRequiredValue(value),
}
})}
/>
{errors.v6?.lease_duration && (
<div className="form__message form__message--error">
{t(errors.v6.lease_duration.message)}
</div>
)}
</div>
</div>
<div className="btn-list">
<button type="submit" className="btn btn-success btn-standard" disabled={invalid}>
<button
type="submit"
className="btn btn-success btn-standard"
disabled={isSubmitting || processingConfig || !isInterfaceIncludesIpv6 || isEmptyConfig || Object.keys(errors).length > 0}
>
{t('save_config')}
</button>
</div>
@ -123,9 +158,4 @@ const FormDHCPv6 = ({ handleSubmit, submitting, processingConfig, ipv6placeholde
);
};
export default reduxForm<
Record<string, any>,
Omit<FormDHCPv6Props, 'handleSubmit' | 'change' | 'submitting' | 'reset'>
>({
form: FORM_NAME.DHCPv6,
})(FormDHCPv6);
export default FormDHCPv6;

View file

@ -1,14 +1,21 @@
import React from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { useSelector } from 'react-redux';
import { useForm } from 'react-hook-form';
import { Trans, useTranslation } from 'react-i18next';
import { renderSelectField } from '../../../helpers/form';
import { validateRequiredValue } from '../../../helpers/validators';
import { FORM_NAME } from '../../../helpers/constants';
import { RootState } from '../../../initialState';
type FormValues = {
interface_name: string;
};
type InterfacesProps = {
initialValues?: {
interface_name: string;
};
};
const renderInterfaces = (interfaces: any) =>
Object.keys(interfaces).map((item) => {
const option = interfaces[item];
@ -47,13 +54,13 @@ const getInterfaceValues = ({ gateway_ip, hardware_address, ip_addresses }: any)
},
];
interface renderInterfaceValuesProps {
interface RenderInterfaceValuesProps {
gateway_ip: string;
hardware_address: string;
ip_addresses: string[];
}
const renderInterfaceValues = ({ gateway_ip, hardware_address, ip_addresses }: renderInterfaceValuesProps) => (
const renderInterfaceValues = ({ gateway_ip, hardware_address, ip_addresses }: RenderInterfaceValuesProps) => (
<div className="d-flex align-items-end dhcp__interfaces-info">
<ul className="list-unstyled m-0">
{getInterfaceValues({
@ -75,13 +82,21 @@ const renderInterfaceValues = ({ gateway_ip, hardware_address, ip_addresses }: r
</div>
);
const Interfaces = () => {
const Interfaces = ({ initialValues }: InterfacesProps) => {
const { t } = useTranslation();
const { processingInterfaces, interfaces, enabled } = useSelector((store: RootState) => store.dhcp, shallowEqual);
const { processingInterfaces, interfaces, enabled } = useSelector((store: RootState) => store.dhcp);
const interface_name =
useSelector((store: RootState) => store.form[FORM_NAME.DHCP_INTERFACES]?.values?.interface_name);
const {
register,
watch,
formState: { errors },
} = useForm<FormValues>({
mode: 'onChange',
defaultValues: initialValues,
});
const interface_name = watch('interface_name');
if (processingInterfaces || !interfaces) {
return null;
@ -92,17 +107,27 @@ const Interfaces = () => {
return (
<div className="row dhcp__interfaces">
<div className="col col__dhcp">
<Field
name="interface_name"
component={renderSelectField}
<label htmlFor="interface_name" className="form__label">
{t('dhcp_interface_select')}
</label>
<select
id="interface_name"
className="form-control custom-select pl-4 col-md"
validate={[validateRequiredValue]}
label="dhcp_interface_select">
disabled={enabled}
{...register('interface_name', {
validate: validateRequiredValue,
})}
>
<option value="" disabled={enabled}>
{t('dhcp_interface_select')}
</option>
{renderInterfaces(interfaces)}
</Field>
</select>
{errors.interface_name && (
<div className="form__message form__message--error">
{t(errors.interface_name.message)}
</div>
)}
</div>
{interfaceValue && renderInterfaceValues({
gateway_ip: interfaceValue.gateway_ip,
@ -113,6 +138,4 @@ const Interfaces = () => {
);
};
export default reduxForm({
form: FORM_NAME.DHCP_INTERFACES,
})(Interfaces);
export default Interfaces;

View file

@ -1,13 +1,9 @@
import React from 'react';
import { connect } from 'react-redux';
import { Controller, useForm } from 'react-hook-form';
import { Trans, useTranslation } from 'react-i18next';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow';
import { renderTextareaField } from '../../../../helpers/form';
import { trimMultilineString, removeEmptyLines } from '../../../../helpers/helpers';
import { CLIENT_ID_LINK, FORM_NAME } from '../../../../helpers/constants';
import { CLIENT_ID_LINK } from '../../../../helpers/constants';
import { removeEmptyLines, trimMultilineString } from '../../../../helpers/helpers';
const fields = [
{
@ -31,88 +27,108 @@ const fields = [
];
interface FormProps {
handleSubmit: (...args: unknown[]) => string;
submitting: boolean;
invalid: boolean;
initialValues: object;
initialValues?: {
allowed_clients?: string;
disallowed_clients?: string;
blocked_hosts?: string;
};
onSubmit: (data: any) => void;
processingSet: boolean;
t: (...args: unknown[]) => string;
textarea?: boolean;
allowedClients?: string;
}
interface renderFieldProps {
id?: string;
title?: string;
subtitle?: string;
disabled?: boolean;
processingSet?: boolean;
normalizeOnBlur?: (...args: unknown[]) => unknown;
interface FormData {
allowed_clients: string;
disallowed_clients: string;
blocked_hosts: string;
}
let Form = (props: FormProps) => {
const { allowedClients, handleSubmit, submitting, invalid, processingSet } = props;
const Form = ({ initialValues, onSubmit, processingSet }: FormProps) => {
const { t } = useTranslation();
const {
control,
handleSubmit,
watch,
formState: { isSubmitting, isDirty },
} = useForm<FormData>({
mode: 'onChange',
defaultValues: {
allowed_clients: initialValues?.allowed_clients || '',
disallowed_clients: initialValues?.disallowed_clients || '',
blocked_hosts: initialValues?.blocked_hosts || '',
},
});
const allowedClients = watch('allowed_clients');
const renderField = ({
id,
title,
subtitle,
disabled = false,
processingSet,
normalizeOnBlur,
}: renderFieldProps) => (
<div key={id} className="form__group mb-5">
<label className="form__label form__label--with-desc" htmlFor={id}>
<Trans>{title}</Trans>
}: {
id: keyof FormData;
title: string;
subtitle: string;
normalizeOnBlur: (value: string) => string;
}) => {
const disabled = allowedClients && id === 'disallowed_clients';
{disabled && (
<>
<span> </span>(<Trans>disabled</Trans>)
</>
)}
</label>
return (
<div key={id} className="form__group mb-5">
<label className="form__label form__label--with-desc" htmlFor={id}>
{t(title)}
{disabled && (
<>
<span> </span>({t('disabled')})
</>
)}
</label>
<div className="form__desc form__desc--top">
<Trans
components={{
a: (
<a href={CLIENT_ID_LINK} target="_blank" rel="noopener noreferrer">
text
</a>
),
}}>
{subtitle}
</Trans>
<div className="form__desc form__desc--top">
<Trans
components={{
a: (
<a href={CLIENT_ID_LINK} target="_blank" rel="noopener noreferrer">
{t('text')}
</a>
),
}}>
{subtitle}
</Trans>
</div>
<Controller
name={id}
control={control}
render={({ field }) => (
<textarea
{...field}
id={id}
className="form-control form-control--textarea font-monospace"
disabled={disabled || processingSet}
onBlur={(e) => {
const normalized = normalizeOnBlur(e.target.value);
field.onChange(normalized);
}}
/>
)}
/>
</div>
<Field
id={id}
name={id}
component={renderTextareaField}
type="text"
className="form-control form-control--textarea font-monospace"
disabled={disabled || processingSet}
normalizeOnBlur={normalizeOnBlur}
/>
</div>
);
);
};
return (
<form onSubmit={handleSubmit}>
{fields.map((f) => {
return renderField({
...f,
disabled: allowedClients && f.id === 'disallowed_clients' || false
});
})}
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((f) => renderField(f as { id: keyof FormData; title: string; subtitle: string; normalizeOnBlur: (value: string) => string; }))}
<div className="card-actions">
<div className="btn-list">
<button
type="submit"
className="btn btn-success btn-standard"
disabled={submitting || invalid || processingSet}>
<Trans>save_config</Trans>
disabled={isSubmitting || !isDirty || processingSet}>
{t('save_config')}
</button>
</div>
</div>
@ -120,18 +136,4 @@ let Form = (props: FormProps) => {
);
};
const selector = formValueSelector(FORM_NAME.ACCESS);
Form = connect((state) => {
const allowedClients = selector(state, 'allowed_clients');
return {
allowedClients,
};
})(Form);
export default flow([
withTranslation(),
reduxForm({
form: FORM_NAME.ACCESS,
}),
])(Form);
export default Form;

View file

@ -1,14 +1,11 @@
import React from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { Trans, useTranslation } from 'react-i18next';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { renderInputField, toNumber, CheckboxField } from '../../../../helpers/form';
import { CACHE_CONFIG_FIELDS, FORM_NAME, UINT32_RANGE } from '../../../../helpers/constants';
import { replaceZeroWithEmptyString } from '../../../../helpers/helpers';
import { clearDnsCache } from '../../../../actions/dnsConfig';
import { CACHE_CONFIG_FIELDS, UINT32_RANGE } from '../../../../helpers/constants';
import { replaceZeroWithEmptyString } from '../../../../helpers/helpers';
import { RootState } from '../../../../initialState';
const INPUTS_FIELDS = [
@ -32,21 +29,41 @@ const INPUTS_FIELDS = [
},
];
interface CacheFormProps {
handleSubmit: (...args: unknown[]) => string;
submitting: boolean;
invalid: boolean;
}
type FormData = {
cache_size: number;
cache_ttl_min: number;
cache_ttl_max: number;
cache_optimistic: boolean;
};
const Form = ({ handleSubmit, submitting, invalid }: CacheFormProps) => {
type CacheFormProps = {
initialValues?: Partial<FormData>;
onSubmit: (data: FormData) => void;
};
const Form = ({ initialValues, onSubmit }: CacheFormProps) => {
const { t } = useTranslation();
const dispatch = useDispatch();
const { processingSetConfig } = useSelector((state: RootState) => state.dnsConfig, shallowEqual);
const { cache_ttl_max, cache_ttl_min } = useSelector(
(state: RootState) => state.form[FORM_NAME.CACHE].values,
shallowEqual,
);
const { processingSetConfig } = useSelector((state: RootState) => state.dnsConfig);
const {
register,
handleSubmit,
watch,
formState: { isSubmitting, isDirty },
} = useForm<FormData>({
mode: 'onChange',
defaultValues: {
cache_size: initialValues?.cache_size || 0,
cache_ttl_min: initialValues?.cache_ttl_min || 0,
cache_ttl_max: initialValues?.cache_ttl_max || 0,
cache_optimistic: initialValues?.cache_optimistic || false,
},
});
const cache_ttl_min = watch('cache_ttl_min');
const cache_ttl_max = watch('cache_ttl_max');
const minExceedsMax = cache_ttl_min > 0 && cache_ttl_max > 0 && cache_ttl_min > cache_ttl_max;
@ -57,7 +74,7 @@ const Form = ({ handleSubmit, submitting, invalid }: CacheFormProps) => {
};
return (
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="row">
{INPUTS_FIELDS.map(({ name, title, description, placeholder }) => (
<div className="col-12" key={name}>
@ -69,17 +86,17 @@ const Form = ({ handleSubmit, submitting, invalid }: CacheFormProps) => {
<div className="form__desc form__desc--top">{t(description)}</div>
<Field
name={name}
<input
type="number"
component={renderInputField}
className="form-control"
placeholder={t(placeholder)}
disabled={processingSetConfig}
className="form-control"
normalizeOnBlur={replaceZeroWithEmptyString}
normalize={toNumber}
min={0}
max={UINT32_RANGE.MAX}
{...register(name as keyof FormData, {
valueAsNumber: true,
setValueAs: (value) => replaceZeroWithEmptyString(value),
})}
/>
</div>
</div>
@ -91,14 +108,20 @@ const Form = ({ handleSubmit, submitting, invalid }: CacheFormProps) => {
<div className="row">
<div className="col-12 col-md-7">
<div className="form__group form__group--settings">
<Field
name="cache_optimistic"
type="checkbox"
component={CheckboxField}
placeholder={t('cache_optimistic')}
disabled={processingSetConfig}
subtitle={t('cache_optimistic_desc')}
/>
<label className="checkbox">
<input
type="checkbox"
className="checkbox__input"
disabled={processingSetConfig}
{...register('cache_optimistic')}
/>
<span className="checkbox__label">
<span className="checkbox__label-text checkbox__label-text--long">
<span className="checkbox__label-title">{t('cache_optimistic')}</span>
<span className="checkbox__label-subtitle">{t('cache_optimistic_desc')}</span>
</span>
</span>
</label>
</div>
</div>
</div>
@ -106,18 +129,18 @@ const Form = ({ handleSubmit, submitting, invalid }: CacheFormProps) => {
<button
type="submit"
className="btn btn-success btn-standard btn-large"
disabled={submitting || invalid || processingSetConfig || minExceedsMax}>
<Trans>save_btn</Trans>
disabled={isSubmitting || !isDirty || processingSetConfig || minExceedsMax}>
{t('save_btn')}
</button>
<button
type="button"
className="btn btn-outline-secondary btn-standard form__button"
onClick={handleClearCache}>
<Trans>clear_cache</Trans>
{t('clear_cache')}
</button>
</form>
);
};
export default reduxForm({ form: FORM_NAME.CACHE })(Form);
export default Form;

View file

@ -1,27 +1,16 @@
import React from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { Field, reduxForm } from 'redux-form';
import { Trans, useTranslation } from 'react-i18next';
import {
renderInputField,
renderRadioField,
renderTextareaField,
CheckboxField,
toNumber,
} from '../../../../helpers/form';
import {
validateIp,
validateIpv4,
validateIpv6,
validateRequiredValue,
validateIp,
validateIPv4Subnet,
validateIPv6Subnet,
validateRequiredValue
} from '../../../../helpers/validators';
import { BLOCKING_MODES, UINT32_RANGE } from '../../../../helpers/constants';
import { removeEmptyLines } from '../../../../helpers/helpers';
import { BLOCKING_MODES, FORM_NAME, UINT32_RANGE } from '../../../../helpers/constants';
import { RootState } from '../../../../initialState';
const checkboxes = [
{
@ -49,163 +38,214 @@ const customIps = [
},
];
const getFields = (processing: any, t: any) =>
Object.values(BLOCKING_MODES)
.map((mode: any) => (
<Field
key={mode}
name="blocking_mode"
type="radio"
component={renderRadioField}
value={mode}
placeholder={t(mode)}
disabled={processing}
/>
));
interface ConfigFormProps {
handleSubmit: (...args: unknown[]) => string;
submitting: boolean;
invalid: boolean;
processing?: boolean;
type FormData = {
ratelimit: number;
ratelimit_subnet_len_ipv4: number;
ratelimit_subnet_len_ipv6: number;
ratelimit_whitelist: string;
edns_cs_enabled: boolean;
edns_cs_use_custom: boolean;
edns_cs_custom_ip?: string;
dnssec_enabled: boolean;
disable_ipv6: boolean;
blocking_mode: string;
blocking_ipv4?: string;
blocking_ipv6?: string;
blocked_response_ttl: number;
}
const Form = ({ handleSubmit, submitting, invalid, processing }: ConfigFormProps) => {
type Props = {
processing?: boolean;
initialValues?: Partial<FormData>;
onSubmit: (data: FormData) => void;
}
const Form = ({ processing, initialValues, onSubmit }: Props) => {
const { t } = useTranslation();
const { blocking_mode, edns_cs_enabled, edns_cs_use_custom } = useSelector(
(state: RootState) => state.form[FORM_NAME.BLOCKING_MODE].values ?? {},
shallowEqual,
);
const {
register,
handleSubmit,
watch,
control,
formState: { errors, isSubmitting, isDirty },
} = useForm<FormData>({
mode: 'onChange',
defaultValues: initialValues,
});
const blocking_mode = watch('blocking_mode');
const edns_cs_enabled = watch('edns_cs_enabled');
const edns_cs_use_custom = watch('edns_cs_use_custom');
return (
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="row">
<div className="col-12 col-md-7">
<div className="form__group form__group--settings">
<label htmlFor="ratelimit" className="form__label form__label--with-desc">
<Trans>rate_limit</Trans>
{t('rate_limit')}
</label>
<div className="form__desc form__desc--top">
<Trans>rate_limit_desc</Trans>
{t('rate_limit_desc')}
</div>
<Field
name="ratelimit"
<input
id="ratelimit"
type="number"
component={renderInputField}
className="form-control"
placeholder={t('form_enter_rate_limit')}
normalize={toNumber}
validate={validateRequiredValue}
min={UINT32_RANGE.MIN}
max={UINT32_RANGE.MAX}
disabled={processing}
{...register('ratelimit', {
required: t('form_error_required'),
valueAsNumber: true,
min: UINT32_RANGE.MIN,
max: UINT32_RANGE.MAX,
})}
/>
{errors.ratelimit && (
<div className="form__message form__message--error">
{errors.ratelimit.message}
</div>
)}
</div>
</div>
<div className="col-12 col-md-7">
<div className="form__group form__group--settings">
<label htmlFor="ratelimit_subnet_len_ipv4" className="form__label form__label--with-desc">
<Trans>rate_limit_subnet_len_ipv4</Trans>
{t('rate_limit_subnet_len_ipv4')}
</label>
<div className="form__desc form__desc--top">
<Trans>rate_limit_subnet_len_ipv4_desc</Trans>
{t('rate_limit_subnet_len_ipv4_desc')}
</div>
<Field
name="ratelimit_subnet_len_ipv4"
<input
id="ratelimit_subnet_len_ipv4"
type="number"
component={renderInputField}
className="form-control"
placeholder={t('form_enter_rate_limit_subnet_len')}
normalize={toNumber}
validate={[validateRequiredValue, validateIPv4Subnet]}
min={0}
max={32}
disabled={processing}
{...register('ratelimit_subnet_len_ipv4', {
required: t('form_error_required'),
valueAsNumber: true,
min: 0,
max: 32,
})}
/>
{errors.ratelimit_subnet_len_ipv4 && (
<div className="form__message form__message--error">
{errors.ratelimit_subnet_len_ipv4.message}
</div>
)}
</div>
</div>
<div className="col-12 col-md-7">
<div className="form__group form__group--settings">
<label htmlFor="ratelimit_subnet_len_ipv6" className="form__label form__label--with-desc">
<Trans>rate_limit_subnet_len_ipv6</Trans>
{t('rate_limit_subnet_len_ipv6')}
</label>
<div className="form__desc form__desc--top">
<Trans>rate_limit_subnet_len_ipv6_desc</Trans>
{t('rate_limit_subnet_len_ipv6_desc')}
</div>
<Field
name="ratelimit_subnet_len_ipv6"
<input
id="ratelimit_subnet_len_ipv6"
type="number"
component={renderInputField}
className="form-control"
placeholder={t('form_enter_rate_limit_subnet_len')}
normalize={toNumber}
validate={[validateRequiredValue, validateIPv6Subnet]}
min={0}
max={128}
disabled={processing}
{...register('ratelimit_subnet_len_ipv6', {
required: t('form_error_required'),
valueAsNumber: true,
min: 0,
max: 128,
})}
/>
{errors.ratelimit_subnet_len_ipv6 && (
<div className="form__message form__message--error">
{errors.ratelimit_subnet_len_ipv6.message}
</div>
)}
</div>
</div>
<div className="col-12 col-md-7">
<div className="form__group form__group--settings">
<label htmlFor="ratelimit_whitelist" className="form__label form__label--with-desc">
<Trans>rate_limit_whitelist</Trans>
{t('rate_limit_whitelist')}
</label>
<div className="form__desc form__desc--top">
<Trans>rate_limit_whitelist_desc</Trans>
{t('rate_limit_whitelist_desc')}
</div>
<Field
name="ratelimit_whitelist"
component={renderTextareaField}
type="text"
<textarea
id="ratelimit_whitelist"
className="form-control"
placeholder={t('rate_limit_whitelist_placeholder')}
normalizeOnBlur={removeEmptyLines}
disabled={processing}
{...register('ratelimit_whitelist', {
onChange: removeEmptyLines,
})}
/>
{errors.ratelimit_whitelist && (
<div className="form__message form__message--error">
{errors.ratelimit_whitelist.message}
</div>
)}
</div>
</div>
<div className="col-12">
<div className="form__group form__group--settings">
<Field
name="edns_cs_enabled"
type="checkbox"
component={CheckboxField}
placeholder={t('edns_enable')}
disabled={processing}
subtitle={t('edns_cs_desc')}
/>
<label className="checkbox checkbox--settings">
<span className="checkbox__marker" />
<input
id="edns_cs_enabled"
type="checkbox"
className="checkbox__input"
disabled={processing}
{...register('edns_cs_enabled')}
/>
<span className="checkbox__label">
<span className="checkbox__label-text">
<span className="checkbox__label-title">{t('edns_enable')}</span>
</span>
</span>
</label>
</div>
</div>
<div className="col-12 form__group form__group--inner">
<div className="form__group ">
<Field
name="edns_cs_use_custom"
type="checkbox"
component={CheckboxField}
placeholder={t('edns_use_custom_ip')}
disabled={processing || !edns_cs_enabled}
subtitle={t('edns_use_custom_ip_desc')}
/>
<div className="form__group">
<label className="checkbox checkbox--settings">
<span className="checkbox__marker" />
<input
id="edns_cs_use_custom"
type="checkbox"
className="checkbox__input"
disabled={processing || !edns_cs_enabled}
{...register('edns_cs_use_custom')}
/>
<span className="checkbox__label">
<span className="checkbox__label-text">
<span className="checkbox__label-subtitle">{t('edns_use_custom_ip')}</span>
</span>
</span>
</label>
</div>
{edns_cs_use_custom && (
<Field
name="edns_cs_custom_ip"
component={renderInputField}
<input
id="edns_cs_custom_ip"
type="text"
className="form-control"
placeholder={t('form_enter_ip')}
validate={[validateIp, validateRequiredValue]}
disabled={processing || !edns_cs_enabled}
{...register('edns_cs_custom_ip', {
required: t('form_error_required'),
validate: (value) => validateIp(value) || validateRequiredValue(value),
})}
/>
)}
</div>
@ -213,14 +253,24 @@ const Form = ({ handleSubmit, submitting, invalid, processing }: ConfigFormProps
{checkboxes.map(({ name, placeholder, subtitle }) => (
<div className="col-12" key={name}>
<div className="form__group form__group--settings">
<Field
name={name}
type="checkbox"
component={CheckboxField}
placeholder={t(placeholder)}
disabled={processing}
subtitle={t(subtitle)}
/>
<label className="checkbox checkbox--settings">
<span className="checkbox__marker" />
<input
id={name}
type="checkbox"
className="checkbox__input"
disabled={processing}
{...register(name as keyof FormData)}
/>
<span className="checkbox__label">
<span className="checkbox__label-text">
<span className="checkbox__label-title">{t(placeholder)}</span>
{subtitle && (
<span className="checkbox__label-subtitle">{t(subtitle)}</span>
)}
</span>
</span>
</label>
</div>
</div>
))}
@ -228,7 +278,7 @@ const Form = ({ handleSubmit, submitting, invalid, processing }: ConfigFormProps
<div className="col-12">
<div className="form__group form__group--settings mb-4">
<label className="form__label form__label--with-desc">
<Trans>blocking_mode</Trans>
{t('blocking_mode')}
</label>
<div className="form__desc form__desc--top">
@ -236,12 +286,25 @@ const Form = ({ handleSubmit, submitting, invalid, processing }: ConfigFormProps
.map((mode: any) => (
<li key={mode}>
<Trans>{`blocking_mode_${mode}`}</Trans>
{t(`blocking_mode_${mode}`)}
</li>
))}
</div>
<div className="custom-controls-stacked">{getFields(processing, t)}</div>
<div className="custom-controls-stacked">
{Object.values(BLOCKING_MODES).map((mode: any) => (
<label key={mode} className="custom-control custom-radio">
<input
type="radio"
className="custom-control-input"
value={mode}
disabled={processing}
{...register('blocking_mode')}
/>
<span className="custom-control-label">{t(mode)}</span>
</label>
))}
</div>
</div>
</div>
{blocking_mode === BLOCKING_MODES.custom_ip && (
@ -250,20 +313,28 @@ const Form = ({ handleSubmit, submitting, invalid, processing }: ConfigFormProps
<div className="col-12 col-sm-6" key={name}>
<div className="form__group form__group--settings">
<label className="form__label form__label--with-desc" htmlFor={name}>
<Trans>{name}</Trans>
{t(name)}
</label>
<div className="form__desc form__desc--top">
<Trans>{description}</Trans>
{t(description)}
</div>
<Field
name={name}
component={renderInputField}
<input
id={name}
type="text"
className="form-control"
placeholder={t('form_enter_ip')}
validate={[validateIp, validateRequiredValue]}
disabled={processing}
{...register(name as keyof FormData, {
required: t('form_error_required'),
validate: (value) => validateIp(value) || validateRequiredValue(value),
})}
/>
{errors[name as keyof FormData] && (
<div className="form__message form__message--error">
{errors[name as keyof FormData]?.message}
</div>
)}
</div>
</div>
))}
@ -273,24 +344,30 @@ const Form = ({ handleSubmit, submitting, invalid, processing }: ConfigFormProps
<div className="col-12 col-md-7">
<div className="form__group form__group--settings">
<label htmlFor="blocked_response_ttl" className="form__label form__label--with-desc">
<Trans>blocked_response_ttl</Trans>
{t('blocked_response_ttl')}
</label>
<div className="form__desc form__desc--top">
<Trans>blocked_response_ttl_desc</Trans>
{t('blocked_response_ttl_desc')}
</div>
<Field
name="blocked_response_ttl"
<input
id="blocked_response_ttl"
type="number"
component={renderInputField}
className="form-control"
placeholder={t('form_enter_blocked_response_ttl')}
normalize={toNumber}
validate={validateRequiredValue}
min={UINT32_RANGE.MIN}
max={UINT32_RANGE.MAX}
disabled={processing}
{...register('blocked_response_ttl', {
required: t('form_error_required'),
valueAsNumber: true,
min: UINT32_RANGE.MIN,
max: UINT32_RANGE.MAX,
})}
/>
{errors.blocked_response_ttl && (
<div className="form__message form__message--error">
{errors.blocked_response_ttl.message}
</div>
)}
</div>
</div>
</div>
@ -298,13 +375,11 @@ const Form = ({ handleSubmit, submitting, invalid, processing }: ConfigFormProps
<button
type="submit"
className="btn btn-success btn-standard btn-large"
disabled={submitting || invalid || processing}>
<Trans>save_btn</Trans>
disabled={isSubmitting || !isDirty || processing}>
{t('save_btn')}
</button>
</form>
);
};
export default reduxForm<Record<string, any>, Omit<ConfigFormProps, 'invalid' | 'submitting' | 'handleSubmit'>>({
form: FORM_NAME.BLOCKING_MODE,
})(Form);
export default Form;

View file

@ -1,227 +1,195 @@
import classnames from 'classnames';
import React, { useRef } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { Trans, useTranslation } from 'react-i18next';
import classnames from 'classnames';
import Examples from './Examples';
import { renderRadioField, renderTextareaField, CheckboxField } from '../../../../helpers/form';
import { DNS_REQUEST_OPTIONS, FORM_NAME, UPSTREAM_CONFIGURATION_WIKI_LINK } from '../../../../helpers/constants';
import { testUpstreamWithFormValues } from '../../../../actions';
import { removeEmptyLines, trimLinesAndRemoveEmpty } from '../../../../helpers/helpers';
import { DNS_REQUEST_OPTIONS, UPSTREAM_CONFIGURATION_WIKI_LINK } from '../../../../helpers/constants';
import { removeEmptyLines } from '../../../../helpers/helpers';
import { getTextareaCommentsHighlight, syncScroll } from '../../../../helpers/highlightTextareaComments';
import '../../../ui/texareaCommentsHighlight.css';
import { RootState } from '../../../../initialState';
import '../../../ui/texareaCommentsHighlight.css';
import Examples from './Examples';
const UPSTREAM_DNS_NAME = 'upstream_dns';
const UPSTREAM_MODE_NAME = 'upstream_mode';
interface renderFieldProps {
name: string;
component: any;
type: string;
className?: string;
placeholder: string;
subtitle?: string;
value?: string;
normalizeOnBlur?: (...args: unknown[]) => unknown;
containerClass?: string;
onScroll?: (...args: unknown[]) => unknown;
type FormData = {
upstream_dns: string;
upstream_mode: string;
fallback_dns: string;
bootstrap_dns: string;
local_ptr_upstreams: string;
use_private_ptr_resolvers: boolean;
resolve_clients: boolean;
}
const renderField = ({
name,
component,
type,
className,
placeholder,
subtitle,
value,
normalizeOnBlur,
containerClass,
onScroll,
}: renderFieldProps) => {
const { t } = useTranslation();
const processingTestUpstream = useSelector((state: RootState) => state.settings.processingTestUpstream);
const processingSetConfig = useSelector((state: RootState) => state.dnsConfig.processingSetConfig);
return (
<div key={placeholder} className={classnames('col-12 mb-4', containerClass)}>
<Field
id={name}
value={value}
name={name}
component={component}
type={type}
className={className}
placeholder={t(placeholder)}
subtitle={t(subtitle)}
disabled={processingSetConfig || processingTestUpstream}
normalizeOnBlur={normalizeOnBlur}
onScroll={onScroll}
/>
</div>
);
};
interface renderTextareaWithHighlightFieldProps {
className: string;
disabled?: boolean;
id: string;
input?: object;
meta?: object;
normalizeOnBlur?: (...args: unknown[]) => unknown;
onScroll?: (...args: unknown[]) => unknown;
placeholder: string;
type: string;
type FormProps = {
initialValues?: Partial<FormData>;
onSubmit: (data: FormData) => void;
}
const renderTextareaWithHighlightField = (props: renderTextareaWithHighlightFieldProps) => {
const upstream_dns = useSelector((store: RootState) => store.form[FORM_NAME.UPSTREAM].values.upstream_dns);
const upstream_dns_file = useSelector((state: RootState) => state.dnsConfig.upstream_dns_file);
const ref = useRef(null);
const onScroll = (e: any) => syncScroll(e, ref);
return (
<>
{renderTextareaField({
...props,
disabled: !!upstream_dns_file,
onScroll,
normalizeOnBlur: trimLinesAndRemoveEmpty,
})}
{getTextareaCommentsHighlight(ref, upstream_dns)}
</>
);
};
const INPUT_FIELDS = [
{
name: UPSTREAM_MODE_NAME,
type: 'radio',
value: DNS_REQUEST_OPTIONS.LOAD_BALANCING,
component: renderRadioField,
subtitle: 'load_balancing_desc',
placeholder: 'load_balancing',
},
{
name: UPSTREAM_MODE_NAME,
type: 'radio',
value: DNS_REQUEST_OPTIONS.PARALLEL,
component: renderRadioField,
subtitle: 'upstream_parallel',
placeholder: 'parallel_requests',
},
{
name: UPSTREAM_MODE_NAME,
type: 'radio',
value: DNS_REQUEST_OPTIONS.FASTEST_ADDR,
component: renderRadioField,
subtitle: 'fastest_addr_desc',
placeholder: 'fastest_addr',
},
];
interface FormProps {
handleSubmit?: (...args: unknown[]) => string;
submitting?: boolean;
invalid?: boolean;
initialValues?: object;
upstream_dns?: string;
fallback_dns?: string;
bootstrap_dns?: string;
}
const Form = ({ submitting, invalid, handleSubmit }: FormProps) => {
const dispatch = useDispatch();
const Form = ({ initialValues, onSubmit }: FormProps) => {
const { t } = useTranslation();
const dispatch = useDispatch();
const textareaRef = useRef<HTMLTextAreaElement>(null);
const upstream_dns = useSelector((store: RootState) => store.form[FORM_NAME.UPSTREAM].values.upstream_dns);
const {
control,
handleSubmit,
watch,
formState: { isSubmitting, isDirty },
} = useForm<FormData>({
mode: 'onChange',
defaultValues: {
upstream_dns: initialValues?.upstream_dns || '',
upstream_mode: initialValues?.upstream_mode || DNS_REQUEST_OPTIONS.LOAD_BALANCING,
fallback_dns: initialValues?.fallback_dns || '',
bootstrap_dns: initialValues?.bootstrap_dns || '',
local_ptr_upstreams: initialValues?.local_ptr_upstreams || '',
use_private_ptr_resolvers: initialValues?.use_private_ptr_resolvers || false,
resolve_clients: initialValues?.resolve_clients || false,
},
});
const upstream_dns = watch('upstream_dns');
const processingTestUpstream = useSelector((state: RootState) => state.settings.processingTestUpstream);
const processingSetConfig = useSelector((state: RootState) => state.dnsConfig.processingSetConfig);
const defaultLocalPtrUpstreams = useSelector((state: RootState) => state.dnsConfig.default_local_ptr_upstreams);
const upstream_dns_file = useSelector((state: RootState) => state.dnsConfig.upstream_dns_file);
const handleUpstreamTest = () => dispatch(testUpstreamWithFormValues());
const handleUpstreamTest = () => {
const formValues = {
bootstrap_dns: watch('bootstrap_dns'),
upstream_dns: watch('upstream_dns'),
local_ptr_upstreams: watch('local_ptr_upstreams'),
fallback_dns: watch('fallback_dns'),
};
dispatch(testUpstreamWithFormValues(formValues));
};
const testButtonClass = classnames('btn btn-primary btn-standard mr-2', {
'btn-loading': processingTestUpstream,
});
const components = {
a: <a href={UPSTREAM_CONFIGURATION_WIKI_LINK} target="_blank" rel="noopener noreferrer" />,
};
return (
<form onSubmit={handleSubmit} className="form--upstream">
<form onSubmit={handleSubmit(onSubmit)} className="form--upstream">
<div className="row">
<label className="col form__label" htmlFor={UPSTREAM_DNS_NAME}>
<Trans components={components}>upstream_dns_help</Trans>{' '}
<Trans
components={[
<a
href="https://link.adtidy.org/forward.html?action=dns_kb_providers&from=ui&app=home"
target="_blank"
rel="noopener noreferrer"
key="0">
DNS providers
</a>,
]}>
dns_providers
</Trans>
{t('upstream_dns_help', { a: (text: string) => <a href={UPSTREAM_CONFIGURATION_WIKI_LINK} target="_blank" rel="noopener noreferrer">{text}</a> })}
{' '}
<a
href="https://link.adtidy.org/forward.html?action=dns_kb_providers&from=ui&app=home"
target="_blank"
rel="noopener noreferrer">
{t('dns_providers', { 0: (text: string) => <a href={UPSTREAM_CONFIGURATION_WIKI_LINK} target="_blank" rel="noopener noreferrer">{text}</a> } )}
</a>
</label>
<div className="col-12 mb-4">
<div className="text-edit-container">
<Field
id={UPSTREAM_DNS_NAME}
name={UPSTREAM_DNS_NAME}
component={renderTextareaWithHighlightField}
type="text"
className="form-control form-control--textarea font-monospace text-input"
placeholder={t('upstream_dns')}
disabled={processingSetConfig || processingTestUpstream}
normalizeOnBlur={removeEmptyLines}
<Controller
name="upstream_dns"
control={control}
render={({ field }) => (
<>
<textarea
{...field}
id={UPSTREAM_DNS_NAME}
className="form-control form-control--textarea font-monospace text-input"
placeholder={t('upstream_dns')}
disabled={!!upstream_dns_file || processingSetConfig || processingTestUpstream}
onScroll={(e) => syncScroll(e, textareaRef)}
onBlur={(e) => {
const value = removeEmptyLines(e.target.value);
field.onChange(value);
}}
/>
{getTextareaCommentsHighlight(textareaRef, upstream_dns)}
</>
)}
/>
</div>
</div>
{INPUT_FIELDS.map(renderField)}
<div className="col-12">
<Examples />
<hr />
</div>
{INPUT_FIELDS.map(({ name, value, subtitle, placeholder }) => (
<div key={value} className="col-12 mb-4">
<Controller
name="upstream_mode"
control={control}
render={({ field }) => (
<div className="custom-control custom-radio">
<input
{...field}
type="radio"
className="custom-control-input"
id={`${name}_${value}`}
value={value}
checked={field.value === value}
disabled={processingSetConfig || processingTestUpstream}
/>
<label className="custom-control-label" htmlFor={`${name}_${value}`}>
<span className="custom-control-label__title">{t(placeholder)}</span>
<span className="custom-control-label__subtitle">{t(subtitle)}</span>
</label>
</div>
)}
/>
</div>
))}
<div className="col-12">
<label className="form__label form__label--with-desc" htmlFor="fallback_dns">
<Trans>fallback_dns_title</Trans>
{t('fallback_dns_title')}
</label>
<div className="form__desc form__desc--top">
<Trans>fallback_dns_desc</Trans>
{t('fallback_dns_desc')}
</div>
<Field
id="fallback_dns"
<Controller
name="fallback_dns"
component={renderTextareaField}
type="text"
className="form-control form-control--textarea form-control--textarea-small font-monospace"
placeholder={t('fallback_dns_placeholder')}
disabled={processingSetConfig}
normalizeOnBlur={removeEmptyLines}
control={control}
render={({ field }) => (
<textarea
{...field}
id="fallback_dns"
className="form-control form-control--textarea form-control--textarea-small font-monospace"
placeholder={t('fallback_dns_placeholder')}
disabled={processingSetConfig}
onBlur={(e) => {
const value = removeEmptyLines(e.target.value);
field.onChange(value);
}}
/>
)}
/>
</div>
@ -231,22 +199,29 @@ const Form = ({ submitting, invalid, handleSubmit }: FormProps) => {
<div className="col-12 mb-2">
<label className="form__label form__label--with-desc" htmlFor="bootstrap_dns">
<Trans>bootstrap_dns</Trans>
{t('bootstrap_dns')}
</label>
<div className="form__desc form__desc--top">
<Trans>bootstrap_dns_desc</Trans>
{t('bootstrap_dns_desc')}
</div>
<Field
id="bootstrap_dns"
<Controller
name="bootstrap_dns"
component={renderTextareaField}
type="text"
className="form-control form-control--textarea form-control--textarea-small font-monospace"
placeholder={t('bootstrap_dns')}
disabled={processingSetConfig}
normalizeOnBlur={removeEmptyLines}
control={control}
render={({ field }) => (
<textarea
{...field}
id="bootstrap_dns"
className="form-control form-control--textarea form-control--textarea-small font-monospace"
placeholder={t('bootstrap_dns')}
disabled={processingSetConfig}
onBlur={(e) => {
const value = removeEmptyLines(e.target.value);
field.onChange(value);
}}
/>
)}
/>
</div>
@ -256,43 +231,64 @@ const Form = ({ submitting, invalid, handleSubmit }: FormProps) => {
<div className="col-12">
<label className="form__label form__label--with-desc" htmlFor="local_ptr">
<Trans>local_ptr_title</Trans>
{t('local_ptr_title')}
</label>
<div className="form__desc form__desc--top">
<Trans>local_ptr_desc</Trans>
{t('local_ptr_desc')}
</div>
<div className="form__desc form__desc--top">
{/** TODO: Add internazionalization for "" */}
{defaultLocalPtrUpstreams?.length > 0 ? (
<Trans values={{ ip: defaultLocalPtrUpstreams.map((s: any) => `"${s}"`).join(', ') }}>
local_ptr_default_resolver
</Trans>
) : (
<Trans>local_ptr_no_default_resolver</Trans>
)}
{defaultLocalPtrUpstreams?.length > 0
? t('local_ptr_default_resolver', { ip: defaultLocalPtrUpstreams.map((s: any) => `"${s}"`).join(', ') })
: t('local_ptr_no_default_resolver')}
</div>
<Field
id="local_ptr_upstreams"
<Controller
name="local_ptr_upstreams"
component={renderTextareaField}
type="text"
className="form-control form-control--textarea form-control--textarea-small font-monospace"
placeholder={t('local_ptr_placeholder')}
disabled={processingSetConfig}
normalizeOnBlur={removeEmptyLines}
control={control}
render={({ field }) => (
<textarea
{...field}
id="local_ptr_upstreams"
className="form-control form-control--textarea form-control--textarea-small font-monospace"
placeholder={t('local_ptr_placeholder')}
disabled={processingSetConfig}
onBlur={(e) => {
const value = removeEmptyLines(e.target.value);
field.onChange(value);
}}
/>
)}
/>
<div className="mt-4">
<Field
<Controller
name="use_private_ptr_resolvers"
type="checkbox"
component={CheckboxField}
placeholder={t('use_private_ptr_resolvers_title')}
subtitle={t('use_private_ptr_resolvers_desc')}
disabled={processingSetConfig}
control={control}
render={({ field: { value, onChange, ...field } }) => (
<label className="checkbox">
<span className="checkbox__marker" />
<input
{...field}
type="checkbox"
checked={value}
onChange={(e) => onChange(e.target.checked)}
className="checkbox__input"
disabled={processingSetConfig}
/>
<span className="checkbox__label">
<span className="checkbox__label-text checkbox__label-text--long">
<span className="checkbox__label-title">
{t('use_private_ptr_resolvers_title')}
</span>
<span className="checkbox__label-subtitle">
{t('use_private_ptr_resolvers_desc')}
</span>
</span>
</span>
</label>
)}
/>
</div>
</div>
@ -302,13 +298,28 @@ const Form = ({ submitting, invalid, handleSubmit }: FormProps) => {
</div>
<div className="col-12 mb-4">
<Field
<Controller
name="resolve_clients"
type="checkbox"
component={CheckboxField}
placeholder={t('resolve_clients_title')}
subtitle={t('resolve_clients_desc')}
disabled={processingSetConfig}
control={control}
render={({ field: { value, onChange, ...field } }) => (
<label className="checkbox">
<span className="checkbox__marker" />
<input
{...field}
type="checkbox"
checked={value}
onChange={(e) => onChange(e.target.checked)}
className="checkbox__input"
disabled={processingSetConfig}
/>
<span className="checkbox__label">
<span className="checkbox__label-text checkbox__label-text--long">
<span className="checkbox__label-title">{t('resolve_clients_title')}</span>
<span className="checkbox__label-subtitle">{t('resolve_clients_desc')}</span>
</span>
</span>
</label>
)}
/>
</div>
</div>
@ -320,14 +331,14 @@ const Form = ({ submitting, invalid, handleSubmit }: FormProps) => {
className={testButtonClass}
onClick={handleUpstreamTest}
disabled={!upstream_dns || processingTestUpstream}>
<Trans>test_upstream_btn</Trans>
{t('test_upstream_btn')}
</button>
<button
type="submit"
className="btn btn-success btn-standard"
disabled={submitting || invalid || processingSetConfig || processingTestUpstream}>
<Trans>apply_btn</Trans>
disabled={isSubmitting || !isDirty || processingSetConfig || processingTestUpstream}>
{t('apply_btn')}
</button>
</div>
</div>
@ -335,4 +346,4 @@ const Form = ({ submitting, invalid, handleSubmit }: FormProps) => {
);
};
export default reduxForm({ form: FORM_NAME.UPSTREAM })(Form);
export default Form;