Skip to content

Commit

Permalink
feat(neuron-ui): call networks controller's methods by remote module
Browse files Browse the repository at this point in the history
  • Loading branch information
Keith-CY committed Jul 25, 2019
1 parent 1173622 commit c4bc431
Show file tree
Hide file tree
Showing 9 changed files with 192 additions and 191 deletions.
87 changes: 83 additions & 4 deletions packages/neuron-ui/src/components/NetworkEditor/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useState, useEffect, useMemo, useCallback } from 'react'

import { AppActions, StateDispatch } from 'states/stateProvider/reducer'
import actionCreators from 'states/stateProvider/actionCreators'
import { Message, MAX_NETWORK_NAME_LENGTH, Routes } from 'utils/const'
import { createNetwork, updateNetwork } from 'services/remote'

import i18n from 'utils/i18n'

Expand Down Expand Up @@ -119,11 +120,89 @@ export const useHandleSubmit = (
name: string = '',
remote: string = '',
networks: State.Network[] = [],
history: any,
dispatch: StateDispatch
) =>
useCallback(() => {
dispatch(actionCreators.createOrUpdateNetwork({ id, name, remote }, networks))
}, [id, name, remote, networks, dispatch])
useCallback(async () => {
const warning = {
type: 'warning',
timestamp: Date.now(),
content: '',
}
let res
if (!name) {
return dispatch({
type: AppActions.AddNotification,
payload: {
...warning,
content: i18n.t(Message.NameRequired),
},
})
}
if (name.length > MAX_NETWORK_NAME_LENGTH) {
return dispatch({
type: AppActions.AddNotification,
payload: {
...warning,
content: i18n.t(Message.LengthOfNameShouldBeLessThanOrEqualTo, {
length: MAX_NETWORK_NAME_LENGTH,
}),
},
})
}
if (!remote) {
return dispatch({
type: AppActions.AddNotification,
payload: {
...warning,
content: i18n.t(Message.URLRequired),
},
})
}
if (!remote.startsWith('http')) {
return dispatch({
type: AppActions.AddNotification,
payload: {
...warning,
content: i18n.t(Message.ProtocolRequired),
},
})
}
// verification, for now, only name is unique
if (id === 'new') {
if (networks.some(network => network.name === name)) {
return dispatch({
type: AppActions.AddNotification,
payload: {
...warning,
content: i18n.t(Message.NetworkNameUsed),
},
})
}
res = await createNetwork({
name,
remote,
})
} else {
if (networks.some(network => network.name === name && network.id !== id)) {
return dispatch({
type: AppActions.AddNotification,
payload: {
...warning,
content: i18n.t(Message.NetworkNameUsed),
},
})
}
res = await updateNetwork(id!, {
name,
remote,
})
}
if (res && res.status) {
history.push(Routes.SettingsNetworks)
}
return res
}, [id, name, remote, networks, history, dispatch])

export default {
useInitialize,
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-ui/src/components/NetworkEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const NetworkEditor = ({
const cachedNetworks = useRef(networks)
const cachedNetwork = cachedNetworks.current.find(network => network.id === id)
const { invalidParams, notModified } = useIsInputsValid(editor, cachedNetwork)
const handleSubmit = useHandleSubmit(id, editor.name.value, editor.remote.value, networks, dispatch)
const handleSubmit = useHandleSubmit(id, editor.name.value, editor.remote.value, networks, history, dispatch)

return (
<Stack tokens={{ childrenGap: 15 }}>
Expand Down
16 changes: 6 additions & 10 deletions packages/neuron-ui/src/components/NetworkSetting/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { useTranslation } from 'react-i18next'
import { Stack, PrimaryButton, ChoiceGroup, IChoiceGroupOption } from 'office-ui-fabric-react'

import { StateWithDispatch } from 'states/stateProvider/reducer'
import actionCreators from 'states/stateProvider/actionCreators'
import chainState from 'states/initStates/chain'
import { appCalls } from 'services/UILayer'
import { setCurrentNetowrk } from 'services/remote'

import { Routes } from 'utils/const'

Expand All @@ -17,19 +17,15 @@ const onContextMenu = (id: string = '') => () => {
const NetworkSetting = ({
chain = chainState,
settings: { networks = [] },
dispatch,
history,
}: React.PropsWithoutRef<StateWithDispatch & RouteComponentProps>) => {
const [t] = useTranslation()

const onChoiceChange = useCallback(
(_e, option?: IChoiceGroupOption) => {
if (option) {
dispatch(actionCreators.setNetwork(option.key))
}
},
[dispatch]
)
const onChoiceChange = useCallback((_e, option?: IChoiceGroupOption) => {
if (option) {
setCurrentNetowrk(option.key)
}
}, [])

const goToCreateNetwork = useCallback(() => {
history.push(`${Routes.NetworkEditor}/new`)
Expand Down
38 changes: 0 additions & 38 deletions packages/neuron-ui/src/containers/Main/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@ import { actionCreators } from 'states/stateProvider/actionCreators'
import UILayer, {
AppMethod,
ChainMethod,
NetworksMethod,
TransactionsMethod,
WalletsMethod,
walletsCall,
transactionsCall,
networksCall,
} from 'services/UILayer'
import { initWindow } from 'services/remote'
import {
Expand Down Expand Up @@ -263,37 +261,6 @@ export const useChannelListeners = ({
})
}
})

UILayer.on(Channel.Networks, (_e: Event, method: NetworksMethod, args: ChannelResponse<any>) => {
if (args.status) {
switch (method) {
case NetworksMethod.Create:
case NetworksMethod.Update: {
history.push(Routes.SettingsNetworks)
break
}
case NetworksMethod.Activate: {
dispatch({
type: NeuronWalletActions.Chain,
payload: { network: args.result },
})
break
}
default: {
break
}
}
} else {
dispatch({
type: AppActions.AddNotification,
payload: {
type: 'alert',
content: args.msg,
timestamp: Date.now(),
},
})
}
})
}, [walletID, i18n, chain, dispatch, history])

export const useSyncChainData = ({ chainURL, dispatch }: { chainURL: string; dispatch: StateDispatch }) => {
Expand Down Expand Up @@ -434,11 +401,6 @@ export const useSubscription = ({
walletsCall.getCurrent()
break
}
case 'network': {
networksCall.getAll()
networksCall.currentID()
break
}
default: {
break
}
Expand Down
22 changes: 0 additions & 22 deletions packages/neuron-ui/src/services/UILayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,6 @@ export enum WalletsMethod {
GetAllAddresses = 'getAllAddresses',
}

export enum NetworksMethod {
Get = 'get',
Create = 'create',
Update = 'update',
Delete = 'delete',
Activate = 'activate',
CurrentID = 'currentID',
}

export enum TransactionsMethod {
GetAll = 'getAll',
GetAllByKeywords = 'getAllByKeywords',
Expand Down Expand Up @@ -96,19 +87,6 @@ export const appCalls = instantiateMethodCall(app) as {
handleViewError: (errorMessage: string) => void
}

export const networks = (method: NetworksMethod, ...params: any[]) => {
UILayer.send(Channel.Networks, method, ...params)
}
export const networksCall = instantiateMethodCall(networks) as {
getAll: () => void
get: (id: string) => void
create: (network: State.NetworkProperty) => void
update: (id: string, options: Partial<State.Network>) => void
delete: (id: string) => void
currentID: () => void
activate: (id: string) => void
}

export const transactions = (method: TransactionsMethod, params: string | GetTransactionsParams) => {
UILayer.send(Channel.Transactions, method, params)
}
Expand Down
101 changes: 101 additions & 0 deletions packages/neuron-ui/src/services/remote.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
// TODO: use error code
interface SuccessFromController {
status: 1
result: any
}
interface FailureFromController {
status: 0
message: {
title: string
content?: string
}
}
type ControllerResponse = SuccessFromController | FailureFromController

const RemoteNotLoadError = {
status: 0 as 0,
message: {
title: 'remote is not supported',
},
}

const controllerNotLoaded = (controllerName: string) => ({
status: 0 as 0,
message: {
title: `${controllerName} controller not loaded`,
},
})

export const initWindow = () => {
if (!window.remote) {
console.warn('remote is not supported')
Expand All @@ -16,6 +44,78 @@ export const validateMnemonic = (mnemonic: string): boolean => {
return remoteValidateMnemonic(mnemonic)
}

export const setCurrentNetowrk = async (networkID: string): Promise<ControllerResponse> => {
if (!window.remote) {
return RemoteNotLoadError
}
const networkController = window.remote.require('./controllers/networks').default
if (networkController) {
const res = await networkController.activate(networkID)
if (res.status) {
return {
status: 1,
result: true,
}
}
return {
status: 0,
message: res.status.msg || '',
}
}
return controllerNotLoaded('network')
}

export const createNetwork = async ({
name,
remote,
}: {
name: string
remote: string
}): Promise<ControllerResponse> => {
if (!window.remote) {
return RemoteNotLoadError
}
const networkController = window.remote.require('./controllers/networks').default
if (networkController) {
const res = await networkController.create({ name, remote })
if (res.status) {
return {
status: 1,
result: true,
}
}
return {
status: 0,
message: res.status.msg || '',
}
}
return controllerNotLoaded('network')
}

export const updateNetwork = async (
networkID: string,
options: Partial<{ name: string; remote: string }>
): Promise<ControllerResponse> => {
if (!window.remote) {
return RemoteNotLoadError
}
const networkController = window.remote.require('./controllers/networks').default
if (networkController) {
const res = await networkController.update(networkID, options)
if (res.status) {
return {
status: 1,
result: true,
}
}
return {
status: 0,
message: res.status.msg || '',
}
}
return controllerNotLoaded('network')
}

export const showMessage = (options: any, callback: Function) => {
if (!window.remote) {
console.warn('remote is not supported')
Expand All @@ -37,6 +137,7 @@ export const showErrorMessage = (title: string, content: string) => {
export default {
initWindow,
validateMnemonic,
setCurrentNetowrk,
showMessage,
showErrorMessage,
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import wallets from './wallets'
import networks from './networks'
import send from './send'
import transactions from './transactions'
import settings from './settings'

export const actionCreators = {
...wallets,
...networks,
...send,
...transactions,
...settings,
Expand Down
Loading

0 comments on commit c4bc431

Please sign in to comment.