Migration: remove all class component

This commit is contained in:
Dreamacro 2019-07-03 22:32:19 +08:00
parent 3d16e6e893
commit 541d36a8e2
22 changed files with 683 additions and 1380 deletions

View File

@ -17,6 +17,11 @@ module.exports = merge(commonConfig, {
hot: true, // enable HMR on the server hot: true, // enable HMR on the server
noInfo: true, noInfo: true,
}, },
resolve: {
alias: {
'react-dom': '@hot-loader/react-dom'
}
},
devtool: 'cheap-module-eval-source-map', devtool: 'cheap-module-eval-source-map',
plugins: [ plugins: [
new webpack.HotModuleReplacementPlugin(), // enable HMR globally new webpack.HotModuleReplacementPlugin(), // enable HMR globally

429
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -32,11 +32,11 @@
"@babel/core": "^7.4.5", "@babel/core": "^7.4.5",
"@babel/preset-env": "^7.4.5", "@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0", "@babel/preset-react": "^7.0.0",
"@hot-loader/react-dom": "^16.8.6",
"@types/classnames": "^2.2.8", "@types/classnames": "^2.2.8",
"@types/node": "^12.0.10", "@types/node": "^12.0.10",
"@types/react": "^16.8.22", "@types/react": "^16.8.22",
"@types/react-dom": "^16.8.4", "@types/react-dom": "^16.8.4",
"@types/react-i18next": "^8.1.0",
"@types/react-router-dom": "^4.3.4", "@types/react-router-dom": "^4.3.4",
"@types/react-sortable-hoc": "^0.6.5", "@types/react-sortable-hoc": "^0.6.5",
"@types/react-virtualized": "^9.21.2", "@types/react-virtualized": "^9.21.2",
@ -53,13 +53,14 @@
"offline-plugin": "^5.0.7", "offline-plugin": "^5.0.7",
"postcss-loader": "^3.0.0", "postcss-loader": "^3.0.0",
"react-addons-test-utils": "^15.6.2", "react-addons-test-utils": "^15.6.2",
"react-hot-loader": "^4.12.0", "react-hot-loader": "^4.12.1",
"sass": "^1.22.2", "sass": "^1.22.2",
"sass-loader": "^7.1.0", "sass-loader": "^7.1.0",
"style-loader": "^0.23.1", "style-loader": "^0.23.1",
"stylelint": "^10.1.0", "stylelint": "^10.1.0",
"stylelint-config-standard": "^18.3.0", "stylelint-config-standard": "^18.3.0",
"stylelint-webpack-plugin": "^0.10.5", "stylelint-webpack-plugin": "^0.10.5",
"terser-webpack-plugin": "^1.3.0",
"tslint": "^5.18.0", "tslint": "^5.18.0",
"tslint-config-standard": "^8.0.1", "tslint-config-standard": "^8.0.1",
"tslint-loader": "^3.6.0", "tslint-loader": "^3.6.0",
@ -78,16 +79,12 @@
"i18next": "^17.0.6", "i18next": "^17.0.6",
"i18next-browser-languagedetector": "^3.0.1", "i18next-browser-languagedetector": "^3.0.1",
"immer": "^3.1.3", "immer": "^3.1.3",
"mobx": "^5.10.1",
"mobx-react": "^6.1.1",
"mobx-react-router": "^4.0.7",
"react": "^16.8.6", "react": "^16.8.6",
"react-dom": "^16.8.6", "react-dom": "^16.8.6",
"react-i18next": "^10.11.2", "react-i18next": "^10.11.2",
"react-router-dom": "^5.0.1", "react-router-dom": "^5.0.1",
"react-sortable-hoc": "^1.9.1", "react-sortable-hoc": "^1.9.1",
"react-virtualized": "^9.21.1", "react-virtualized": "^9.21.1",
"terser-webpack-plugin": "^1.3.0",
"typescript": "^3.5.2", "typescript": "^3.5.2",
"unstated-next": "^1.1.0", "unstated-next": "^1.1.0",
"use-immer": "^0.3.2", "use-immer": "^0.3.2",

View File

@ -1,6 +1,6 @@
import * as React from 'react' import React, { useEffect } from 'react'
import { Route, Redirect } from 'react-router-dom' import { Route, Redirect } from 'react-router-dom'
import { hot } from 'react-hot-loader' import { hot } from 'react-hot-loader/root'
import classnames from 'classnames' import classnames from 'classnames'
import { I18nProps } from '@models' import { I18nProps } from '@models'
import { isClashX } from '@lib/jsBridge' import { isClashX } from '@lib/jsBridge'
@ -18,33 +18,33 @@ import { getLogsStreamReader } from '@lib/request'
export interface AppProps extends I18nProps { export interface AppProps extends I18nProps {
} }
@hot(module) function App () {
export default class App extends React.Component<AppProps, {}> { useEffect(() => {
componentDidMount () {
getLogsStreamReader() getLogsStreamReader()
} }, [])
render () {
const routes = [
// { path: '/', name: 'Overview', component: Overview, exact: true },
{ path: '/proxies', name: 'Proxies', component: Proxies },
{ path: '/logs', name: 'Logs', component: Logs },
{ path: '/rules', name: 'Rules', component: Rules, noMobile: true },
{ path: '/settings', name: 'Settings', component: Settings }
]
return ( const routes = [
<div className={classnames('app', { 'not-clashx': !isClashX() })}> // { path: '/', name: 'Overview', component: Overview, exact: true },
<SlideBar routes={routes} /> { path: '/proxies', name: 'Proxies', component: Proxies },
<div className="page-container"> { path: '/logs', name: 'Logs', component: Logs },
<Route exact path="/" component={() => <Redirect to="/proxies"/>}/> { path: '/rules', name: 'Rules', component: Rules, noMobile: true },
{ { path: '/settings', name: 'Settings', component: Settings }
routes.map( ]
route => <Route exact={false} path={route.path} key={route.path} component={route.component}/>
) return (
} <div className={classnames('app', { 'not-clashx': !isClashX() })}>
</div> <SlideBar routes={routes} />
<ExternalControllerModal /> <div className="page-container">
<Route exact path="/" component={() => <Redirect to="/proxies"/>}/>
{
routes.map(
route => <Route exact={false} path={route.path} key={route.path} component={route.component}/>
)
}
</div> </div>
) <ExternalControllerModal />
} </div>
)
} }
export default hot(App)

View File

@ -1,96 +1,77 @@
import * as React from 'react' import React, { useEffect } from 'react'
import { withTranslation, WithTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { inject, observer } from 'mobx-react' import { useObject } from '@lib/hook'
import { storeKeys } from '@lib/createStore'
import { Modal, Input, Row, Col, Alert } from '@components' import { Modal, Input, Row, Col, Alert } from '@components'
import { BaseProps } from '@models' import { APIInfo, ExternalControllerModal } from '@stores'
import './style.scss' import './style.scss'
interface ExternalControllerModalProps extends BaseProps, WithTranslation {} export default function ExternalController () {
const { t } = useTranslation(['Settings'])
interface ExternalControllerModalState { const { data: info, update, fetch } = APIInfo.useContainer()
hostname: string const { hidden, visible } = ExternalControllerModal.useContainer()
port: string const { value, set, change } = useObject({
secret: string
}
@inject(...storeKeys)
@observer
class ExternalController extends React.Component<ExternalControllerModalProps, ExternalControllerModalState> {
state = {
hostname: '', hostname: '',
port: '', port: '',
secret: '' secret: ''
})
useEffect(() => {
fetch()
}, [])
useEffect(() => {
set({ hostname: info.hostname, port: info.port, secret: info.secret })
}, [info])
function handleOk () {
const { hostname, port, secret } = value
update({ hostname, port, secret })
} }
private handleOk = () => { return (
const { hostname, port, secret } = this.state <Modal
this.props.store.updateAPIInfo({ hostname, port, secret }) show={visible}
} title={t('externalControllerSetting.title')}
bodyClassName="external-controller"
private handleCancel = () => { onClose={hidden}
this.props.store.setShowAPIModal(false) onOk={handleOk}
} >
<Alert type="info" inside={true}>
async componentWillMount () { <p>{t('externalControllerSetting.note')}</p>
await this.props.store.fetchAPIInfo() </Alert>
const info = this.props.store.apiInfo <Row gutter={24} align="middle">
this.setState({ hostname: info.hostname, port: info.port, secret: info.secret }) <Col span={4} className="title">{t('externalControllerSetting.host')}</Col>
} <Col span={20} className="form">
<Input
render () { align="left"
const { t } = this.props inside={true}
const { hostname, port, secret } = this.state value={value.hostname}
const show = this.props.store.showAPIModal onChange={hostname => change('hostname', hostname)}
/>
return ( </Col>
<Modal </Row>
show={show} <Row gutter={24} align="middle">
title={t('externalControllerSetting.title')} <Col span={4} className="title">{t('externalControllerSetting.port')}</Col>
bodyClassName="external-controller" <Col span={20} className="form">
onClose={this.handleCancel} <Input
onOk={this.handleOk} align="left"
> inside={true}
<Alert type="info" inside={true}> value={value.port}
<p>{t('externalControllerSetting.note')}</p> onChange={port => change('port', port)}
</Alert> />
<Row gutter={24} align="middle"> </Col>
<Col span={4} className="title">{t('externalControllerSetting.host')}</Col> </Row>
<Col span={20} className="form"> <Row gutter={24} align="middle">
<Input <Col span={4} className="title">{t('externalControllerSetting.secret')}</Col>
align="left" <Col span={20} className="form">
inside={true} <Input
value={hostname} align="left"
onChange={hostname => this.setState({ hostname })} inside={true}
/> value={value.secret}
</Col> onChange={secret => change('secret', secret)}
</Row> />
<Row gutter={24} align="middle"> </Col>
<Col span={4} className="title">{t('externalControllerSetting.port')}</Col> </Row>
<Col span={20} className="form"> </Modal>
<Input )
align="left"
inside={true}
value={port}
onChange={port => this.setState({ port })}
/>
</Col>
</Row>
<Row gutter={24} align="middle">
<Col span={4} className="title">{t('externalControllerSetting.secret')}</Col>
<Col span={20} className="form">
<Input
align="left"
inside={true}
value={secret}
onChange={secret => this.setState({ secret })}
/>
</Col>
</Row>
</Modal>
)
}
} }
export default withTranslation(['Settings'])(ExternalController)

View File

@ -1,23 +1,21 @@
import * as React from 'react' import * as React from 'react'
const logo = require('@assets/LOGO-fixing.svg') const logo = require('@assets/LOGO-fixing.svg')
export default class Overview extends React.Component<{}, {}> { export default function Overview () {
render () { return (
return ( <div style={{
<div style={{ height: '90vh',
height: '90vh', display: 'flex',
display: 'flex', alignItems: 'center',
alignItems: 'center', justifyContent: 'center',
justifyContent: 'center', flexDirection: 'column',
flexDirection: 'column', opacity: 0.3
opacity: 0.3 }}>
}}> <img src={logo} alt="Logo" style={{
<img src={logo} alt="Logo" style={{ width: 200
width: 200 }}/>
}}/>
<h1 style={{ color: '#54759A', marginTop: 20 }}>Coming Soon...</h1> <h1 style={{ color: '#54759A', marginTop: 20 }}>Coming Soon...</h1>
</div> </div>
) )
}
} }

View File

@ -1,43 +1,38 @@
import * as React from 'react' import * as React from 'react'
import { inject } from 'mobx-react' import { Data } from '@stores'
import { BaseComponentProps } from '@models'
import { ConfigStore } from '@stores'
import { changeProxySelected, Group as IGroup } from '@lib/request' import { changeProxySelected, Group as IGroup } from '@lib/request'
import { storeKeys } from '@lib/createStore'
import { Tags } from '@components' import { Tags } from '@components'
import './style.scss' import './style.scss'
interface GroupProps extends BaseComponentProps { interface GroupProps {
config: IGroup config: IGroup
store?: ConfigStore
} }
@inject(...storeKeys) export function Group (props: GroupProps) {
export class Group extends React.Component<GroupProps, {}> { const { fetch } = Data.useContainer()
handleChangeProxySelected = async (name: string) => { const { config } = props
await changeProxySelected(this.props.config.name, name)
await this.props.store.fetchData() async function handleChangeProxySelected (name: string) {
await changeProxySelected(props.config.name, name)
await fetch()
} }
render () { const canClick = config.type === 'Selector'
const { config } = this.props return (
const canClick = config.type === 'Selector' <div className="proxy-group">
return ( <div className="proxy-group-part">
<div className="proxy-group"> <span className="proxy-group-name">{ config.name }</span>
<div className="proxy-group-part"> <span className="proxy-group-type">{ config.type }</span>
<span className="proxy-group-name">{ config.name }</span>
<span className="proxy-group-type">{ config.type }</span>
</div>
<div className="proxy-group-tags-container">
<Tags
className="proxy-group-tags"
data={config.all}
onClick={this.handleChangeProxySelected}
select={config.now}
canClick={canClick}
rowHeight={30} />
</div>
</div> </div>
) <div className="proxy-group-tags-container">
} <Tags
className="proxy-group-tags"
data={config.all}
onClick={handleChangeProxySelected}
select={config.now}
canClick={canClick}
rowHeight={30} />
</div>
</div>
)
} }

View File

@ -1,144 +0,0 @@
import * as React from 'react'
import classnames from 'classnames'
import { Row, Col, Input, Icon, Select, Option, Switch } from '@components'
import { noop } from '@lib/helper'
// type selector
export function ProxyTypeSelector ({ types, label, value, onSelect = noop }: {
types: { [key: string]: string },
label: string,
value: string,
onSelect?: (type: string) => void
}) {
return (
<Row gutter={24} className="proxy-editor-row">
<Col span={6} className="proxy-editor-label">{label}</Col>
<Col span={18}>
<Select value={value} onSelect={onSelect}>
{
Object.keys(types)
.map(typeName => {
const type = types[typeName]
return (
<Option value={type} key={type}>{typeName}</Option>
)
})
}
</Select>
</Col>
</Row>
)
}
// color selector
export function ProxyColorSelector ({ colors, value, onSelect = noop }: {
colors: string[],
value: string,
onSelect?: (color: string) => void
}) {
return (
<Row gutter={24} style={{ padding: '12px 0' }}>
<div className="proxy-editor-color-selector">
{
colors.map(color => (
<span
className={classnames('color-item', {
'color-item-active': value === color
})}
key={color}
style={{ background: color }}
onClick={() => onSelect(color)}
/>
))
}
</div>
</Row>
)
}
// input form
export function ProxyInputForm ({ label, value, onChange = noop }: {
label: string,
value: string,
onChange?: (value: string) => void
}) {
return (
<Row gutter={24} className="proxy-editor-row">
<Col span={6} className="proxy-editor-label">{label}</Col>
<Col span={18}>
<Input value={value} onChange={onChange} align="left"/>
</Col>
</Row>
)
}
// switch form
export function ProxySwitch ({ label, value, onChange = noop }: {
label: string,
value: boolean,
onChange?: (value: boolean) => void
}) {
return (
<Row gutter={24} align="middle" className="proxy-editor-row">
<Col span={6} className="proxy-editor-label">{label}</Col>
<Col span={18}>
<Switch checked={value} onChange={onChange} />
</Col>
</Row>
)
}
// password form
export class ProxyPasswordForm extends React.Component<{
label: string,
value: string,
onChange?: (value: string) => void
}, { showPassword: boolean }> {
state = {
showPassword: false
}
render () {
const { label, value, onChange } = this.props
const { showPassword } = this.state
const type = showPassword ? 'text' : 'password'
return (
<Row gutter={24} className="proxy-editor-row">
<Col span={6} className="proxy-editor-label">{label}</Col>
<Col span={18} className="proxy-editor-value">
<Input style={{ paddingRight: '32px' }} type={type} value={value} onChange={onChange} align="left" />
<Icon
className="proxy-editor-passsword-icon"
type={showPassword ? 'hide' : 'show'}
size={20}
onClick={() => this.setState({ showPassword: !showPassword })}
/>
</Col>
</Row>
)
}
}
// cipher selector
export function ProxyCipherSelector ({ ciphers, label, value, onSelect = noop }: {
ciphers: string[],
label: string,
value: string,
onSelect?: (type: string) => void
}) {
return (
<Row gutter={24} className="proxy-editor-row">
<Col span={6} className="proxy-editor-label">{label}</Col>
<Col span={18}>
<Select value={value} onSelect={onSelect}>
{
ciphers.map(cipher => (
<Option value={cipher} key={cipher}>{cipher}</Option>
))
}
</Select>
</Col>
</Row>
)
}

View File

@ -1,224 +0,0 @@
import * as React from 'react'
import { withTranslation, WithTranslation } from 'react-i18next'
import { Modal } from '@components'
import { getLocalStorageItem, setLocalStorageItem } from '@lib/helper'
import './style.scss'
import {
BaseComponentProps,
Proxy as IProxy,
SsProxyConfigList, VmessProxyConfigList, Socks5ProxyConfigList,
TagColors,
ProxyType,
SsCipher, VmessCipher, pickCipherWithAlias
} from '@models'
import {
ProxyInputForm,
ProxySwitch,
ProxyColorSelector,
ProxyTypeSelector,
ProxyPasswordForm,
ProxyCipherSelector
} from './FormItems'
interface ModifyProxyDialogProps extends BaseComponentProps, WithTranslation {
config: IProxy
onOk?: (config: IProxy) => void
onCancel?: () => void
}
interface ModifyProxyDialogState {
config: IProxy
currentColor: string
}
class RawDialog extends React.Component<ModifyProxyDialogProps, ModifyProxyDialogState> {
constructor (props: ModifyProxyDialogProps) {
super(props)
this.state = {
config: props.config,
currentColor: getLocalStorageItem(props.config.name)
}
}
componentDidMount () {
console.log(this.props.config)
}
handleOk = () => {
const { onOk } = this.props
const { config, currentColor } = this.state
setLocalStorageItem(config.name, currentColor)
onOk(config)
}
handleConfigChange = (key: string, value: any) => {
console.log(key, value)
const { config } = this.state
this.setState({ config: { ...config, [key]: value } })
}
getCipherFromType (type) {
switch (type) {
case 'ss':
return SsCipher
case 'vmess':
return VmessCipher
default:
return []
}
}
getConfigListFromType (type) {
switch (type) {
case 'ss':
return SsProxyConfigList
case 'vmess':
return VmessProxyConfigList
case 'socks5':
return Socks5ProxyConfigList
default:
return []
}
}
renderFormItem (key) {
const { t } = this.props
const { config } = this.state
switch (key) {
case 'type':
return (
<ProxyTypeSelector
key={key}
types={ProxyType}
label={t('editDialog.type')}
value={config.type}
onSelect={value => this.handleConfigChange('type', value)}
/>
)
case 'name':
return (
<ProxyInputForm
key={key}
label={t('editDialog.name')}
value={config.name}
onChange={value => this.handleConfigChange('name', value)}
/>
)
case 'server':
return (
<ProxyInputForm
key={key}
label={t('editDialog.server')}
value={config.server}
onChange={value => this.handleConfigChange('server', value)}
/>
)
case 'port':
return (
<ProxyInputForm
key={key}
label={t('editDialog.port')}
value={config.port ? config.port.toString() : ''}
onChange={value => this.handleConfigChange('port', +value)}
/>
)
case 'password':
return (
<ProxyPasswordForm
key={key}
label={t('editDialog.password')}
value={config.password}
onChange={value => this.handleConfigChange('password', value)}
/>
)
case 'cipher':
return (
<ProxyCipherSelector
key={key}
ciphers={this.getCipherFromType(config.type)}
label={t('editDialog.cipher')}
value={pickCipherWithAlias(config.cipher)}
onSelect={value => this.handleConfigChange('cipher', value)}
/>
)
case 'obfs':
return (
<ProxyInputForm
key={key}
label={t('editDialog.obfs')}
value={config.obfs}
onChange={value => this.handleConfigChange('obfs', value)}
/>
)
case 'obfs-host':
return (
<ProxyInputForm
key={key}
label={t('editDialog.obfs-host')}
value={config['obfs-host']}
onChange={value => this.handleConfigChange('obfs-host', value)}
/>
)
case 'uuid':
return (
<ProxyPasswordForm
key={key}
label={t('editDialog.uuid')}
value={config.uuid}
onChange={value => this.handleConfigChange('uuid', value)}
/>
)
case 'alterId':
return (
<ProxyInputForm
key={key}
label={t('editDialog.alterId')}
value={config.alterId ? config.alterId.toString() : ''}
onChange={value => this.handleConfigChange('alterId', +value)}
/>
)
case 'tls':
return (
<ProxySwitch
key={key}
label={t('editDialog.tls')}
value={!!config.tls}
onChange={value => this.handleConfigChange('tls', !!value)}
/>
)
default:
return null
}
}
render () {
const { onCancel, t } = this.props
const { currentColor, config } = this.state
const { type } = config
const configList = this.getConfigListFromType(type)
return <Modal
className="proxy-editor"
title={t('editDialog.title')}
onOk={this.handleOk}
onClose={onCancel}
>
<ProxyColorSelector
colors={TagColors}
value={currentColor}
onSelect={color => this.setState({ currentColor: color })}
/>
{
configList.map(c => this.renderFormItem(c))
}
</Modal>
}
}
export const ModifyProxyDialog = withTranslation(['Proxies'])(RawDialog)

View File

@ -1,51 +0,0 @@
@import '~@styles/variables';
.proxy-editor {
.proxy-editor-row {
padding: 5px 0;
.proxy-editor-label {
padding-left: 0;
line-height: 30px;
}
.proxy-editor-value {
position: relative;
.proxy-editor-passsword-icon {
position: absolute;
right: 15px;
top: 4px;
cursor: pointer;
color: $color-primary-darken;
user-select: none;
}
}
}
.proxy-editor-color-selector {
display: flex;
align-items: center;
.color-item {
position: relative;
margin-right: 20px;
width: 16px;
height: 16px;
border-radius: 50%;
cursor: pointer;
}
.color-item-active::after {
position: absolute;
left: -3px;
top: -3px;
content: '';
display: block;
width: 22px;
height: 22px;
border-radius: 50%;
border: 1px solid $color-gray-dark;
}
}
}

View File

@ -1,4 +1,4 @@
import * as React from 'react' import React, { useState, useMemo, useLayoutEffect, useEffect } from 'react'
import classnames from 'classnames' import classnames from 'classnames'
import { BaseComponentProps, TagColors } from '@models' import { BaseComponentProps, TagColors } from '@models'
import { getProxyDelay, Proxy as IProxy } from '@lib/request' import { getProxyDelay, Proxy as IProxy } from '@lib/request'
@ -9,82 +9,54 @@ import './style.scss'
interface ProxyProps extends BaseComponentProps { interface ProxyProps extends BaseComponentProps {
config: IProxy config: IProxy
// onEdit?: (e: React.MouseEvent<HTMLElement>) => void
} }
interface ProxyState { async function getDelay (name: string) {
delay: number if (isClashX()) {
hasError: boolean const delay = await jsBridge.getProxyDelay(name)
color: string return delay
}
const { data: { delay } } = await getProxyDelay(name)
return delay
} }
export class Proxy extends React.Component<ProxyProps , ProxyState> { export function Proxy (props: ProxyProps) {
constructor (props: ProxyProps) { const { config, className } = props
super(props) const [delay, setDelay] = useState(0)
const { config } = props async function speedTest () {
const { name } = config const [delay, err] = await to(getDelay(config.name))
let color = getLocalStorageItem(name) setDelay(err ? 0 : delay)
}
useEffect(() => {
setDelay(config.history.length ? config.history.slice(-1)[0].delay : 0)
}, [config])
useLayoutEffect(() => {
EE.subscribe(Action.SPEED_NOTIFY, speedTest)
return () => EE.unsubscribe(Action.SPEED_NOTIFY, speedTest)
}, [])
const hasError = useMemo(() => delay === 0, [delay])
const color = useMemo(() => {
let color = getLocalStorageItem(config.name)
if (!color) { if (!color) {
color = sample(TagColors) color = sample(TagColors)
setLocalStorageItem(name, color) setLocalStorageItem(name, color)
} }
const delay = config.history.length ? config.history.slice(-1)[0].delay : 0 return color
this.state = { }, [config])
delay,
hasError: delay === 0,
color
}
}
componentWillUpdate () { const backgroundColor = hasError ? undefined : color
const { config: { name } } = this.props return (
const { color: rawColor } = this.state <div className={classnames('proxy-item', { 'proxy-error': hasError }, className)}>
const color = getLocalStorageItem(name) <span className="proxy-type" style={{ backgroundColor }}>{config.type}</span>
<p className="proxy-name">{config.name}</p>
if (rawColor !== color) { <p className="proxy-delay">{delay === 0 ? '-' : `${delay}ms`}</p>
this.setState({ color }) </div>
} )
}
componentDidMount () {
EE.subscribe(Action.SPEED_NOTIFY, this.speedTest)
}
componentWillUnmount () {
EE.unsubscribe(Action.SPEED_NOTIFY, this.speedTest)
}
getDelay = async (name: string) => {
if (isClashX()) {
const delay = await jsBridge.getProxyDelay(name)
return delay
}
const { data: { delay } } = await getProxyDelay(name)
return delay
}
speedTest = async () => {
const { config } = this.props
const [delay, err] = await to(this.getDelay(config.name))
this.setState({ delay: err ? -1 : delay, hasError: !!err })
}
render () {
const { config, className } = this.props
const { delay, color, hasError } = this.state
const backgroundColor = hasError ? undefined : color
return (
<div className={classnames('proxy-item', { 'proxy-error': hasError }, className)}>
<span className="proxy-type" style={{ backgroundColor }}>{config.type}</span>
<p className="proxy-name">{config.name}</p>
<p className="proxy-delay">{delay === 0 ? '-' : `${delay}ms`}</p>
{/* <Icon className="proxy-editor" type="setting" onClick={onEdit} /> */}
</div>
)
}
} }

View File

@ -1,3 +1,2 @@
export * from './Proxy' export * from './Proxy'
export * from './Group' export * from './Group'
export * from './ModifyProxyDialog'

View File

@ -1,67 +1,55 @@
import * as React from 'react' import React, { useLayoutEffect } from 'react'
import { withTranslation, WithTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { inject, observer } from 'mobx-react'
import { storeKeys } from '@lib/createStore'
import EE from '@lib/event' import EE from '@lib/event'
import { Card, Header, Icon } from '@components' import { Card, Header, Icon } from '@components'
import { BaseRouterProps } from '@models' import { Data } from '@stores'
import { Proxy, Group } from './components' import { Proxy, Group } from './components'
import './style.scss' import './style.scss'
interface ProxiesProps extends BaseRouterProps, WithTranslation {} export default function Proxies () {
const { data, fetch } = Data.useContainer()
const { t } = useTranslation(['Proxies'])
interface ProxiesState { useLayoutEffect(() => {
} fetch()
}, [])
@inject(...storeKeys) function handleNotitySpeedTest () {
@observer
class Proxies extends React.Component<ProxiesProps, ProxiesState> {
componentDidMount () {
this.props.store.fetchData()
}
handleNotitySpeedTest = () => {
EE.notifySpeedTest() EE.notifySpeedTest()
} }
render () { return (
const { t, store } = this.props <div className="page">
<div className="proxies-container">
return ( <Header title={t('groupTitle')} />
<div className="page"> <Card className="proxies-group-card">
<div className="proxies-container"> <ul className="proxies-group-list">
<Header title={t('groupTitle')} />
<Card className="proxies-group-card">
<ul className="proxies-group-list">
{
store.data.proxyGroup.map(p => (
<li className="proxies-group-item" key={p.name}>
<Group config={p} />
</li>
))
}
</ul>
</Card>
</div>
<div className="proxies-container">
<Header title={t('title')}>
<Icon type="speed" size={20} />
<span className="proxies-speed-test" onClick={this.handleNotitySpeedTest}>{t('speedTestText')}</span>
</Header>
<ul className="proxies-list">
{ {
store.data.proxy.map(p => ( data.proxyGroup.map(p => (
<li key={p.name}> <li className="proxies-group-item" key={p.name}>
<Proxy config={p} /> <Group config={p} />
</li> </li>
)) ))
} }
</ul> </ul>
</div> </Card>
</div> </div>
) <div className="proxies-container">
} <Header title={t('title')}>
<Icon type="speed" size={20} />
<span className="proxies-speed-test" onClick={handleNotitySpeedTest}>{t('speedTestText')}</span>
</Header>
<ul className="proxies-list">
{
data.proxy.map(p => (
<li key={p.name}>
<Proxy config={p} />
</li>
))
}
</ul>
</div>
</div>
)
} }
export default withTranslation(['Proxies'])(Proxies)

View File

@ -1,24 +1,20 @@
import * as React from 'react' import React, { useEffect } from 'react'
import { withTranslation, WithTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Header, Card, Row, Col } from '@components' import { Header, Card, Row, Col } from '@components'
import { BaseRouterProps } from '@models'
import './style.scss' import './style.scss'
import { storeKeys } from '@lib/createStore' import { Data } from '@stores'
import { inject, observer } from 'mobx-react'
import { List, AutoSizer } from 'react-virtualized' import { List, AutoSizer } from 'react-virtualized'
interface RulesProps extends BaseRouterProps, WithTranslation {} export default function Rules () {
const { data, fetch } = Data.useContainer()
const { t } = useTranslation(['Rules'])
const { rules } = data
@inject(...storeKeys) useEffect(() => {
@observer fetch()
class Rules extends React.Component<RulesProps, {}> { }, [])
componentWillMount () { function renderRuleItem ({ index, key, style }) {
this.props.store.fetchData()
}
renderRuleItem = ({ index, key, style }) => {
const { rules } = this.props.store.data
const rule = rules[index] const rule = rules[index]
return ( return (
<li className="rule-item" key={key} style={style}> <li className="rule-item" key={key} style={style}>
@ -37,31 +33,25 @@ class Rules extends React.Component<RulesProps, {}> {
) )
} }
render () { return (
const { t } = this.props <div className="page">
const { rules } = this.props.store.data <Header title={t('title')} />
return ( <Card className="rules-card">
<div className="page"> <AutoSizer className="rules">
<Header title={t('title')} /> {
<Card className="rules-card"> ({ height, width }) => (
<AutoSizer className="rules"> <List
{ height={height}
({ height, width }) => ( width={width}
<List rowCount={rules.length}
height={height} rowRenderer={renderRuleItem}
width={width} rowHeight={50}
rowCount={rules.length} overscanRowCount={10}
rowRenderer={this.renderRuleItem} />
rowHeight={50} )
overscanRowCount={10} }
/> </AutoSizer>
) </Card>
} </div>
</AutoSizer> )
</Card>
</div>
)
}
} }
export default withTranslation(['Rules'])(Rules)

View File

@ -1,225 +1,208 @@
import * as React from 'react' import React, { useEffect } from 'react'
import { withTranslation, WithTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import i18next from 'i18next' import i18next from 'i18next'
import { inject, observer } from 'mobx-react'
import { Header, Card, Row, Col, Switch, ButtonSelect, ButtonSelectOptions, Input, Icon } from '@components' import { Header, Card, Row, Col, Switch, ButtonSelect, ButtonSelectOptions, Input, Icon } from '@components'
import { BaseRouterProps } from '@models' import { APIInfo, Data, ClashXData, ExternalControllerModal } from '@stores'
import { updateConfig } from '@lib/request' import { updateConfig } from '@lib/request'
import { useObject } from '@lib/hook'
import { to } from '@lib/helper' import { to } from '@lib/helper'
import { rootStores, storeKeys } from '@lib/createStore'
import './style.scss'
import { isClashX, jsBridge } from '@lib/jsBridge' import { isClashX, jsBridge } from '@lib/jsBridge'
import './style.scss'
interface SettingProps extends BaseRouterProps, WithTranslation {} const languageOptions: ButtonSelectOptions[] = [{ label: '中文', value: 'zh' }, { label: 'English', value: 'en' }]
@inject(...storeKeys) function changeLanguage (language: string) {
@observer i18next.changeLanguage(language)
class Settings extends React.Component<SettingProps, {}> { }
state = {
async function handleStartAtLoginChange (state: boolean) {
await jsBridge.setStartAtLogin(state)
}
async function handleSetSystemProxy (state: boolean) {
await jsBridge.setSystemProxy(state)
}
export default function Settings () {
const { data: clashXData, fetch: fetchClashXData } = ClashXData.useContainer()
const { data, fetch } = Data.useContainer()
const { data: apiInfo } = APIInfo.useContainer()
const { show } = ExternalControllerModal.useContainer()
const { t, i18n } = useTranslation(['Settings'])
const { value: info, change } = useObject({
socks5ProxyPort: 7891, socks5ProxyPort: 7891,
httpProxyPort: 7890, httpProxyPort: 7890,
isClashX: false isClashX: false
} })
languageOptions: ButtonSelectOptions[] = [{ label: '中文', value: 'zh' }, { label: 'English', value: 'en' }] useEffect(() => {
fetch()
if (isClashX()) {
fetchClashXData().then(() => change('isClashX', true))
}
}, [])
changeLanguage = (language: string) => { useEffect(() => {
i18next.changeLanguage(language) change('socks5ProxyPort', data.general.socksPort)
} change('httpProxyPort', data.general.port)
}, [data])
handleProxyModeChange = async (mode: string) => { async function handleProxyModeChange (mode: string) {
const [, err] = await to(updateConfig({ mode })) const [, err] = await to(updateConfig({ mode }))
if (!err) { if (!err) {
rootStores.store.fetchData() fetch()
} }
} }
handleHttpPortSave = async () => { async function handleHttpPortSave () {
const [, err] = await to(updateConfig({ 'port': this.state.httpProxyPort })) const [, err] = await to(updateConfig({ 'port': info.httpProxyPort }))
if (!err) { if (!err) {
await this.props.store.fetchData() await fetch()
this.setState({ httpProxyPort: this.props.store.data.general.port }) change('httpProxyPort', data.general.port)
} }
} }
handleSocksPortSave = async () => { async function handleSocksPortSave () {
const [, err] = await to(updateConfig({ 'socks-port': this.state.socks5ProxyPort })) const [, err] = await to(updateConfig({ 'socks-port': info.socks5ProxyPort }))
if (!err) { if (!err) {
await this.props.store.fetchData() await fetch()
this.setState({ socks5ProxyPort: this.props.store.data.general.socksPort }) change('socks5ProxyPort', data.general.socksPort)
} }
} }
handleAllowLanChange = async (state: boolean) => { async function handleAllowLanChange (state: boolean) {
const [, err] = await to(updateConfig({ 'allow-lan': state })) const [, err] = await to(updateConfig({ 'allow-lan': state }))
if (!err) { if (!err) {
await this.props.store.fetchData() await fetch()
} }
} }
handleStartAtLoginChange = async (state: boolean) => { const {
await jsBridge.setStartAtLogin(state) hostname: externalControllerHost,
this.setState({ startAtLogin: state }) port: externalControllerPort
} } = apiInfo
handleSetSystemProxy = async (state: boolean) => { const { allowLan, mode } = data.general
await jsBridge.setSystemProxy(state) const {
this.setState({ setAsSystemProxy: state }) startAtLogin,
} systemProxy
} = clashXData
async componentDidMount () { const proxyModeOptions: ButtonSelectOptions[] = [
await rootStores.store.fetchData() { label: t('values.global'), value: 'Global' },
if (isClashX()) { { label: t('values.rules'), value: 'Rule' },
await rootStores.store.fetchClashXData() { label: t('values.direct'), value: 'Direct' }
this.setState({ ]
isClashX: true
})
}
const general = this.props.store.data.general return (
this.setState({ <div className="page">
socks5ProxyPort: general.socksPort, <Header title={t('title')} />
httpProxyPort: general.port <Card className="settings-card">
}) <Row gutter={24} align="middle">
} <Col span={12}>
<Col span={14} offset={1}>
render () { <span className="label">{t('labels.startAtLogin')}</span>
const { t, i18n, store } = this.props
const {
isClashX,
socks5ProxyPort,
httpProxyPort
} = this.state
const {
hostname: externalControllerHost,
port: externalControllerPort
} = store.apiInfo
const { allowLan, mode } = store.data.general
const {
startAtLogin,
systemProxy
} = store.clashxData
const proxyModeOptions: ButtonSelectOptions[] = [
{ label: t('values.global'), value: 'Global' },
{ label: t('values.rules'), value: 'Rule' },
{ label: t('values.direct'), value: 'Direct' }
]
return (
<div className="page">
<Header title={t('title')} />
<Card className="settings-card">
<Row gutter={24} align="middle">
<Col span={12}>
<Col span={14} offset={1}>
<span className="label">{t('labels.startAtLogin')}</span>
</Col>
<Col span={8} className="value-column">
<Switch disabled={!isClashX} checked={startAtLogin} onChange={this.handleStartAtLoginChange} />
</Col>
</Col> </Col>
<Col span={12}> <Col span={8} className="value-column">
<Col span={8} offset={1}> <Switch disabled={!isClashX} checked={startAtLogin} onChange={handleStartAtLoginChange} />
<span className="label">{t('labels.language')}</span>
</Col>
<Col span={14} className="value-column">
<ButtonSelect options={this.languageOptions} value={i18n.language.replace(/-.+$/, '')} onSelect={this.changeLanguage} />
</Col>
</Col> </Col>
</Row> </Col>
<Row gutter={24} align="middle"> <Col span={12}>
<Col span={12}> <Col span={8} offset={1}>
<Col span={14} offset={1}> <span className="label">{t('labels.language')}</span>
<span className="label">{t('labels.setAsSystemProxy')}</span>
</Col>
<Col span={8} className="value-column">
<Switch
disabled={!isClashX}
checked={systemProxy}
onChange={this.handleSetSystemProxy}
/>
</Col>
</Col> </Col>
<Col span={12}> <Col span={14} className="value-column">
<Col span={14} offset={1}> <ButtonSelect options={languageOptions} value={i18n.language.replace(/-.+$/, '')} onSelect={changeLanguage} />
<span className="label">{t('labels.allowConnectFromLan')}</span>
</Col>
<Col span={8} className="value-column">
<Switch
checked={allowLan}
onChange={this.handleAllowLanChange}
/>
</Col>
</Col> </Col>
</Row> </Col>
</Card> </Row>
<Row gutter={24} align="middle">
<Col span={12}>
<Col span={14} offset={1}>
<span className="label">{t('labels.setAsSystemProxy')}</span>
</Col>
<Col span={8} className="value-column">
<Switch
disabled={!isClashX}
checked={systemProxy}
onChange={handleSetSystemProxy}
/>
</Col>
</Col>
<Col span={12}>
<Col span={14} offset={1}>
<span className="label">{t('labels.allowConnectFromLan')}</span>
</Col>
<Col span={8} className="value-column">
<Switch
checked={allowLan}
onChange={handleAllowLanChange}
/>
</Col>
</Col>
</Row>
</Card>
<Card className="settings-card"> <Card className="settings-card">
<Row gutter={24} align="middle"> <Row gutter={24} align="middle">
<Col span={12}> <Col span={12}>
<Col span={8} offset={1}> <Col span={8} offset={1}>
<span className="label">{t('labels.proxyMode')}</span> <span className="label">{t('labels.proxyMode')}</span>
</Col>
<Col span={14} className="value-column">
<ButtonSelect
options={proxyModeOptions}
value={mode}
onSelect={this.handleProxyModeChange}
/>
</Col>
</Col> </Col>
<Col span={12}> <Col span={14} className="value-column">
<Col span={14} offset={1}> <ButtonSelect
<span className="label">{t('labels.socks5ProxyPort')}</span> options={proxyModeOptions}
</Col> value={mode}
<Col span={8}> onSelect={handleProxyModeChange}
<Input />
value={socks5ProxyPort}
onChange={socks5ProxyPort => this.setState({ socks5ProxyPort: parseInt(socks5ProxyPort, 10) })}
onBlur={this.handleSocksPortSave}
/>
</Col>
</Col> </Col>
</Row> </Col>
<Row gutter={24} align="middle"> <Col span={12}>
<Col span={12}> <Col span={14} offset={1}>
<Col span={14} offset={1}> <span className="label">{t('labels.socks5ProxyPort')}</span>
<span className="label">{t('labels.httpProxyPort')}</span>
</Col>
<Col span={8}>
<Input
type="number"
value={httpProxyPort}
onChange={httpProxyPort => this.setState({ httpProxyPort: parseInt(httpProxyPort, 10) })}
onBlur={this.handleHttpPortSave}
/>
</Col>
</Col> </Col>
<Col span={12}> <Col span={8}>
<Col span={12} offset={1}> <Input
<span className="label">{t('labels.externalController')}</span> value={info.socks5ProxyPort}
</Col> onChange={socks5ProxyPort => change('socks5ProxyPort', parseInt(socks5ProxyPort, 10))}
<Col className="external-controller" span={10}> onBlur={handleSocksPortSave}
<span className="modify-btn" onClick={() => this.props.store.setShowAPIModal(true)}> />
{`${externalControllerHost}:${externalControllerPort}`}
</span>
</Col>
</Col> </Col>
</Row> </Col>
</Card> </Row>
<Row gutter={24} align="middle">
<Col span={12}>
<Col span={14} offset={1}>
<span className="label">{t('labels.httpProxyPort')}</span>
</Col>
<Col span={8}>
<Input
value={info.httpProxyPort}
onChange={httpProxyPort => change('httpProxyPort', parseInt(httpProxyPort, 10))}
onBlur={handleHttpPortSave}
/>
</Col>
</Col>
<Col span={12}>
<Col span={12} offset={1}>
<span className="label">{t('labels.externalController')}</span>
</Col>
<Col className="external-controller" span={10}>
<span className="modify-btn" onClick={show}>
{`${externalControllerHost}:${externalControllerPort}`}
</span>
</Col>
</Col>
</Row>
</Card>
<Card className="clash-version" style={{ display: 'none' }}> <Card className="clash-version" style={{ display: 'none' }}>
<span className="check-icon"> <span className="check-icon">
<Icon type="check" size={20} /> <Icon type="check" size={20} />
</span> </span>
<p className="version-info">{t('versionString', { version: 'unknown' })}</p> <p className="version-info">{t('versionString', { version: 'unknown' })}</p>
<span className="check-update-btn">{t('checkUpdate')}</span> <span className="check-update-btn">{t('checkUpdate')}</span>
</Card> </Card>
</div> </div>
) )
}
} }
export default withTranslation(['Settings'])(Settings)

View File

@ -1,14 +0,0 @@
import { createHashHistory } from 'history'
import { configure } from 'mobx'
import { RouterStore, ConfigStore } from '@stores'
// prepare MobX stores
configure({ enforceActions: 'observed' })
const history = createHashHistory()
export const rootStores = {
router: new RouterStore(history),
store: new ConfigStore()
}
export const storeKeys = Object.keys(rootStores)

View File

@ -1,7 +1,7 @@
import axios, { AxiosInstance } from 'axios' import axios, { AxiosInstance } from 'axios'
import { Partial, getLocalStorageItem } from '@lib/helper' import { Partial, getLocalStorageItem } from '@lib/helper'
import { isClashX, jsBridge } from '@lib/jsBridge' import { isClashX, jsBridge } from '@lib/jsBridge'
import { rootStores } from '@lib/createStore' import { ExternalControllerModal } from '@stores'
import { Log } from '@models/Log' import { Log } from '@models/Log'
import { StreamReader } from './streamer' import { StreamReader } from './streamer'
@ -117,7 +117,8 @@ export async function getInstance () {
resp => resp, resp => resp,
err => { err => {
if (!err.response || err.response.status === 401) { if (!err.response || err.response.status === 401) {
rootStores.store.setShowAPIModal(true) const { show } = ExternalControllerModal.useContainer()
show()
} }
throw err throw err
} }

View File

@ -1,21 +1,11 @@
import { CSSProperties, ReactNode } from 'react' import { CSSProperties, ReactNode } from 'react'
import { RouteComponentProps } from 'react-router' import { RouteComponentProps } from 'react-router'
import { RouterStore, ConfigStore } from '@stores'
/** /**
* expose base router component props * expose base router component props
* and mobx store to props * and mobx store to props
*/ */
export interface BaseRouterProps extends RouteComponentProps<any>, BaseProps {} export interface BaseRouterProps extends RouteComponentProps<any> {}
/**
* use when component is inject by mobx
*/
export interface BaseProps extends BaseComponentProps {
styles?: any
router?: RouterStore
store?: ConfigStore
}
export interface BaseComponentProps { export interface BaseComponentProps {
className?: string className?: string

View File

@ -1,9 +1,7 @@
import * as React from 'react' import * as React from 'react'
import { render } from 'react-dom' import { render } from 'react-dom'
import { Provider } from 'mobx-react'
import { HashRouter } from 'react-router-dom' import { HashRouter } from 'react-router-dom'
import { I18nextProvider } from 'react-i18next' import { I18nextProvider } from 'react-i18next'
import { rootStores } from '@lib/createStore'
import { BaseComponentProps } from '@models/BaseProps' import { BaseComponentProps } from '@models/BaseProps'
import { APIInfo, Data, ClashXData, ExternalControllerModal } from '@stores' import { APIInfo, Data, ClashXData, ExternalControllerModal } from '@stores'
import App from '@containers/App' import App from '@containers/App'
@ -27,13 +25,11 @@ export default function renderApp () {
const rootEl = document.getElementById('root') const rootEl = document.getElementById('root')
const AppInstance = ( const AppInstance = (
<Store> <Store>
<Provider {...rootStores}> <HashRouter>
<HashRouter> <I18nextProvider i18n={ i18n }>
<I18nextProvider i18n={ i18n }> <App />
<App /> </I18nextProvider>
</I18nextProvider> </HashRouter>
</HashRouter>
</Provider>
</Store> </Store>
) )

View File

@ -1,228 +0,0 @@
import { observable, action, runInAction } from 'mobx'
import * as yaml from 'yaml'
import * as Models from '@models'
import { jsBridge, isClashX } from '@lib/jsBridge'
import * as API from '@lib/request'
import { getLocalStorageItem, setLocalStorageItem, partition } from '@lib/helper'
export class ConfigStore {
@observable
config: Models.Config = {
proxy: [],
proxyGroup: [],
rules: []
}
@observable
data: Models.Data = {
general: {},
proxy: [],
proxyGroup: [],
rules: []
}
@observable
apiInfo: Models.APIInfo = {
hostname: '127.0.0.1',
port: '9090',
secret: ''
}
@observable
showAPIModal = false
@observable
clashxData: Models.ClashXData = {
startAtLogin: false,
systemProxy: false
}
@action
async fetchAPIInfo () {
if (isClashX()) {
const apiInfo = await jsBridge.getAPIInfo()
runInAction(() => {
this.apiInfo = { hostname: apiInfo.host, port: apiInfo.port, secret: apiInfo.secret }
})
return
}
const info = await API.getExternalControllerConfig()
runInAction(() => {
this.apiInfo = { ...info }
})
}
@action
async fetchData () {
const [{ data: general }, rawProxies, rules] = await Promise.all([API.getConfig(), API.getProxies(), API.getRules()])
runInAction(() => {
this.data.general = {
port: general.port,
socksPort: general['socks-port'],
redirPort: general['redir-port'],
mode: general.mode,
logLevel: general['log-level'],
allowLan: general['allow-lan']
}
const policyGroup = new Set(['Selector', 'URLTest', 'Fallback', 'LoadBalance'])
const unUsedProxy = new Set(['DIRECT', 'REJECT', 'GLOBAL'])
const proxyList = rawProxies.data.proxies['GLOBAL'] as API.Group
const proxies = proxyList.all
.filter(key => !unUsedProxy.has(key))
.map(key => ({ ...rawProxies.data.proxies[key], name: key }))
const [proxy, groups] = partition(proxies, proxy => !policyGroup.has(proxy.type))
this.data.proxy = proxy as API.Proxy[]
this.data.proxyGroup = groups as API.Group[]
this.data.rules = rules.data.rules
})
}
@action
async fetchClashXData () {
const startAtLogin = await jsBridge.getStartAtLogin()
const systemProxy = await jsBridge.isSystemProxySet()
runInAction(() => {
this.clashxData = {
startAtLogin,
systemProxy
}
})
}
@action
async fetchAndParseConfig () {
const rawConfig = await jsBridge.readConfigString()
runInAction(() => {
// emit error when config is empty
// because read config might be error
if (!rawConfig) {
return
}
// otherwise parse ini
const config = yaml.parse(rawConfig)
const externalController = config['external-controller'] as string || ''
const host = externalController.split(':')
const proxies = config.Proxy as any[] || []
const proxy: Models.Proxy[] = proxies
.filter(p => ['vmess', 'ss', 'socks5'].includes(p.type))
const proxyGroups = config['Proxy Group'] as any[] || []
const proxyGroup: Models.ProxyGroup[] = proxyGroups
.filter(p => ['url-test', 'select', 'fallback'].includes(p.type))
const rules = config['Rule'] as any[] || []
const rule: Models.Rule[] = rules.map(r => r.split(',')).filter(r => r.length >= 3).map(r => ({
type: Models.RuleType[r[0] as string],
payload: r[1],
proxy: r[2]
}))
this.config = {
general: {
port: config.port || 0,
socksPort: config['socks-port'] || 0,
redirPort: config['redir-port'] || 0,
allowLan: config['allow-lan'] || false,
externalControllerAddr: host[0] || '',
externalControllerPort: host[1] || '',
secret: config.secret || '',
logLevel: config['log-level'] || 'info',
mode: config.mode || 'Rule'
},
proxy,
proxyGroup,
rules: rule || []
}
})
}
@action
async fetchConfig () {
const { data: config } = await API.getConfig()
this.config = {
general: {
port: config.port,
socksPort: config['socks-port'],
redirPort: config['redir-port'],
allowLan: config['allow-lan'],
mode: config.mode,
externalControllerAddr: getLocalStorageItem('externalControllerAddr', '127.0.0.1'),
externalControllerPort: getLocalStorageItem('externalControllerPort', '9090'),
secret: getLocalStorageItem('secret', '')
}
}
}
@action
async updateConfig () {
const { general, proxy, proxyGroup, rules } = this.config
const externalController = `${general.externalControllerAddr}:${general.externalControllerPort}`
const Rule = rules.map(r => [r.type, r.payload, r.proxy].join(','))
const config = {
'external-controller': externalController,
port: general.port,
'socks-port': general.socksPort,
'redir-port': general.redirPort,
'allow-lan': general.allowLan,
secret: general.secret,
'log-level': general.logLevel,
mode: general.mode,
Proxy: proxy,
'Proxy Group': proxyGroup,
Rule
}
const data = yaml.stringify(config)
// console.log(data)
jsBridge.writeConfigWithString(data)
}
@action
async updateAPIInfo (info: Models.APIInfo) {
const { hostname, port, secret } = info
setLocalStorageItem('externalControllerAddr', hostname)
setLocalStorageItem('externalControllerPort', port)
setLocalStorageItem('secret', secret)
window.location.reload()
}
@action
setShowAPIModal (visible: boolean) {
runInAction(() => {
this.showAPIModal = visible
})
}
@action
async modifyProxyByIndexAndSave (index: number, config: Models.Proxy) {
const { proxy } = this.config
const fomatedConfig: Models.Proxy = {}
const { type } = config
let configList: string[] = []
switch (type) {
case 'ss':
configList = Models.SsProxyConfigList
break
case 'vmess':
configList = Models.VmessProxyConfigList
break
case 'socks5':
configList = Models.Socks5ProxyConfigList
break
}
for (const configKey of configList) {
fomatedConfig[configKey] = config[configKey]
}
proxy[index] = fomatedConfig
await this.updateConfig()
await this.fetchAndParseConfig()
}
}

View File

@ -1,14 +0,0 @@
import { History } from 'history'
import { RouterStore as BaseRouterStore, syncHistoryWithStore } from 'mobx-react-router'
export class RouterStore extends BaseRouterStore {
constructor (history?: History) {
super()
if (history) {
this.history = syncHistoryWithStore(history, this)
}
}
}
export default RouterStore

View File

@ -1,3 +1 @@
export * from './ConfigStore'
export * from './RouterStore'
export * from './HookStore' export * from './HookStore'