Skip to content

Commit

Permalink
feat: Adapt switch internal network type, and notify the user network…
Browse files Browse the repository at this point in the history
… type is not running external. (#2921)

Co-authored-by: 严国宇 <[email protected]>
Co-authored-by: Keith <[email protected]>
  • Loading branch information
yanguoyu and Keith-CY authored Nov 7, 2023
1 parent e94fe9d commit 743fbd4
Show file tree
Hide file tree
Showing 82 changed files with 1,309 additions and 461 deletions.
10 changes: 5 additions & 5 deletions packages/neuron-ui/src/components/DataSetting/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useState } from 'react'
import React, { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
getCkbNodeDataPath,
Expand All @@ -7,11 +7,11 @@ import {
stopProcessMonitor,
setCkbNodeDataPath,
} from 'services/remote'
import { isSuccessResponse, useDidMount } from 'utils'
import { isSuccessResponse } from 'utils'

const type = 'ckb'

export const useDataPath = () => {
export const useDataPath = (network?: State.Network) => {
const [t] = useTranslation()
const [isSaving, setIsSaving] = useState(false)
const [savingType, setSavingType] = useState<string | null>()
Expand All @@ -20,13 +20,13 @@ export const useDataPath = () => {
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [faidMessage, setFaidMessage] = useState('')

useDidMount(() => {
useEffect(() => {
getCkbNodeDataPath().then(res => {
if (isSuccessResponse(res)) {
setPrevPath(res.result!)
}
})
})
}, [network?.id])
const onSetting = useCallback(() => {
invokeShowOpenDialog({
buttonLabel: t('settings.data.set', { lng: navigator.language }),
Expand Down
42 changes: 13 additions & 29 deletions packages/neuron-ui/src/components/DataSetting/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import React, { useCallback, useEffect, useState, useRef, useMemo } from 'react'
import React, { useCallback, useRef, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import Button from 'widgets/Button'
import ClearCache from 'components/ClearCache'
import { useDispatch, useState as useGlobalState } from 'states'
import { shell } from 'electron'
import { getIsCkbRunExternal } from 'services/remote'
import { isSuccessResponse } from 'utils'
import Tooltip from 'widgets/Tooltip'
import Dialog from 'widgets/Dialog'
import AlertDialog from 'widgets/AlertDialog'
import { LIGHT_NETWORK_TYPE } from 'utils/const'
import { NetworkType } from 'utils/const'
import { Attention } from 'widgets/Icons/icon'
import { useDataPath } from './hooks'

Expand Down Expand Up @@ -42,6 +40,12 @@ const PathItem = ({
const DataSetting = () => {
const dispatch = useDispatch()
const [t] = useTranslation()
const resyncRef = useRef<HTMLButtonElement | null>(null)
const {
chain: { networkID },
settings: { networks = [] },
} = useGlobalState()
const network = useMemo(() => networks.find(n => n.id === networkID), [networkID, networks])
const {
onSetting,
prevPath,
Expand All @@ -53,38 +57,20 @@ const DataSetting = () => {
savingType,
faidMessage,
setFaidMessage,
} = useDataPath()

const resyncRef = useRef<HTMLButtonElement | null>(null)
} = useDataPath(network)

const openPath = useCallback(() => {
if (prevPath) {
shell.openPath(prevPath!)
}
}, [prevPath])
const [isCkbRunExternal, setIsCkbRunExternal] = useState<boolean | undefined>()
useEffect(() => {
getIsCkbRunExternal().then(res => {
if (isSuccessResponse(res)) {
setIsCkbRunExternal(res.result ?? false)
} else {
// ignore
}
})
}, [])
const {
chain: { networkID },
settings: { networks = [] },
} = useGlobalState()
const isLightClient = useMemo(
() => networks.find(n => n.id === networkID)?.type === LIGHT_NETWORK_TYPE,
[networkID, networks]
)
const isLightClient = network?.type === NetworkType.Light
const hiddenDataPath = isLightClient || !network?.readonly
return (
<>
<div className={styles.root}>
<div className={styles.leftContainer}>
{isLightClient ? null : (
{hiddenDataPath ? null : (
<div className={styles.label}>
<div>{t('settings.data.ckb-node-data')}</div>
<Tooltip
Expand All @@ -110,9 +96,7 @@ const DataSetting = () => {
</div>
</div>
<div className={styles.rightContainer}>
{isLightClient ? null : (
<PathItem path={prevPath} openPath={openPath} handleClick={onSetting} disabled={isCkbRunExternal} />
)}
{hiddenDataPath ? null : <PathItem path={prevPath} openPath={openPath} handleClick={onSetting} />}
<ClearCache
className={styles.item}
btnClassName={styles.itemBtn}
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-ui/src/components/HDWalletSign/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { DeviceSignIndex as DeviceSignIndexSubject } from 'services/subjects'

import styles from '../HardwareSign/hardwareSign.module.scss'

const { MAINNET_TAG } = CONSTANTS
const { MAINNET_CLIENT_LIST } = CONSTANTS

const HDWalletSign = ({ tx }: { tx: State.DetailedTransaction }) => {
const [t] = useTranslation()
Expand All @@ -33,7 +33,7 @@ const HDWalletSign = ({ tx }: { tx: State.DetailedTransaction }) => {
throw new Error('Cannot find current network in the network list')
}

setIsMainnet(network.chain === MAINNET_TAG)
setIsMainnet(MAINNET_CLIENT_LIST.includes(network.chain))
}
})
.catch(err => console.warn(err))
Expand Down
7 changes: 2 additions & 5 deletions packages/neuron-ui/src/components/HistoryDetailPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,16 @@ import Tooltip from 'widgets/Tooltip'

import {
ErrorCode,
CONSTANTS,
localNumberFormatter,
uniformTimeFormatter,
shannonToCKBFormatter,
isSuccessResponse,
isMainnet as isMainnetUtil,
} from 'utils'
import { HIDE_BALANCE } from 'utils/const'

import styles from './historyDetailPage.module.scss'

const { MAINNET_TAG } = CONSTANTS

type InputOrOutputType = (State.DetailedInput | State.DetailedOutput) & { idx: number }

const InfoItem = ({ label, value, className }: { label: string; value: React.ReactNode; className?: string }) => (
Expand All @@ -46,8 +44,7 @@ const HistoryDetailPage = () => {
settings: { networks },
wallet: currentWallet,
} = useGlobalState()
const network = networks.find(n => n.id === networkID)
const isMainnet = network != null && network.chain === MAINNET_TAG
const isMainnet = isMainnetUtil(networks, networkID)
const [t] = useTranslation()
const [transaction, setTransaction] = useState(transactionState)
const [error, setError] = useState({ code: '', message: '' })
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-ui/src/components/MultisigAddress/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { ReactComponent as Transfer } from 'widgets/Icons/Transfer.svg'
import { ReactComponent as Upload } from 'widgets/Icons/Upload.svg'
import { ReactComponent as Edit } from 'widgets/Icons/Edit.svg'
import { Download, Search } from 'widgets/Icons/icon'
import { HIDE_BALANCE, LIGHT_NETWORK_TYPE } from 'utils/const'
import { HIDE_BALANCE, NetworkType } from 'utils/const'
import { onEnter } from 'utils/inputDevice'
import { useSearch, useConfigManage, useExportConfig, useActions, useSubscription } from './hooks'

Expand Down Expand Up @@ -62,7 +62,7 @@ const MultisigAddress = () => {
} = useGlobalState()
const isMainnet = isMainnetUtil(networks, networkID)
const isLightClient = useMemo(
() => networks.find(n => n.id === networkID)?.type === LIGHT_NETWORK_TYPE,
() => networks.find(n => n.id === networkID)?.type === NetworkType.Light,
[networks, networkID]
)
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React, { FC, useMemo, useState } from 'react'
import Tabs, { VariantProps } from 'widgets/Tabs'
import { clsx, localNumberFormatter, shannonToCKBFormatter } from 'utils'
import { clsx, localNumberFormatter, shannonToCKBFormatter, isMainnet as isMainnetUtils } from 'utils'
import { useTranslation } from 'react-i18next'
import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils'
import { onEnter } from 'utils/inputDevice'
import { EyesClose, EyesOpen } from 'widgets/Icons/icon'
import { HIDE_BALANCE, MAINNET_TAG } from 'utils/const'
import { HIDE_BALANCE } from 'utils/const'
import ScriptTag from 'components/ScriptTag'
import LockInfoDialog from 'components/LockInfoDialog'
import { useState as useGlobalState } from 'states'
Expand All @@ -24,8 +24,7 @@ const TabsVariantWithCellsCard: FC<
chain: { networkID },
settings: { networks },
} = useGlobalState()
const network = networks.find(n => n.id === networkID)
const isMainnet = network != null && network.chain === MAINNET_TAG
const isMainnet = isMainnetUtils(networks, networkID)

const [isPrivacyMode, setIsPrivacyMode] = useState(false)
const [showingLockInfo, setShowingLockInfo] = useState<CKBComponents.Script | null>(null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ const NetworkEditorDialog = ({
onCancel,
id,
onSuccess,
url,
}: {
onCancel: () => void
id: 'new' | string
onSuccess: () => void
url?: string
}) => {
const {
settings: { networks = [] },
Expand All @@ -31,7 +33,7 @@ const NetworkEditorDialog = ({
const [editor, setEditor] = useState({
name: '',
nameError: '',
url: '',
url: url ?? '',
urlError: '',
})
const [isUpdating, setIsUpdating] = useState(false)
Expand Down Expand Up @@ -115,6 +117,7 @@ const NetworkEditorDialog = ({
error={editor.urlError}
placeholder={t('settings.network.edit-network.input-rpc')}
autoFocus
disabled={!!url}
/>
<TextField
value={editor.name}
Expand Down
59 changes: 48 additions & 11 deletions packages/neuron-ui/src/components/NetworkSetting/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import React, { useEffect, useCallback, useState } from 'react'
import React, { useEffect, useCallback, useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { ReactComponent as EditNetwork } from 'widgets/Icons/Edit.svg'
import { ReactComponent as DeleteNetwork } from 'widgets/Icons/Delete.svg'
import { ReactComponent as AddSimple } from 'widgets/Icons/AddSimple.svg'
import NetworkEditorDialog from 'components/NetworkEditorDialog'
import AlertDialog from 'widgets/AlertDialog'
import Toast from 'widgets/Toast'
import { chainState } from 'states'
import { setCurrentNetwork, deleteNetwork } from 'services/remote'
import RadioGroup from 'widgets/RadioGroup'
import { useOnWindowResize, useToggleChoiceGroupBorder, getNetworkLabelI18nkey } from 'utils'
import { AddSimple, Switch } from 'widgets/Icons/icon'
import Tooltip from 'widgets/Tooltip'
import { LIGHT_CLIENT_MAINNET, NetworkType } from 'utils/const'
import { lastShowInternalNodeIds } from 'services/localCache'
import styles from './networkSetting.module.scss'

const NetworkSetting = ({ chain = chainState, settings: { networks = [] } }: State.AppWithNeuronWallet) => {
Expand Down Expand Up @@ -43,7 +46,6 @@ const NetworkSetting = ({ chain = chainState, settings: { networks = [] } }: Sta
break
}
default:
// @ts-ignore
}
},
[setNetId, setShowEditorDialog, setShowDeleteDialog]
Expand Down Expand Up @@ -75,20 +77,55 @@ const NetworkSetting = ({ chain = chainState, settings: { networks = [] } }: Sta
}
}, [setShowEditorDialog, setNotice, netId])

const onSwitchNetworkType = useCallback<React.MouseEventHandler<HTMLButtonElement>>(() => {
const selectedNetwork = networks.find(v => v.id === currentId)
const switchNetwork = networks.find(v => v.type === selectedNetwork?.type && v.id !== currentId)
if (switchNetwork) {
setCurrentNetwork(switchNetwork.id)
lastShowInternalNodeIds.save(switchNetwork.type, switchNetwork.id)
}
}, [currentId, networks])

const showNetworks = useMemo(() => {
const internalLightNodeId = lastShowInternalNodeIds.get(NetworkType.Light)
return networks.filter(v => v.type !== NetworkType.Light || v.id === internalLightNodeId)
}, [currentId, networks])

return (
<div>
<RadioGroup
defaultValue={currentId}
value={currentId}
onChange={handleChange}
itemClassName={styles.radioItem}
options={networks.map(network => ({
options={showNetworks.map(network => ({
value: network.id,
label: (
<div className={styles.networkLabel}>
<p>{`${network.name} (${network.remote})`}</p>
<div className={styles.tag}>{t(getNetworkLabelI18nkey(network.chain))}</div>
</div>
),
label:
currentId === network.id && network.type === NetworkType.Light ? (
<div className={styles.networkLabel}>
<p>{`${network.name} (${network.remote})`}</p>
<Tooltip
tip={
<button type="button" onClick={onSwitchNetworkType} className={styles.switchBtn}>
{t('settings.network.switch-network-type', {
type: network.chain === LIGHT_CLIENT_MAINNET ? 'testnet' : 'mainnet',
})}
</button>
}
placement="top"
showTriangle
>
<div className={styles.tag}>
{t(getNetworkLabelI18nkey(network.chain))}
<Switch />
</div>
</Tooltip>
</div>
) : (
<div className={styles.networkLabel}>
<p>{`${network.name} (${network.remote})`}</p>
<div className={styles.tag}>{t(getNetworkLabelI18nkey(network.chain))}</div>
</div>
),
suffix: (
<div className={styles.suffix}>
{network.readonly ? null : (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@
background: var(--table-head-background-color);
border: 1px solid var(--divide-line-color);
border-radius: 40px;
display: flex;
align-items: center;

& > svg {
margin-left: 4px;
}
}
.switchBtn {
border: none;
background-color: transparent;
cursor: pointer;
color: var(--main-text-color);
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-ui/src/components/PageContainer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import SyncStatusComponent from 'components/SyncStatus'
import { AppActions, useDispatch, useState as useGlobalState } from 'states'
import { openExternal } from 'services/remote'
import Tooltip from 'widgets/Tooltip'
import { LIGHT_NETWORK_TYPE } from 'utils/const'
import { NetworkType } from 'utils/const'
import Dialog from 'widgets/Dialog'
import TextField from 'widgets/TextField'

Expand Down Expand Up @@ -59,7 +59,7 @@ const PageContainer: React.FC<ComponentProps> = props => {
const { theme, onSetTheme } = useTheme()
const network = useMemo(() => networks.find(n => n.id === networkID), [networks, networkID])
const isLightClient = useMemo(
() => networks.find(n => n.id === networkID)?.type === LIGHT_NETWORK_TYPE,
() => networks.find(n => n.id === networkID)?.type === NetworkType.Light,
[networkID, networks]
)
const netWorkTypeLabel = useMemo(() => (network ? getNetworkLabelI18nkey(network.chain) : ''), [network])
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-ui/src/components/Receive/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const useCopyAndDownloadQrCode = () => {
const toShortAddr = (addr: string) => {
try {
const script = addressToScript(addr)
const isMainnet = addr.startsWith('ckb')
const isMainnet = addr.startsWith(AddressPrefix.Mainnet)
return bech32Address(script.args, { prefix: isMainnet ? AddressPrefix.Mainnet : AddressPrefix.Testnet })
} catch {
return ''
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const { DEFAULT_SUDT_FIELDS } = CONSTANTS
const toShortAddr = (addr: string) => {
try {
const script = addressToScript(addr)
const isMainnet = addr.startsWith('ckb')
const isMainnet = addr.startsWith(AddressPrefix.Mainnet)
return bech32Address(script.args, {
prefix: isMainnet ? AddressPrefix.Mainnet : AddressPrefix.Testnet,
codeHashOrCodeHashIndex: '0x02',
Expand Down
Loading

2 comments on commit 743fbd4

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packaging for test is done in 6785547095

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packaging for test is done in 6785553269

Please sign in to comment.