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 { upstream_dns_file } = getState().dnsConfig;
const { bootstrap_dns, upstream_dns, local_ptr_upstreams, fallback_dns } = const { bootstrap_dns, upstream_dns, local_ptr_upstreams, fallback_dns } = formValues;
getState().form[FORM_NAME.UPSTREAM].values;
return dispatch( return dispatch(
testUpstream( testUpstream(

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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