Skip to content

Commit

Permalink
refactor: remove unnecessary types from fetcher
Browse files Browse the repository at this point in the history
  • Loading branch information
WhiteMinds committed Oct 17, 2023
1 parent 33247ec commit 89d499d
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 72 deletions.
19 changes: 13 additions & 6 deletions src/components/Toast/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import { useTimeoutWithUnmount } from '../../utils/hook'
import { ToastItemPanel, ToastPanel } from './styled'
import { createGlobalState, useGlobalState } from '../../utils/state'

interface ToastMessage {
message: string
type: 'success' | 'warning' | 'danger'
duration?: number
id: number
}

const getColor = (type: 'success' | 'warning' | 'danger') => {
switch (type) {
case 'success':
Expand All @@ -20,7 +27,7 @@ const ANIMATION_DISAPPEAR_TIME = 2000
const MAX_FRAME: number = (ANIMATION_DISAPPEAR_TIME / 1000) * 40 // suppose fps = 40
const DEFAULT_TOAST_DURATION = 3000

const ToastItem = ({ data, willLeave }: { data: State.ToastMessage; willLeave: Function }) => {
const ToastItem = ({ data, willLeave }: { data: ToastMessage; willLeave: Function }) => {
const [opacity, setOpacity] = useState(1)
let animationId: number = 0
useTimeoutWithUnmount(
Expand Down Expand Up @@ -60,7 +67,7 @@ const ToastItem = ({ data, willLeave }: { data: State.ToastMessage; willLeave: F
}

const initialState = {
toasts: [] as State.ToastMessage[],
toasts: [] as ToastMessage[],
toast: '',
}

Expand All @@ -74,20 +81,20 @@ const reducer = (state: any, action: any) => {
case 'REMOVE':
return {
...state,
toasts: state.toasts.filter((toast: State.ToastMessage) => toast.id !== action.payload.toast.id),
toasts: state.toasts.filter((toast: ToastMessage) => toast.id !== action.payload.toast.id),
}
default:
return state
}
}

const globalToast = createGlobalState<State.ToastMessage | null>(null)
const globalToast = createGlobalState<ToastMessage | null>(null)

export function useSetToast() {
const [, setToast] = useGlobalState(globalToast)

return useCallback(
(data: Pick<State.ToastMessage, 'message' | 'duration'> & Partial<Pick<State.ToastMessage, 'type'>>) =>
(data: Pick<ToastMessage, 'message' | 'duration'> & Partial<Pick<ToastMessage, 'type'>>) =>
setToast({
id: new Date().getTime(),
message: data.message,
Expand Down Expand Up @@ -116,7 +123,7 @@ export default () => {
return state.toasts.length === 0 ? null : (
<ToastPanel className="toast">
{state.toasts &&
state.toasts.map((item: State.ToastMessage) => (
state.toasts.map((item: ToastMessage) => (
<ToastItem
willLeave={() => {
dispatch({
Expand Down
6 changes: 3 additions & 3 deletions src/components/TransactionItem/TransactionItemCell/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ import { useBoolean, useIsMobile } from '../../../utils/hook'
import CopyTooltipText from '../../Text/CopyTooltipText'
import EllipsisMiddle from '../../EllipsisMiddle'

const isDaoDepositCell = (cellType: State.CellTypes) => cellType === 'nervos_dao_deposit'
const isDaoDepositCell = (cellType: State.Cell['cellType']) => cellType === 'nervos_dao_deposit'

const isDaoWithdrawCell = (cellType: State.CellTypes) => cellType === 'nervos_dao_withdrawing'
const isDaoWithdrawCell = (cellType: State.Cell['cellType']) => cellType === 'nervos_dao_withdrawing'

const isDaoCell = (cellType: State.CellTypes) => isDaoDepositCell(cellType) || isDaoWithdrawCell(cellType)
const isDaoCell = (cellType: State.Cell['cellType']) => isDaoDepositCell(cellType) || isDaoWithdrawCell(cellType)

const AddressTextWithAlias: FC<{
address: string
Expand Down
3 changes: 2 additions & 1 deletion src/pages/Address/AddressComp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { ReactComponent as TimeDownIcon } from '../../assets/time_down.svg'
import { ReactComponent as TimeUpIcon } from '../../assets/time_up.svg'
import { sliceNftName } from '../../utils/string'
import {
OrderByType,
useIsLGScreen,
useIsMobile,
useNewAddr,
Expand Down Expand Up @@ -317,7 +318,7 @@ export const AddressTransactions = ({
address: string
transactions: State.Transaction[]
transactionsTotal: number
timeOrderBy: State.SortOrderTypes
timeOrderBy: OrderByType
}) => {
const isMobile = useIsMobile()
const { t } = useTranslation()
Expand Down
15 changes: 3 additions & 12 deletions src/service/app/blockchain.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import { explorerService, Response } from '../../services/ExplorerService'
import { explorerService } from '../../services/ExplorerService'
import { setChainAlerts } from '../../components/Sheet'

const alertNotEmpty = (
wrapper: Response.Wrapper<State.BlockchainInfo> | null,
): wrapper is Response.Wrapper<State.BlockchainInfo> => (wrapper?.attributes.blockchainInfo.alerts.length ?? 0) > 0

const ALERT_TO_FILTER_OUT = 'CKB v0.105.* have bugs. Please upgrade to the latest version.'

export const handleBlockchainAlert = () => {
explorerService.api.fetchBlockchainInfo().then(wrapper => {
if (alertNotEmpty(wrapper)) {
setChainAlerts(
wrapper.attributes.blockchainInfo.alerts.map(alert => alert.message).filter(msg => msg !== ALERT_TO_FILTER_OUT),
)
} else {
setChainAlerts([])
}
const alerts = wrapper?.attributes.blockchainInfo.alerts ?? []
setChainAlerts(alerts.map(alert => alert.message).filter(msg => msg !== ALERT_TO_FILTER_OUT))
})
}

Expand Down
21 changes: 18 additions & 3 deletions src/services/ExplorerService/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,24 @@ export const apiFetcher = {
statistics => statistics.tipBlockNumber,
),

fetchBlockchainInfo: () => v1GetNullableWrapped<State.BlockchainInfo>('statistics/blockchain_info'),

fetchNodeVersion: () => v1GetUnwrapped<State.NodeVersion>('/nets/version'),
fetchBlockchainInfo: () =>
v1GetNullableWrapped<{
blockchainInfo: {
isInitialBlockDownload: boolean
epoch: string
difficulty: string
medianTime: string
chain: string
alerts: {
id: string
message: string
noticeNntil: string
priority: string
}[]
}
}>('statistics/blockchain_info'),

fetchNodeVersion: () => v1GetUnwrapped<{ version: string }>('/nets/version'),

fetchNervosDao: () => v1GetUnwrapped<State.NervosDao>(`contracts/nervos_dao`),

Expand Down
44 changes: 0 additions & 44 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,6 @@ declare namespace State {
hashType: string
}

export interface NodeVersion {
version: string
}

export interface ToastMessage {
message: string
type: 'success' | 'warning' | 'danger'
duration?: number
id: number
}

export interface AppError {
type: 'Network' | 'ChainAlert' | 'Maintenance'
message: string[]
}

type CellTypes = Cell['cellType']

interface UDTInfo {
symbol: string
amount: string
Expand Down Expand Up @@ -291,22 +273,6 @@ declare namespace State {
createTimestamp?: number
}

export interface BlockchainInfo {
blockchainInfo: {
isInitialBlockDownload: boolean
epoch: string
difficulty: string
medianTime: string
chain: string
alerts: {
id: string
message: string
noticeNntil: string
priority: string
}[]
}
}

export interface NervosDao {
totalDeposit: string
depositorsCount: string
Expand Down Expand Up @@ -574,14 +540,6 @@ declare namespace State {
uan?: string
}

export interface AddressState {
address: Address
transactions: Transaction[]
total: number
addressStatus: FetchStatus
transactionsStatus: FetchStatus
}

export type TransactionCsvExportType = 'address_transactions' | 'blocks' | 'udts' | 'nft'

export interface ChartColor {
Expand All @@ -593,6 +551,4 @@ declare namespace State {
secondaryIssuanceColors: string[]
liquidityColors: string[]
}

type SortOrderTypes = 'asc' | 'desc'
}
8 changes: 5 additions & 3 deletions src/utils/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,26 +182,28 @@ export function useSearchParams<T extends string>(...names: T[]): Partial<Record
return useMemo(() => getSearchParams(location.search, names), [location.search, names])
}

export type OrderByType = 'asc' | 'desc'

// REFACTOR: remove useSearchParams
export function useSortParam<T extends string>(
isSortBy: (s?: string) => boolean,
): {
sortBy: T | undefined
orderBy: State.SortOrderTypes
orderBy: OrderByType
sort?: string
handleSortClick: (sortRule?: T) => void
} {
type SortType = T | undefined
function isSortByType(s?: string): s is SortType {
return isSortBy(s) || s === undefined
}
function isOrderByType(s?: string): s is State.SortOrderTypes {
function isOrderByType(s?: string): s is OrderByType {
return s === 'asc' || s === 'desc'
}
const { sort: sortParam } = useSearchParams('sort')
const updateSearchParams = useUpdateSearchParams<'sort' | 'page'>()
let sortBy: SortType
let orderBy: State.SortOrderTypes = 'asc'
let orderBy: OrderByType = 'asc'
if (sortParam) {
const sortEntry = sortParam.split(',')[0]
const indexOfPoint = sortEntry.indexOf('.')
Expand Down

0 comments on commit 89d499d

Please sign in to comment.