Skip to content

Commit

Permalink
Refactor: Organize the code in the service to the appropriate location (
Browse files Browse the repository at this point in the history
#134)

* refactor: move the global state in the Sheet component to a more appropriate location

* refactor: code related to app settings

* refactor: implement cacheService to replace cache utils

* refactor: remove useInitApp

* feat: remove an unnecessary chain alert filter

* refactor: i18n SupportedLngs

* feat: modifiy the expiration time point of table data cached at the date level
  • Loading branch information
WhiteMinds authored Nov 7, 2023
1 parent 634d0cc commit 1147e6e
Show file tree
Hide file tree
Showing 51 changed files with 402 additions and 365 deletions.
9 changes: 9 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module.exports = {
root: true,
extends: ['airbnb', 'plugin:prettier/recommended'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'react-hooks', 'unused-imports'],
Expand Down Expand Up @@ -99,7 +100,15 @@ module.exports = {
allow: ['^.*_'],
},
],
// The service layer uses the singleton pattern, so there will be many methods that do not use this.
'class-methods-use-this': 'off',
// TODO: Perhaps @typescript-eslint/recommended should be used.
'@typescript-eslint/array-type': 'error',
'no-dupe-class-members': 'off',
'@typescript-eslint/no-dupe-class-members': 'error',
'lines-between-class-members': 'off',
// It looks like this rule has a bug, and it seems that typescript-eslint missed this rule when supporting eslint v8.
'@typescript-eslint/lines-between-class-members': 'off',
},
env: {
jest: true,
Expand Down
2 changes: 0 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { DefaultTheme, ThemeProvider } from 'styled-components'
import Routers from './routes'
import Toast from './components/Toast'
import useInitApp from './contexts/providers/hook'
import { isMainnet } from './utils/chain'
import { DASQueryContextProvider } from './contexts/providers/dasQuery'
import { getPrimaryColor, getSecondaryColor } from './constants/common'
Expand All @@ -17,7 +16,6 @@ const appStyle = {
const queryClient = new QueryClient()

const App = () => {
useInitApp()
const theme = useMemo<DefaultTheme>(
() => ({
primary: getPrimaryColor(),
Expand Down
10 changes: 0 additions & 10 deletions src/__tests__/utils/date.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
parseSimpleDate,
parseSimpleDateNoSecond,
getCurrentYear,
getCSTTime,
} from '../../utils/date'

describe('Date methods tests', () => {
Expand Down Expand Up @@ -81,13 +80,4 @@ describe('Date methods tests', () => {
MockDate.set(1588694400000)
expect(getCurrentYear()).toBe(2020)
})

it('getCSTTime', async () => {
timezoneMock.register('UTC')
expect(parseSimpleDate(1588651000000)).toBe('2020/05/05 03:56:40')
MockDate.set(1588651000000, 0)
expect(getCSTTime()).toBe(1588679800000)
timezoneMock.register('UTC')
expect(parseSimpleDate(1588679800000)).toBe('2020/05/05 11:56:40')
})
})
21 changes: 4 additions & 17 deletions src/components/Header/BlockchainComp/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ import { HeaderBlockchainPanel, MobileSubMenuPanel } from './styled'
import SimpleButton from '../../SimpleButton'
import ChainDropdown from '../../Dropdown/ChainType'
import { useIsMobile } from '../../../utils/hook'
import { ChainName, MAINNET_URL, TESTNET_URL } from '../../../constants/common'
import { ChainName, MAINNET_URL, ONE_DAY_MILLISECOND, TESTNET_URL } from '../../../constants/common'
import { explorerService } from '../../../services/ExplorerService'
import { AppCachedKeys } from '../../../constants/cache'
import { fetchCachedData, storeCachedData } from '../../../utils/cache'
import { cacheService } from '../../../services/CacheService'

const getDropdownIcon = (showDropdown: boolean) => {
if (!showDropdown) return WhiteDropdownIcon
Expand Down Expand Up @@ -123,24 +122,12 @@ export default memo(() => {
['node_version'],
async () => {
const { version } = await explorerService.api.fetchNodeVersion()
storeCachedData(AppCachedKeys.Version, `${version}&${new Date().getTime()}`)
cacheService.set<string>('node_version', version, { expireTime: ONE_DAY_MILLISECOND })
return version
},
{
keepPreviousData: true,
initialData: () => {
// version cache format: version&timestamp
const data = fetchCachedData<string>(AppCachedKeys.Version)
if (!data?.includes('&')) return undefined

const timestamp = Number(data.substring(data.indexOf('&') + 1))
const DAY_TIMESTAMP = 24 * 60 * 60 * 1000
const isStale = Date.now() - timestamp > DAY_TIMESTAMP
if (isStale) return undefined

const nodeVersion = data.substring(0, data.indexOf('&'))
return nodeVersion
},
initialData: () => cacheService.get<string>('node_version'),
},
)
const nodeVersion = query.data ?? ''
Expand Down
15 changes: 5 additions & 10 deletions src/components/Sheet/index.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import { useTranslation } from 'react-i18next'
import { useMemo } from 'react'
import { SheetPanel, SheetPointPanel, SheetItem } from './styled'
import { createGlobalState, createGlobalStateSetter, useGlobalState } from '../../utils/state'

const globalNetworkErrMsgs = createGlobalState<string[]>([])
const globalChainAlerts = createGlobalState<string[]>([])

export const setNetworkErrMsgs = createGlobalStateSetter(globalNetworkErrMsgs)
export const setChainAlerts = createGlobalStateSetter(globalChainAlerts)
import { useBlockchainAlerts, useNetworkErrMsgs } from '../../services/ExplorerService'

const Sheet = () => {
const { t } = useTranslation()
const [networkErrMsgs] = useGlobalState(globalNetworkErrMsgs)
const [chainAlerts] = useGlobalState(globalChainAlerts)
const messages: string[] = chainAlerts.concat(networkErrMsgs)
const networkErrMsgs = useNetworkErrMsgs()
const chainAlerts = useBlockchainAlerts()
const messages = useMemo<string[]>(() => [...chainAlerts, ...networkErrMsgs], [chainAlerts, networkErrMsgs])

return messages.length > 0 ? (
<SheetPanel>
Expand Down
36 changes: 0 additions & 36 deletions src/constants/cache.ts

This file was deleted.

3 changes: 3 additions & 0 deletions src/constants/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ export const PAGE_CELL_COUNT = 200
export const NEXT_HARD_FORK_EPOCH = 5414
export const EPOCH_HOURS = 4
export const ONE_DAY_SECOND = 24 * 60 * 60
export const ONE_DAY_MILLISECOND = ONE_DAY_SECOND * 1000
export const ONE_YEAR_MILLISECOND = ONE_DAY_MILLISECOND * 365
export const ONE_HOUR_SECOND = 60 * 60
export const ONE_HOUR_MILLISECOND = ONE_HOUR_SECOND * 1000
export const ONE_MINUTE_SECOND = 60
export const EPOCHS_PER_HALVING = 8760
export const THEORETICAL_EPOCH_TIME = 1000 * 60 * 60 * 4 // 4 hours
Expand Down
19 changes: 0 additions & 19 deletions src/contexts/providers/hook.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/pages/Home/AverageBlockTimeChart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import { HomeChartLink, ChartLoadingPanel } from './styled'
import ChartNoDataImage from '../../../assets/chart_no_data_white.png'
import { useChartQueryWithCache, useIsLGScreen } from '../../../utils/hook'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { ChartCachedKeys } from '../../../constants/cache'
import { ReactChartCore } from '../../StatisticsChart/common'
import { AverageBlockTimeCacheKey } from '../../StatisticsChart/block/AverageBlockTime'

const useOption = () => {
const { t } = useTranslation()
Expand Down Expand Up @@ -111,7 +111,7 @@ export default memo(() => {

const query = useChartQueryWithCache(
explorerService.api.fetchStatisticAverageBlockTimes,
ChartCachedKeys.AverageBlockTime,
AverageBlockTimeCacheKey,
'date',
)
const fullStatisticAverageBlockTimes = useMemo(() => query.data ?? [], [query.data])
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Home/HashRateChart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { HomeChartLink, ChartLoadingPanel } from './styled'
import ChartNoDataImage from '../../../assets/chart_no_data_white.png'
import { useChartQueryWithCache, useIsLGScreen } from '../../../utils/hook'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { ChartCachedKeys } from '../../../constants/cache'
import { ReactChartCore } from '../../StatisticsChart/common'
import { HashRateCacheKey } from '../../StatisticsChart/mining/HashRate'

const useOption = () => {
const { t } = useTranslation()
Expand Down Expand Up @@ -103,7 +103,7 @@ const useOption = () => {
}
export default memo(() => {
const isLG = useIsLGScreen()
const query = useChartQueryWithCache(explorerService.api.fetchStatisticHashRate, ChartCachedKeys.HashRate, 'date')
const query = useChartQueryWithCache(explorerService.api.fetchStatisticHashRate, HashRateCacheKey, 'date')
const fullStatisticHashRates = useMemo(() => query.data ?? [], [query.data])
const parseOption = useOption()

Expand Down
14 changes: 2 additions & 12 deletions src/pages/Home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,17 @@ import {
} from './styled'
import Content from '../../components/Content'
import { parseTime, parseTimeNoSecond } from '../../utils/date'
import {
BLOCK_POLLING_TIME,
BLOCKCHAIN_ALERT_POLLING_TIME,
ListPageParams,
DELAY_BLOCK_NUMBER,
} from '../../constants/common'
import { BLOCK_POLLING_TIME, ListPageParams, DELAY_BLOCK_NUMBER } from '../../constants/common'
import { localeNumberString, handleHashRate, handleDifficulty } from '../../utils/number'
import { handleBigNumber } from '../../utils/string'
import { isMainnet } from '../../utils/chain'
import LatestBlocksIcon from '../../assets/latest_blocks.png'
import LatestTransactionsIcon from '../../assets/latest_transactions.png'
import { BlockCardItem, TransactionCardItem } from './TableCard'
import Loading from '../../components/Loading/SmallLoading'
import { useElementIntersecting, useInterval, useIsLGScreen, useIsMobile } from '../../utils/hook'
import { useElementIntersecting, useIsLGScreen, useIsMobile } from '../../utils/hook'
import Banner from '../../components/Banner'
import { HalvingBanner } from '../../components/Banner/HalvingBanner'
import { handleBlockchainAlert } from '../../service/app/blockchain'
import Search from '../../components/Search'
import AverageBlockTimeChart from './AverageBlockTimeChart'
import HashRateChart from './HashRateChart'
Expand Down Expand Up @@ -233,10 +227,6 @@ export default () => {
[transactionsQuery.data?.transactions],
)

useInterval(() => {
handleBlockchainAlert()
}, BLOCKCHAIN_ALERT_POLLING_TIME)

const blockchainDataList = useBlockchainDataList(isMobile, isLG)

return (
Expand Down
3 changes: 1 addition & 2 deletions src/pages/StatisticsChart/activities/AddressBalanceRank.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { shannonToCkb, shannonToCkbDecimal } from '../../../utils/util'
import { localeNumberString } from '../../../utils/number'
import { tooltipColor, tooltipWidth, SmartChartPage, SmartChartPageProps } from '../common'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { ChartCachedKeys } from '../../../constants/cache'
import { useAdaptPCEllipsis } from '../../../utils/hook'
import { ChartColorConfig } from '../../../constants/common'

Expand Down Expand Up @@ -144,7 +143,7 @@ export const AddressBalanceRankChart = ({ isThumbnail = false }: { isThumbnail?:
onFetched={setStatisticAddressBalanceRanks}
getEChartOption={getEChartOption}
toCSV={toCSV}
cacheKey={ChartCachedKeys.AddressBalanceRank}
cacheKey="AddressBalanceRank"
cacheMode="date"
/>
)
Expand Down
3 changes: 1 addition & 2 deletions src/pages/StatisticsChart/activities/AddressCount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { DATA_ZOOM_CONFIG, assertIsArray, handleAxis } from '../../../utils/char
import { parseDateNoTime } from '../../../utils/date'
import { tooltipColor, tooltipWidth, SmartChartPage } from '../common'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { ChartCachedKeys } from '../../../constants/cache'
import { useCurrentLanguage } from '../../../utils/i18n'
import { ChartColorConfig } from '../../../constants/common'

Expand Down Expand Up @@ -109,7 +108,7 @@ export const AddressCountChart = ({ isThumbnail = false }: { isThumbnail?: boole
fetchData={explorerService.api.fetchStatisticAddressCount}
getEChartOption={useOption}
toCSV={toCSV}
cacheKey={ChartCachedKeys.AddressCount}
cacheKey="AddressCount"
cacheMode="date"
/>
)
Expand Down
7 changes: 3 additions & 4 deletions src/pages/StatisticsChart/activities/BalanceDistribution.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import BigNumber from 'bignumber.js'
import { useTranslation } from 'react-i18next'
import { LanuageType, useCurrentLanguage } from '../../../utils/i18n'
import { SupportedLng, useCurrentLanguage } from '../../../utils/i18n'
import {
DATA_ZOOM_CONFIG,
assertIsArray,
Expand All @@ -11,7 +11,6 @@ import {
} from '../../../utils/chart'
import { tooltipColor, tooltipWidth, SeriesItem, SmartChartPage } from '../common'
import { localeNumberString } from '../../../utils/number'
import { ChartCachedKeys } from '../../../constants/cache'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { ChartColorConfig } from '../../../constants/common'

Expand All @@ -22,7 +21,7 @@ const parseTooltip = ({
data,
color,
currentLanguage,
}: SeriesItem & { data: string; currentLanguage: LanuageType }): string => {
}: SeriesItem & { data: string; currentLanguage: SupportedLng }): string => {
return `<div>${tooltipColor(color)}${widthSpan(seriesName, currentLanguage)} ${localeNumberString(data)}</div>`
}

Expand Down Expand Up @@ -188,7 +187,7 @@ export const BalanceDistributionChart = ({ isThumbnail = false }: { isThumbnail?
fetchData={explorerService.api.fetchStatisticBalanceDistribution}
getEChartOption={useOption}
toCSV={toCSV}
cacheKey={ChartCachedKeys.BalanceDistribution}
cacheKey="BalanceDistribution"
cacheMode="date"
/>
)
Expand Down
7 changes: 3 additions & 4 deletions src/pages/StatisticsChart/activities/CellCount.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import BigNumber from 'bignumber.js'
import { useTranslation } from 'react-i18next'
import { LanuageType, useCurrentLanguage } from '../../../utils/i18n'
import { SupportedLng, useCurrentLanguage } from '../../../utils/i18n'
import {
DATA_ZOOM_CONFIG,
assertIsArray,
Expand All @@ -10,11 +10,10 @@ import {
} from '../../../utils/chart'
import { parseDateNoTime } from '../../../utils/date'
import { tooltipColor, tooltipWidth, SeriesItem, SmartChartPage } from '../common'
import { ChartCachedKeys } from '../../../constants/cache'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { ChartColorConfig } from '../../../constants/common'

const widthSpan = (value: string, currentLanguage: LanuageType) =>
const widthSpan = (value: string, currentLanguage: SupportedLng) =>
tooltipWidth(value, currentLanguage === 'en' ? 125 : 80)

const useTooltip = () => {
Expand Down Expand Up @@ -195,7 +194,7 @@ export const CellCountChart = ({ isThumbnail = false }: { isThumbnail?: boolean
fetchData={explorerService.api.fetchStatisticCellCount}
getEChartOption={useOption}
toCSV={toCSV}
cacheKey={ChartCachedKeys.CellCount}
cacheKey="CellCount"
cacheMode="date"
/>
)
Expand Down
3 changes: 1 addition & 2 deletions src/pages/StatisticsChart/activities/TransactionCount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useTranslation } from 'react-i18next'
import { DATA_ZOOM_CONFIG, assertIsArray, handleAxis } from '../../../utils/chart'
import { parseDateNoTime } from '../../../utils/date'
import { tooltipColor, tooltipWidth, SmartChartPage } from '../common'
import { ChartCachedKeys } from '../../../constants/cache'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { useCurrentLanguage } from '../../../utils/i18n'
import { ChartColorConfig } from '../../../constants/common'
Expand Down Expand Up @@ -107,7 +106,7 @@ export const TransactionCountChart = ({ isThumbnail = false }: { isThumbnail?: b
fetchData={explorerService.api.fetchStatisticTransactionCount}
getEChartOption={useOption}
toCSV={toCSV}
cacheKey={ChartCachedKeys.TransactionCount}
cacheKey="TransactionCount"
cacheMode="date"
/>
)
Expand Down
3 changes: 1 addition & 2 deletions src/pages/StatisticsChart/activities/TxFeeHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { parseDateNoTime } from '../../../utils/date'
import { tooltipColor, tooltipWidth, SmartChartPage } from '../common'
import { shannonToCkbDecimal } from '../../../utils/util'
import { isMainnet } from '../../../utils/chain'
import { ChartCachedKeys } from '../../../constants/cache'
import { ChartItem, explorerService } from '../../../services/ExplorerService'
import { useCurrentLanguage } from '../../../utils/i18n'
import { ChartColorConfig } from '../../../constants/common'
Expand Down Expand Up @@ -113,7 +112,7 @@ export const TxFeeHistoryChart = ({ isThumbnail = false }: { isThumbnail?: boole
fetchData={explorerService.api.fetchStatisticTxFeeHistory}
getEChartOption={useOption}
toCSV={toCSV}
cacheKey={ChartCachedKeys.TransactionFee}
cacheKey="TransactionFee"
cacheMode="date"
/>
)
Expand Down
Loading

1 comment on commit 1147e6e

@vercel
Copy link

@vercel vercel bot commented on 1147e6e Nov 7, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.