install forms

This commit is contained in:
Ildar Kamalov 2024-12-12 15:08:42 +03:00
parent 8e43af21d9
commit 0a1739df3b
7 changed files with 529 additions and 491 deletions

22
client/package-lock.json generated vendored
View file

@ -25,6 +25,7 @@
"react": "^16.13.1", "react": "^16.13.1",
"react-click-outside": "^3.0.1", "react-click-outside": "^3.0.1",
"react-dom": "^16.13.1", "react-dom": "^16.13.1",
"react-hook-form": "^7.54.0",
"react-i18next": "^11.7.2", "react-i18next": "^11.7.2",
"react-modal": "^3.11.2", "react-modal": "^3.11.2",
"react-popper-tooltip": "^2.11.1", "react-popper-tooltip": "^2.11.1",
@ -15570,6 +15571,21 @@
"react": "^16.13.1" "react": "^16.13.1"
} }
}, },
"node_modules/react-hook-form": {
"version": "7.54.0",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.54.0.tgz",
"integrity": "sha512-PS05+UQy/IdSbJNojBypxAo9wllhHgGmyr8/dyGQcPoiMf3e7Dfb9PWYVRco55bLbxH9S+1yDDJeTdlYCSxO3A==",
"engines": {
"node": ">=18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/react-hook-form"
},
"peerDependencies": {
"react": "^16.8.0 || ^17 || ^18 || ^19"
}
},
"node_modules/react-hot-loader": { "node_modules/react-hot-loader": {
"version": "4.13.1", "version": "4.13.1",
"resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.13.1.tgz", "resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.13.1.tgz",
@ -31540,6 +31556,12 @@
"scheduler": "^0.19.1" "scheduler": "^0.19.1"
} }
}, },
"react-hook-form": {
"version": "7.54.0",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.54.0.tgz",
"integrity": "sha512-PS05+UQy/IdSbJNojBypxAo9wllhHgGmyr8/dyGQcPoiMf3e7Dfb9PWYVRco55bLbxH9S+1yDDJeTdlYCSxO3A==",
"requires": {}
},
"react-hot-loader": { "react-hot-loader": {
"version": "4.13.1", "version": "4.13.1",
"resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.13.1.tgz", "resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.13.1.tgz",

1
client/package.json vendored
View file

@ -38,6 +38,7 @@
"react": "^16.13.1", "react": "^16.13.1",
"react-click-outside": "^3.0.1", "react-click-outside": "^3.0.1",
"react-dom": "^16.13.1", "react-dom": "^16.13.1",
"react-hook-form": "^7.54.0",
"react-i18next": "^11.7.2", "react-i18next": "^11.7.2",
"react-modal": "^3.11.2", "react-modal": "^3.11.2",
"react-popper-tooltip": "^2.11.1", "react-popper-tooltip": "^2.11.1",

View file

@ -27,7 +27,8 @@ export const setAllSettingsSuccess = createAction('SET_ALL_SETTINGS_SUCCESS');
export const setAllSettings = (values: any) => async (dispatch: any) => { export const setAllSettings = (values: any) => async (dispatch: any) => {
dispatch(setAllSettingsRequest()); dispatch(setAllSettingsRequest());
try { try {
const { confirm_password, ...config } = values; const config = { ...values };
delete config.confirm_password;
await apiClient.setAllSettings(config); await apiClient.setAllSettings(config);
dispatch(setAllSettingsSuccess()); dispatch(setAllSettingsSuccess());
@ -48,7 +49,10 @@ export const checkConfig = (values: any) => async (dispatch: any) => {
dispatch(checkConfigRequest()); dispatch(checkConfigRequest());
try { try {
const check = await apiClient.checkConfig(values); const check = await apiClient.checkConfig(values);
dispatch(checkConfigSuccess(check)); dispatch(checkConfigSuccess({
...values,
check,
}));
} catch (error) { } catch (error) {
dispatch(addErrorToast({ error })); dispatch(addErrorToast({ error }));
dispatch(checkConfigFailure()); dispatch(checkConfigFailure());

View file

@ -1,47 +1,46 @@
import React from 'react'; import React from 'react';
import { useForm } from 'react-hook-form';
import { Field, reduxForm } from 'redux-form';
import { withTranslation, Trans } from 'react-i18next'; import { withTranslation, Trans } from 'react-i18next';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import cn from 'classnames';
import i18n from '../../i18n'; import i18n from '../../i18n';
import Controls from './Controls'; import Controls from './Controls';
import { renderInputField } from '../../helpers/form';
import { FORM_NAME } from '../../helpers/constants';
import { validatePasswordLength } from '../../helpers/validators'; import { validatePasswordLength } from '../../helpers/validators';
const required = (value: any) => { type Props = {
if (value || value === 0) { onAuthSubmit: (...args: unknown[]) => string;
return false;
}
return <Trans>form_error_required</Trans>;
};
const validate = (values: any) => {
const errors: { confirm_password?: string } = {};
if (values.confirm_password !== values.password) {
errors.confirm_password = i18n.t('form_error_password');
}
return errors;
};
interface AuthProps {
handleSubmit: (...args: unknown[]) => string;
pristine: boolean; pristine: boolean;
invalid: boolean; invalid: boolean;
t: (...args: unknown[]) => string; t: (...args: unknown[]) => string;
} }
const Auth = (props: AuthProps) => { const Auth = (props: Props) => {
const { handleSubmit, pristine, invalid, t } = props; const { t, onAuthSubmit } = props;
const {
register,
handleSubmit,
watch,
formState: { errors, isDirty, isValid },
} = useForm({
mode: 'onChange',
defaultValues: {
username: '',
password: '',
confirm_password: '',
},
});
const password = watch('password');
const validateConfirmPassword = (value: string) => {
if (value !== password) {
return i18n.t('form_error_password');
}
return undefined;
};
return ( return (
<form className="setup__step" onSubmit={handleSubmit}> <form className="setup__step" onSubmit={handleSubmit(onAuthSubmit)}>
<div className="setup__group"> <div className="setup__group">
<div className="setup__subtitle"> <div className="setup__subtitle">
<Trans>install_auth_title</Trans> <Trans>install_auth_title</Trans>
@ -55,62 +54,80 @@ const Auth = (props: AuthProps) => {
<label> <label>
<Trans>install_auth_username</Trans> <Trans>install_auth_username</Trans>
</label> </label>
<input
<Field {...register('username', { required: {
name="username" value: true,
component={renderInputField} message: i18n.t('form_error_required'),
}})}
type="text" type="text"
className="form-control" className={cn('form-control', { 'is-invalid': errors.username })}
placeholder={t('install_auth_username_enter')} placeholder={t('install_auth_username_enter')}
validate={[required]}
autoComplete="username" autoComplete="username"
/> />
{errors.username && (
<div className="invalid-feedback">
{errors.username.message}
</div>
)}
</div> </div>
<div className="form-group"> <div className="form-group">
<label> <label>
<Trans>install_auth_password</Trans> <Trans>install_auth_password</Trans>
</label> </label>
<input
<Field {...register('password', {
name="password" required: {
component={renderInputField} value: true,
message: i18n.t('form_error_required'),
},
validate: validatePasswordLength,
})}
type="password" type="password"
className="form-control" className={cn('form-control', { 'is-invalid': errors.password })}
placeholder={t('install_auth_password_enter')} placeholder={t('install_auth_password_enter')}
validate={[required, validatePasswordLength]}
autoComplete="new-password" autoComplete="new-password"
/> />
{errors.password && (
<div className="invalid-feedback">
{errors.password.message || i18n.t('form_error_password_length')}
</div>
)}
</div> </div>
<div className="form-group"> <div className="form-group">
<label> <label>
<Trans>install_auth_confirm</Trans> <Trans>install_auth_confirm</Trans>
</label> </label>
<input
<Field {...register('confirm_password', {
name="confirm_password" required: {
component={renderInputField} value: true,
message: i18n.t('form_error_required'),
},
validate: validateConfirmPassword,
})}
type="password" type="password"
className="form-control" className={cn('form-control', { 'is-invalid': errors.confirm_password })}
placeholder={t('install_auth_confirm')} placeholder={t('install_auth_confirm')}
validate={[required]}
autoComplete="new-password" autoComplete="new-password"
/> />
{errors.confirm_password && (
<div className="invalid-feedback">
{errors.confirm_password.message}
</div>
)}
</div> </div>
</div> </div>
<Controls pristine={pristine} invalid={invalid} /> <Controls
isDirty={isDirty}
isValid={isValid}
/>
</form> </form>
); );
}; };
export default flow([ export default flow([
withTranslation(), withTranslation(),
reduxForm({
form: FORM_NAME.INSTALL,
destroyOnUnmount: false,
forceUnregisterOnUnmount: true,
validate,
}),
])(Auth); ])(Auth);

View file

@ -1,30 +1,65 @@
import React, { Component } from 'react'; import React, { useEffect, useCallback } from 'react';
import { connect } from 'react-redux'; import { useForm, Controller } from 'react-hook-form';
import { Trans, useTranslation } from 'react-i18next';
import { Field, reduxForm, formValueSelector } from 'redux-form'; import i18n from 'i18next';
import { Trans, withTranslation } from 'react-i18next';
import flow from 'lodash/flow';
import i18n, { TFunction } from 'i18next';
import i18next from 'i18next';
import Controls from './Controls'; import Controls from './Controls';
import AddressList from './AddressList'; import AddressList from './AddressList';
import { getInterfaceIp } from '../../helpers/helpers'; import { getInterfaceIp } from '../../helpers/helpers';
import { import {
ALL_INTERFACES_IP, ALL_INTERFACES_IP,
FORM_NAME,
ADDRESS_IN_USE_TEXT, ADDRESS_IN_USE_TEXT,
PORT_53_FAQ_LINK, PORT_53_FAQ_LINK,
STATUS_RESPONSE, STATUS_RESPONSE,
STANDARD_DNS_PORT, STANDARD_DNS_PORT,
STANDARD_WEB_PORT, STANDARD_WEB_PORT,
MAX_PORT,
} from '../../helpers/constants'; } from '../../helpers/constants';
import { renderInputField, toNumber } from '../../helpers/form'; import { toNumber } from '../../helpers/form';
import { validateRequiredValue, validateInstallPort } from '../../helpers/validators'; import { validateRequiredValue } from '../../helpers/validators';
import { DhcpInterface } from '../../initialState'; import { DhcpInterface } from '../../initialState';
const validateInstallPort = (value: any) => {
if (value < 1 || value > MAX_PORT) {
return i18next.t('form_error_port');
}
return undefined;
};
type StaticIpType = {
ip: string;
static: string;
};
type ConfigType = {
web: {
ip: string;
port?: number;
status: string;
can_autofix: boolean;
};
dns: {
ip: string;
port?: number;
status: string;
can_autofix: boolean;
};
staticIp: StaticIpType;
};
type Props = {
handleSubmit: (data: any) => void;
handleChange?: (...args: unknown[]) => unknown;
handleFix: (web: any, dns: any, set_static_ip: boolean) => void;
validateForm: (data: any) => void;
config: ConfigType;
interfaces: DhcpInterface[];
initialValues?: object;
};
const renderInterfaces = (interfaces: DhcpInterface[]) => const renderInterfaces = (interfaces: DhcpInterface[]) =>
Object.values(interfaces).map((option: DhcpInterface) => { Object.values(interfaces).map((option: DhcpInterface) => {
const { name, ip_addresses, flags } = option; const { name, ip_addresses, flags } = option;
@ -43,113 +78,69 @@ const renderInterfaces = (interfaces: DhcpInterface[]) =>
return null; return null;
}); });
type Props = { const Settings: React.FC<Props> = ({
handleSubmit: (...args: unknown[]) => string; handleSubmit,
handleChange?: (...args: unknown[]) => unknown; handleFix,
handleFix: (...args: unknown[]) => unknown; validateForm,
validateForm?: (...args: unknown[]) => unknown; config,
webIp: string; interfaces,
dnsIp: string; }) => {
config: { const { t } = useTranslation();
web: {
status: string;
can_autofix: boolean;
};
dns: {
status: string;
can_autofix: boolean;
};
staticIp: {
ip: string;
static: string;
};
};
webPort?: number;
dnsPort?: number;
interfaces: DhcpInterface[];
invalid: boolean;
initialValues?: object;
t: TFunction;
};
class Settings extends Component<Props> { const defaultValues = {
componentDidMount() {
const { webIp, webPort, dnsIp, dnsPort } = this.props;
this.props.validateForm({
web: { web: {
ip: webIp, ip: config.web.ip || ALL_INTERFACES_IP,
port: webPort, port: config.web.port || STANDARD_WEB_PORT,
}, },
dns: { dns: {
ip: dnsIp, ip: config.dns.ip || ALL_INTERFACES_IP,
port: dnsPort, port: config.dns.port || STANDARD_DNS_PORT,
},
};
const {
control,
watch,
handleSubmit: reactHookFormSubmit,
formState: { isValid, errors },
} = useForm({
defaultValues,
mode: 'onChange',
});
const watchFields = watch();
const { status: webStatus, can_autofix: isWebFixAvailable } = config.web;
const { status: dnsStatus, can_autofix: isDnsFixAvailable } = config.dns;
const { staticIp } = config;
const webIpVal = watch("web.ip");
const webPortVal = watch("web.port");
const dnsIpVal = watch("dns.ip");
const dnsPortVal = watch("dns.port");
useEffect(() => {
validateForm({
web: {
ip: webIpVal,
port: webPortVal,
},
dns: {
ip: dnsIpVal,
port: dnsPortVal,
}, },
}); });
} }, [webIpVal, webPortVal, dnsIpVal, dnsPortVal]);
getStaticIpMessage = (staticIp: { ip: string; static: string }) => {
const { static: status, ip } = staticIp;
switch (status) {
case STATUS_RESPONSE.NO: {
return (
<>
<div className="mb-2">
<Trans values={{ ip }} components={[<strong key="0">text</strong>]}>
install_static_configure
</Trans>
</div>
<button
type="button"
className="btn btn-outline-primary btn-sm"
onClick={() => this.handleStaticIp(ip)}>
<Trans>set_static_ip</Trans>
</button>
</>
);
}
case STATUS_RESPONSE.ERROR: {
return (
<div className="text-danger">
<Trans>install_static_error</Trans>
</div>
);
}
case STATUS_RESPONSE.YES: {
return (
<div className="text-success">
<Trans>install_static_ok</Trans>
</div>
);
}
default:
return null;
}
};
handleAutofix = (type: any) => {
const {
webIp,
webPort,
dnsIp,
dnsPort,
handleFix,
} = this.props;
const handleAutofix = (type: string) => {
const web = { const web = {
ip: webIp, ip: watchFields.web?.ip,
port: webPort, port: watchFields.web?.port,
autofix: false, autofix: false,
}; };
const dns = { const dns = {
ip: dnsIp, ip: watchFields.dns?.ip,
port: dnsPort, port: watchFields.dns?.port,
autofix: false, autofix: false,
}; };
const set_static_ip = false; const set_static_ip = false;
@ -163,64 +154,70 @@ class Settings extends Component<Props> {
handleFix(web, dns, set_static_ip); handleFix(web, dns, set_static_ip);
}; };
handleStaticIp = (ip: any) => { const handleStaticIp = (ip: string) => {
const {
webIp,
webPort,
dnsIp,
dnsPort,
handleFix,
} = this.props;
const web = { const web = {
ip: webIp, ip: watchFields.web?.ip,
port: webPort, port: watchFields.web?.port,
autofix: false, autofix: false,
}; };
const dns = { const dns = {
ip: dnsIp, ip: watchFields.dns?.ip,
port: dnsPort, port: watchFields.dns?.port,
autofix: false, autofix: false,
}; };
const set_static_ip = true; const set_static_ip = true;
if (window.confirm(this.props.t('confirm_static_ip', { ip }))) { if (window.confirm(t('confirm_static_ip', { ip }))) {
handleFix(web, dns, set_static_ip); handleFix(web, dns, set_static_ip);
} }
}; };
render() { const getStaticIpMessage = useCallback((staticIp: StaticIpType) => {
const { const { static: status, ip } = staticIp;
handleSubmit,
handleChange, switch (status) {
case STATUS_RESPONSE.NO:
return (
<>
<div className="mb-2">
<Trans values={{ ip }} components={[<strong key="0">text</strong>]}>
install_static_configure
</Trans>
</div>
webIp, <button
type="button"
className="btn btn-outline-primary btn-sm"
onClick={() => handleStaticIp(ip)}
>
<Trans>set_static_ip</Trans>
</button>
</>
);
case STATUS_RESPONSE.ERROR:
return (
<div className="text-danger">
<Trans>install_static_error</Trans>
</div>
);
case STATUS_RESPONSE.YES:
return (
<div className="text-success">
<Trans>install_static_ok</Trans>
</div>
);
default:
return null;
}
}, [handleStaticIp]);
webPort, const onSubmit = (data: any) => {
validateForm(data);
dnsIp, handleSubmit(data);
};
dnsPort,
interfaces,
invalid,
config,
t,
} = this.props;
const { status: webStatus, can_autofix: isWebFixAvailable } = config.web;
const { status: dnsStatus, can_autofix: isDnsFixAvailable } = config.dns;
const { staticIp } = config;
return ( return (
<form className="setup__step" onSubmit={handleSubmit}> <form className="setup__step" onSubmit={reactHookFormSubmit(onSubmit)}>
<div className="setup__group"> <div className="setup__group">
<div className="setup__subtitle"> <div className="setup__subtitle">
<Trans>install_settings_title</Trans> <Trans>install_settings_title</Trans>
@ -232,17 +229,23 @@ class Settings extends Component<Props> {
<label> <label>
<Trans>install_settings_listen</Trans> <Trans>install_settings_listen</Trans>
</label> </label>
<Controller
<Field
name="web.ip" name="web.ip"
component="select" control={control}
render={({ field }) => (
<select
{...field}
className="form-control custom-select" className="form-control custom-select"
onChange={handleChange}> onChange={(e) => {
field.onChange(e);
}}>
<option value={ALL_INTERFACES_IP}> <option value={ALL_INTERFACES_IP}>
{this.props.t('install_settings_all_interfaces')} {t('install_settings_all_interfaces')}
</option> </option>
{renderInterfaces(interfaces)} {renderInterfaces(interfaces)}
</Field> </select>
)}
/>
</div> </div>
</div> </div>
@ -251,17 +254,33 @@ class Settings extends Component<Props> {
<label> <label>
<Trans>install_settings_port</Trans> <Trans>install_settings_port</Trans>
</label> </label>
<Controller
<Field
name="web.port" name="web.port"
component={renderInputField} control={control}
rules={{
required: t('form_error_required'),
validate: {
installPort: validateInstallPort,
},
}}
render={({ field }) => (
<input
{...field}
type="number" type="number"
className="form-control" className="form-control"
placeholder={STANDARD_WEB_PORT.toString()} placeholder={STANDARD_WEB_PORT.toString()}
validate={[validateInstallPort, validateRequiredValue]} onChange={(e) => {
normalize={toNumber} const val = toNumber(e.target.value);
onChange={handleChange} field.onChange(val);
}}
/> />
)}
/>
{errors.web?.port && (
<div className="text-danger">
{errors.web.port.message}
</div>
)}
</div> </div>
</div> </div>
@ -273,7 +292,8 @@ class Settings extends Component<Props> {
<button <button
type="button" type="button"
className="btn btn-secondary btn-sm ml-2" className="btn btn-secondary btn-sm ml-2"
onClick={() => this.handleAutofix('web')}> onClick={() => handleAutofix('web')}
>
<Trans>fix</Trans> <Trans>fix</Trans>
</button> </button>
)} )}
@ -288,7 +308,11 @@ class Settings extends Component<Props> {
<Trans>install_settings_interface_link</Trans> <Trans>install_settings_interface_link</Trans>
<div className="mt-1"> <div className="mt-1">
<AddressList interfaces={interfaces} address={webIp} port={webPort} /> <AddressList
interfaces={interfaces}
address={watchFields.web?.ip}
port={watchFields.web?.port}
/>
</div> </div>
</div> </div>
</div> </div>
@ -304,15 +328,23 @@ class Settings extends Component<Props> {
<label> <label>
<Trans>install_settings_listen</Trans> <Trans>install_settings_listen</Trans>
</label> </label>
<Controller
<Field
name="dns.ip" name="dns.ip"
component="select" control={control}
render={({ field }) => (
<select
{...field}
className="form-control custom-select" className="form-control custom-select"
onChange={handleChange}> onChange={(e) => {
<option value={ALL_INTERFACES_IP}>{t('install_settings_all_interfaces')}</option> field.onChange(e);
}}>
<option value={ALL_INTERFACES_IP}>
{t('install_settings_all_interfaces')}
</option>
{renderInterfaces(interfaces)} {renderInterfaces(interfaces)}
</Field> </select>
)}
/>
</div> </div>
</div> </div>
@ -321,17 +353,34 @@ class Settings extends Component<Props> {
<label> <label>
<Trans>install_settings_port</Trans> <Trans>install_settings_port</Trans>
</label> </label>
<Controller
<Field
name="dns.port" name="dns.port"
component={renderInputField} control={control}
rules={{
required: t('form_error_required'),
validate: {
required: validateRequiredValue,
installPort: validateInstallPort,
},
}}
render={({ field }) => (
<input
{...field}
type="number" type="number"
className="form-control" className="form-control"
placeholder={STANDARD_WEB_PORT.toString()} placeholder={STANDARD_WEB_PORT.toString()}
validate={[validateInstallPort, validateRequiredValue]} onChange={(e) => {
normalize={toNumber} const val = toNumber(e.target.value);
onChange={handleChange} field.onChange(val);
}}
/> />
)}
/>
{errors.dns?.port.message && (
<div className="text-danger">
{t(errors.dns.port.message)}
</div>
)}
</div> </div>
</div> </div>
@ -344,7 +393,7 @@ class Settings extends Component<Props> {
<button <button
type="button" type="button"
className="btn btn-secondary btn-sm ml-2" className="btn btn-secondary btn-sm ml-2"
onClick={() => this.handleAutofix('dns')}> onClick={() => handleAutofix('dns')}>
<Trans>fix</Trans> <Trans>fix</Trans>
</button> </button>
)} )}
@ -354,9 +403,7 @@ class Settings extends Component<Props> {
<p className="mb-1"> <p className="mb-1">
<Trans>autofix_warning_text</Trans> <Trans>autofix_warning_text</Trans>
</p> </p>
<Trans components={[<li key="0">text</li>]}>autofix_warning_list</Trans> <Trans components={[<li key="0">text</li>]}>autofix_warning_list</Trans>
<p className="mb-1"> <p className="mb-1">
<Trans>autofix_warning_result</Trans> <Trans>autofix_warning_result</Trans>
</p> </p>
@ -364,19 +411,21 @@ class Settings extends Component<Props> {
)} )}
</> </>
)} )}
{dnsPort === STANDARD_DNS_PORT && {watchFields.dns?.port === STANDARD_DNS_PORT &&
!isDnsFixAvailable && !isDnsFixAvailable &&
dnsStatus.includes(ADDRESS_IN_USE_TEXT) && ( dnsStatus?.includes(ADDRESS_IN_USE_TEXT) && (
<Trans <Trans
components={[ components={[
<a <a
href={PORT_53_FAQ_LINK} href={PORT_53_FAQ_LINK}
key="0" key="0"
target="_blank" target="_blank"
rel="noopener noreferrer"> rel="noopener noreferrer"
>
link link
</a>, </a>,
]}> ]}
>
port_53_faq_link port_53_faq_link
</Trans> </Trans>
)} )}
@ -389,7 +438,12 @@ class Settings extends Component<Props> {
<Trans>install_settings_dns_desc</Trans> <Trans>install_settings_dns_desc</Trans>
<div className="mt-1"> <div className="mt-1">
<AddressList interfaces={interfaces} address={dnsIp} port={dnsPort} isDns={true} /> <AddressList
interfaces={interfaces}
address={watchFields.dns?.ip}
port={watchFields.dns?.port}
isDns={true}
/>
</div> </div>
</div> </div>
</div> </div>
@ -403,36 +457,12 @@ class Settings extends Component<Props> {
<Trans>static_ip_desc</Trans> <Trans>static_ip_desc</Trans>
</div> </div>
{this.getStaticIpMessage(staticIp)} {getStaticIpMessage(staticIp)}
</div> </div>
<Controls invalid={invalid} /> <Controls invalid={!isValid} />
</form> </form>
); );
}
}
const selector = formValueSelector(FORM_NAME.INSTALL);
const SettingsForm = connect((state) => {
const webIp = selector(state, 'web.ip');
const webPort = selector(state, 'web.port');
const dnsIp = selector(state, 'dns.ip');
const dnsPort = selector(state, 'dns.port');
return {
webIp,
webPort,
dnsIp,
dnsPort,
}; };
})(Settings);
export default flow([ export default Settings;
withTranslation(),
reduxForm({
form: FORM_NAME.INSTALL,
destroyOnUnmount: false,
forceUnregisterOnUnmount: true,
}),
])(SettingsForm);

View file

@ -1,101 +1,77 @@
import React, { Component, Fragment } from 'react'; import React, { useEffect, Fragment } from 'react';
import { connect } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import debounce from 'lodash/debounce'; import debounce from 'lodash/debounce';
import * as actionCreators from '../../actions/install'; import * as actionCreators from '../../actions/install';
import { getWebAddress } from '../../helpers/helpers'; import { getWebAddress } from '../../helpers/helpers';
import { INSTALL_FIRST_STEP, INSTALL_TOTAL_STEPS, ALL_INTERFACES_IP, DEBOUNCE_TIMEOUT } from '../../helpers/constants'; import { INSTALL_TOTAL_STEPS, ALL_INTERFACES_IP, DEBOUNCE_TIMEOUT } from '../../helpers/constants';
import Loading from '../../components/ui/Loading'; import Loading from '../../components/ui/Loading';
import Greeting from './Greeting'; import Greeting from './Greeting';
import Settings from './Settings'; import Settings from './Settings';
import Auth from './Auth';
import Devices from './Devices'; import Devices from './Devices';
import Submit from './Submit'; import Submit from './Submit';
import Progress from './Progress'; import Progress from './Progress';
import Toasts from '../../components/Toasts'; import Toasts from '../../components/Toasts';
import Footer from '../../components/ui/Footer'; import Footer from '../../components/ui/Footer';
import Icons from '../../components/ui/Icons'; import Icons from '../../components/ui/Icons';
import { Logo } from '../../components/ui/svg/logo'; import { Logo } from '../../components/ui/svg/logo';
import './Setup.css'; import './Setup.css';
import '../../components/ui/Tabler.css'; import '../../components/ui/Tabler.css';
import Auth from './Auth';
interface SetupProps { const Setup = () => {
getDefaultAddresses: (...args: unknown[]) => unknown; const dispatch = useDispatch();
setAllSettings: (...args: unknown[]) => unknown;
checkConfig: (...args: unknown[]) => unknown; const install = useSelector((state: any) => state.install);
nextStep: (...args: unknown[]) => unknown; const { processingDefault, step, web, dns, staticIp, interfaces } = install;
prevStep: (...args: unknown[]) => unknown;
install: { useEffect(() => {
step: number; dispatch(actionCreators.getDefaultAddresses());
processingDefault: boolean; }, []);
web;
dns; const handleFormSubmit = (values: any) => {
staticIp; const config = { ...values };
interfaces; delete config.staticIp;
};
step?: number; if (web.port && dns.port) {
web?: object; dispatch(actionCreators.setAllSettings({
dns?: object; web,
dns,
...config,
}));
} }
class Setup extends Component<SetupProps> {
componentDidMount() {
this.props.getDefaultAddresses();
}
handleFormSubmit = (values: any) => {
const { staticIp, ...config } = values;
this.props.setAllSettings(config);
}; };
handleFormChange = debounce((values) => { const checkConfig = debounce((values) => {
const { web, dns } = values; const { web, dns } = values;
if (values && web.port && dns.port) { if (values && web.port && dns.port) {
this.props.checkConfig({ web, dns, set_static_ip: false }); dispatch(actionCreators.checkConfig({ web, dns, set_static_ip: false }));
} }
}, DEBOUNCE_TIMEOUT); }, DEBOUNCE_TIMEOUT);
handleFix = (web: any, dns: any, set_static_ip: any) => { const handleFix = (web: any, dns: any, set_static_ip: any) => {
this.props.checkConfig({ web, dns, set_static_ip }); dispatch(actionCreators.checkConfig({ web, dns, set_static_ip }));
}; };
openDashboard = (ip: any, port: any) => { const openDashboard = (ip: any, port: any) => {
let address = getWebAddress(ip, port); let address = getWebAddress(ip, port);
if (ip === ALL_INTERFACES_IP) { if (ip === ALL_INTERFACES_IP) {
address = getWebAddress(window.location.hostname, port); address = getWebAddress(window.location.hostname, port);
} }
window.location.replace(address); window.location.replace(address);
}; };
nextStep = () => { const handleNextStep = () => {
if (this.props.install.step < INSTALL_TOTAL_STEPS) { if (step < INSTALL_TOTAL_STEPS) {
this.props.nextStep(); dispatch(actionCreators.nextStep());
} }
}; };
prevStep = () => { const renderPage = (step: any, config: any, interfaces: any) => {
if (this.props.install.step > INSTALL_FIRST_STEP) {
this.props.prevStep();
}
};
renderPage(step: any, config: any, interfaces: any) {
switch (step) { switch (step) {
case 1: case 1:
return <Greeting />; return <Greeting />;
@ -105,35 +81,32 @@ class Setup extends Component<SetupProps> {
config={config} config={config}
initialValues={config} initialValues={config}
interfaces={interfaces} interfaces={interfaces}
onSubmit={this.nextStep} handleSubmit={handleNextStep}
onChange={this.handleFormChange} validateForm={checkConfig}
validateForm={this.handleFormChange} handleFix={handleFix}
handleFix={this.handleFix}
/> />
); );
case 3: case 3:
return <Auth onSubmit={this.handleFormSubmit} />; return <Auth onAuthSubmit={handleFormSubmit} />;
case 4: case 4:
return <Devices interfaces={interfaces} />; return <Devices interfaces={interfaces} />;
case 5: case 5:
return <Submit openDashboard={this.openDashboard} />; return <Submit openDashboard={openDashboard} />;
default: default:
return false; return false;
} }
};
if (processingDefault) {
return <Loading />;
} }
render() {
const { processingDefault, step, web, dns, staticIp, interfaces } = this.props.install;
return ( return (
<Fragment> <>
{processingDefault && <Loading />}
{!processingDefault && (
<Fragment>
<div className="setup"> <div className="setup">
<div className="setup__container"> <div className="setup__container">
<Logo className="setup__logo" /> <Logo className="setup__logo" />
{this.renderPage(step, { web, dns, staticIp }, interfaces)} {renderPage(step, { web, dns, staticIp }, interfaces)}
<Progress step={step} /> <Progress step={step} />
</div> </div>
</div> </div>
@ -143,17 +116,8 @@ class Setup extends Component<SetupProps> {
<Toasts /> <Toasts />
<Icons /> <Icons />
</Fragment> </>
)}
</Fragment>
); );
}
}
const mapStateToProps = (state: any) => {
const { install, toasts } = state;
const props = { install, toasts };
return props;
}; };
export default connect(mapStateToProps, actionCreators)(Setup); export default Setup;

View file

@ -10,15 +10,15 @@ import { ALL_INTERFACES_IP, INSTALL_FIRST_STEP, STANDARD_DNS_PORT, STANDARD_WEB_
const install = handleActions( const install = handleActions(
{ {
[actions.getDefaultAddressesRequest.toString().toString()]: (state: any) => ({ [actions.getDefaultAddressesRequest.toString()]: (state: any) => ({
...state, ...state,
processingDefault: true, processingDefault: true,
}), }),
[actions.getDefaultAddressesFailure.toString().toString()]: (state: any) => ({ [actions.getDefaultAddressesFailure.toString()]: (state: any) => ({
...state, ...state,
processingDefault: false, processingDefault: false,
}), }),
[actions.getDefaultAddressesSuccess.toString().toString()]: (state: any, { payload }: any) => { [actions.getDefaultAddressesSuccess.toString()]: (state: any, { payload }: any) => {
const { interfaces, version } = payload; const { interfaces, version } = payload;
const web = { ...state.web, port: payload.web_port }; const web = { ...state.web, port: payload.web_port };
const dns = { ...state.dns, port: payload.dns_port }; const dns = { ...state.dns, port: payload.dns_port };
@ -35,37 +35,37 @@ const install = handleActions(
return newState; return newState;
}, },
[actions.nextStep.toString().toString()]: (state: any) => ({ [actions.nextStep.toString()]: (state: any) => ({
...state, ...state,
step: state.step + 1, step: state.step + 1,
}), }),
[actions.prevStep.toString().toString()]: (state: any) => ({ [actions.prevStep.toString()]: (state: any) => ({
...state, ...state,
step: state.step - 1, step: state.step - 1,
}), }),
[actions.setAllSettingsRequest.toString().toString()]: (state: any) => ({ [actions.setAllSettingsRequest.toString()]: (state: any) => ({
...state, ...state,
processingSubmit: true, processingSubmit: true,
}), }),
[actions.setAllSettingsFailure.toString().toString()]: (state: any) => ({ [actions.setAllSettingsFailure.toString()]: (state: any) => ({
...state, ...state,
processingSubmit: false, processingSubmit: false,
}), }),
[actions.setAllSettingsSuccess.toString().toString()]: (state: any) => ({ [actions.setAllSettingsSuccess.toString()]: (state: any) => ({
...state, ...state,
processingSubmit: false, processingSubmit: false,
}), }),
[actions.checkConfigRequest.toString().toString()]: (state: any) => ({ [actions.checkConfigRequest.toString()]: (state: any) => ({
...state, ...state,
processingCheck: true, processingCheck: true,
}), }),
[actions.checkConfigFailure.toString().toString()]: (state: any) => ({ [actions.checkConfigFailure.toString()]: (state: any) => ({
...state, ...state,
processingCheck: false, processingCheck: false,
}), }),
[actions.checkConfigSuccess.toString().toString()]: (state: any, { payload }: any) => { [actions.checkConfigSuccess.toString()]: (state: any, { payload }: any) => {
const web = { ...state.web, ...payload.web }; const web = { ...state.web, ...payload.web };
const dns = { ...state.dns, ...payload.dns }; const dns = { ...state.dns, ...payload.dns };
const staticIp = { ...state.staticIp, ...payload.static_ip }; const staticIp = { ...state.staticIp, ...payload.static_ip };