Skip to content

Commit c4bc431

Browse files
committed
feat(neuron-ui): call networks controller's methods by remote module
1 parent 1173622 commit c4bc431

9 files changed

Lines changed: 192 additions & 191 deletions

File tree

packages/neuron-ui/src/components/NetworkEditor/hooks.ts

Lines changed: 83 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { useState, useEffect, useMemo, useCallback } from 'react'
22

33
import { AppActions, StateDispatch } from 'states/stateProvider/reducer'
4-
import actionCreators from 'states/stateProvider/actionCreators'
4+
import { Message, MAX_NETWORK_NAME_LENGTH, Routes } from 'utils/const'
5+
import { createNetwork, updateNetwork } from 'services/remote'
56

67
import i18n from 'utils/i18n'
78

@@ -119,11 +120,89 @@ export const useHandleSubmit = (
119120
name: string = '',
120121
remote: string = '',
121122
networks: State.Network[] = [],
123+
history: any,
122124
dispatch: StateDispatch
123125
) =>
124-
useCallback(() => {
125-
dispatch(actionCreators.createOrUpdateNetwork({ id, name, remote }, networks))
126-
}, [id, name, remote, networks, dispatch])
126+
useCallback(async () => {
127+
const warning = {
128+
type: 'warning',
129+
timestamp: Date.now(),
130+
content: '',
131+
}
132+
let res
133+
if (!name) {
134+
return dispatch({
135+
type: AppActions.AddNotification,
136+
payload: {
137+
...warning,
138+
content: i18n.t(Message.NameRequired),
139+
},
140+
})
141+
}
142+
if (name.length > MAX_NETWORK_NAME_LENGTH) {
143+
return dispatch({
144+
type: AppActions.AddNotification,
145+
payload: {
146+
...warning,
147+
content: i18n.t(Message.LengthOfNameShouldBeLessThanOrEqualTo, {
148+
length: MAX_NETWORK_NAME_LENGTH,
149+
}),
150+
},
151+
})
152+
}
153+
if (!remote) {
154+
return dispatch({
155+
type: AppActions.AddNotification,
156+
payload: {
157+
...warning,
158+
content: i18n.t(Message.URLRequired),
159+
},
160+
})
161+
}
162+
if (!remote.startsWith('http')) {
163+
return dispatch({
164+
type: AppActions.AddNotification,
165+
payload: {
166+
...warning,
167+
content: i18n.t(Message.ProtocolRequired),
168+
},
169+
})
170+
}
171+
// verification, for now, only name is unique
172+
if (id === 'new') {
173+
if (networks.some(network => network.name === name)) {
174+
return dispatch({
175+
type: AppActions.AddNotification,
176+
payload: {
177+
...warning,
178+
content: i18n.t(Message.NetworkNameUsed),
179+
},
180+
})
181+
}
182+
res = await createNetwork({
183+
name,
184+
remote,
185+
})
186+
} else {
187+
if (networks.some(network => network.name === name && network.id !== id)) {
188+
return dispatch({
189+
type: AppActions.AddNotification,
190+
payload: {
191+
...warning,
192+
content: i18n.t(Message.NetworkNameUsed),
193+
},
194+
})
195+
}
196+
res = await updateNetwork(id!, {
197+
name,
198+
remote,
199+
})
200+
}
201+
if (res && res.status) {
202+
history.push(Routes.SettingsNetworks)
203+
}
204+
return res
205+
}, [id, name, remote, networks, history, dispatch])
127206

128207
export default {
129208
useInitialize,

packages/neuron-ui/src/components/NetworkEditor/index.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ const NetworkEditor = ({
2424
const cachedNetworks = useRef(networks)
2525
const cachedNetwork = cachedNetworks.current.find(network => network.id === id)
2626
const { invalidParams, notModified } = useIsInputsValid(editor, cachedNetwork)
27-
const handleSubmit = useHandleSubmit(id, editor.name.value, editor.remote.value, networks, dispatch)
27+
const handleSubmit = useHandleSubmit(id, editor.name.value, editor.remote.value, networks, history, dispatch)
2828

2929
return (
3030
<Stack tokens={{ childrenGap: 15 }}>

packages/neuron-ui/src/components/NetworkSetting/index.tsx

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ import { useTranslation } from 'react-i18next'
44
import { Stack, PrimaryButton, ChoiceGroup, IChoiceGroupOption } from 'office-ui-fabric-react'
55

66
import { StateWithDispatch } from 'states/stateProvider/reducer'
7-
import actionCreators from 'states/stateProvider/actionCreators'
87
import chainState from 'states/initStates/chain'
98
import { appCalls } from 'services/UILayer'
9+
import { setCurrentNetowrk } from 'services/remote'
1010

1111
import { Routes } from 'utils/const'
1212

@@ -17,19 +17,15 @@ const onContextMenu = (id: string = '') => () => {
1717
const NetworkSetting = ({
1818
chain = chainState,
1919
settings: { networks = [] },
20-
dispatch,
2120
history,
2221
}: React.PropsWithoutRef<StateWithDispatch & RouteComponentProps>) => {
2322
const [t] = useTranslation()
2423

25-
const onChoiceChange = useCallback(
26-
(_e, option?: IChoiceGroupOption) => {
27-
if (option) {
28-
dispatch(actionCreators.setNetwork(option.key))
29-
}
30-
},
31-
[dispatch]
32-
)
24+
const onChoiceChange = useCallback((_e, option?: IChoiceGroupOption) => {
25+
if (option) {
26+
setCurrentNetowrk(option.key)
27+
}
28+
}, [])
3329

3430
const goToCreateNetwork = useCallback(() => {
3531
history.push(`${Routes.NetworkEditor}/new`)

packages/neuron-ui/src/containers/Main/hooks.ts

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,10 @@ import { actionCreators } from 'states/stateProvider/actionCreators'
77
import UILayer, {
88
AppMethod,
99
ChainMethod,
10-
NetworksMethod,
1110
TransactionsMethod,
1211
WalletsMethod,
1312
walletsCall,
1413
transactionsCall,
15-
networksCall,
1614
} from 'services/UILayer'
1715
import { initWindow } from 'services/remote'
1816
import {
@@ -263,37 +261,6 @@ export const useChannelListeners = ({
263261
})
264262
}
265263
})
266-
267-
UILayer.on(Channel.Networks, (_e: Event, method: NetworksMethod, args: ChannelResponse<any>) => {
268-
if (args.status) {
269-
switch (method) {
270-
case NetworksMethod.Create:
271-
case NetworksMethod.Update: {
272-
history.push(Routes.SettingsNetworks)
273-
break
274-
}
275-
case NetworksMethod.Activate: {
276-
dispatch({
277-
type: NeuronWalletActions.Chain,
278-
payload: { network: args.result },
279-
})
280-
break
281-
}
282-
default: {
283-
break
284-
}
285-
}
286-
} else {
287-
dispatch({
288-
type: AppActions.AddNotification,
289-
payload: {
290-
type: 'alert',
291-
content: args.msg,
292-
timestamp: Date.now(),
293-
},
294-
})
295-
}
296-
})
297264
}, [walletID, i18n, chain, dispatch, history])
298265

299266
export const useSyncChainData = ({ chainURL, dispatch }: { chainURL: string; dispatch: StateDispatch }) => {
@@ -434,11 +401,6 @@ export const useSubscription = ({
434401
walletsCall.getCurrent()
435402
break
436403
}
437-
case 'network': {
438-
networksCall.getAll()
439-
networksCall.currentID()
440-
break
441-
}
442404
default: {
443405
break
444406
}

packages/neuron-ui/src/services/UILayer.ts

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,6 @@ export enum WalletsMethod {
3535
GetAllAddresses = 'getAllAddresses',
3636
}
3737

38-
export enum NetworksMethod {
39-
Get = 'get',
40-
Create = 'create',
41-
Update = 'update',
42-
Delete = 'delete',
43-
Activate = 'activate',
44-
CurrentID = 'currentID',
45-
}
46-
4738
export enum TransactionsMethod {
4839
GetAll = 'getAll',
4940
GetAllByKeywords = 'getAllByKeywords',
@@ -96,19 +87,6 @@ export const appCalls = instantiateMethodCall(app) as {
9687
handleViewError: (errorMessage: string) => void
9788
}
9889

99-
export const networks = (method: NetworksMethod, ...params: any[]) => {
100-
UILayer.send(Channel.Networks, method, ...params)
101-
}
102-
export const networksCall = instantiateMethodCall(networks) as {
103-
getAll: () => void
104-
get: (id: string) => void
105-
create: (network: State.NetworkProperty) => void
106-
update: (id: string, options: Partial<State.Network>) => void
107-
delete: (id: string) => void
108-
currentID: () => void
109-
activate: (id: string) => void
110-
}
111-
11290
export const transactions = (method: TransactionsMethod, params: string | GetTransactionsParams) => {
11391
UILayer.send(Channel.Transactions, method, params)
11492
}

packages/neuron-ui/src/services/remote.ts

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,31 @@
1+
// TODO: use error code
2+
interface SuccessFromController {
3+
status: 1
4+
result: any
5+
}
6+
interface FailureFromController {
7+
status: 0
8+
message: {
9+
title: string
10+
content?: string
11+
}
12+
}
13+
type ControllerResponse = SuccessFromController | FailureFromController
14+
15+
const RemoteNotLoadError = {
16+
status: 0 as 0,
17+
message: {
18+
title: 'remote is not supported',
19+
},
20+
}
21+
22+
const controllerNotLoaded = (controllerName: string) => ({
23+
status: 0 as 0,
24+
message: {
25+
title: `${controllerName} controller not loaded`,
26+
},
27+
})
28+
129
export const initWindow = () => {
230
if (!window.remote) {
331
console.warn('remote is not supported')
@@ -16,6 +44,78 @@ export const validateMnemonic = (mnemonic: string): boolean => {
1644
return remoteValidateMnemonic(mnemonic)
1745
}
1846

47+
export const setCurrentNetowrk = async (networkID: string): Promise<ControllerResponse> => {
48+
if (!window.remote) {
49+
return RemoteNotLoadError
50+
}
51+
const networkController = window.remote.require('./controllers/networks').default
52+
if (networkController) {
53+
const res = await networkController.activate(networkID)
54+
if (res.status) {
55+
return {
56+
status: 1,
57+
result: true,
58+
}
59+
}
60+
return {
61+
status: 0,
62+
message: res.status.msg || '',
63+
}
64+
}
65+
return controllerNotLoaded('network')
66+
}
67+
68+
export const createNetwork = async ({
69+
name,
70+
remote,
71+
}: {
72+
name: string
73+
remote: string
74+
}): Promise<ControllerResponse> => {
75+
if (!window.remote) {
76+
return RemoteNotLoadError
77+
}
78+
const networkController = window.remote.require('./controllers/networks').default
79+
if (networkController) {
80+
const res = await networkController.create({ name, remote })
81+
if (res.status) {
82+
return {
83+
status: 1,
84+
result: true,
85+
}
86+
}
87+
return {
88+
status: 0,
89+
message: res.status.msg || '',
90+
}
91+
}
92+
return controllerNotLoaded('network')
93+
}
94+
95+
export const updateNetwork = async (
96+
networkID: string,
97+
options: Partial<{ name: string; remote: string }>
98+
): Promise<ControllerResponse> => {
99+
if (!window.remote) {
100+
return RemoteNotLoadError
101+
}
102+
const networkController = window.remote.require('./controllers/networks').default
103+
if (networkController) {
104+
const res = await networkController.update(networkID, options)
105+
if (res.status) {
106+
return {
107+
status: 1,
108+
result: true,
109+
}
110+
}
111+
return {
112+
status: 0,
113+
message: res.status.msg || '',
114+
}
115+
}
116+
return controllerNotLoaded('network')
117+
}
118+
19119
export const showMessage = (options: any, callback: Function) => {
20120
if (!window.remote) {
21121
console.warn('remote is not supported')
@@ -37,6 +137,7 @@ export const showErrorMessage = (title: string, content: string) => {
37137
export default {
38138
initWindow,
39139
validateMnemonic,
140+
setCurrentNetowrk,
40141
showMessage,
41142
showErrorMessage,
42143
}

packages/neuron-ui/src/states/stateProvider/actionCreators/index.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import wallets from './wallets'
2-
import networks from './networks'
32
import send from './send'
43
import transactions from './transactions'
54
import settings from './settings'
65

76
export const actionCreators = {
87
...wallets,
9-
...networks,
108
...send,
119
...transactions,
1210
...settings,

0 commit comments

Comments
 (0)