Skip to content

Commit

Permalink
Network in query string (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tbaut authored Sep 10, 2024
1 parent 7f66c44 commit 692497d
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 38 deletions.
5 changes: 3 additions & 2 deletions src/components/DelegateCard.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { useNavigate } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { Delegate } from '@/contexts/DelegatesContext'
import { ContentReveal } from './ui/content-reveal'
Expand All @@ -11,6 +11,7 @@ interface Props {
export const DelegateCard = ({ delegate: d }: Props) => {
const [copied, setCopied] = useState<boolean>(false)
const navigate = useNavigate()
const { search } = useLocation()

useEffect(() => {
if (copied) {
Expand All @@ -19,7 +20,7 @@ export const DelegateCard = ({ delegate: d }: Props) => {
}, [copied])

const onDelegate = () => {
navigate(`/delegate/${d.address}`)
navigate(`/delegate/${d.address}${search}`)
}

return (
Expand Down
7 changes: 3 additions & 4 deletions src/contexts/DelegatesContext.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState } from 'react'
import { useNetwork } from './NetworkContext'
import { DelegeeListKusama, DelegeeListPolkadot } from '@/lib/constants'
// import { dotApi } from '@/clients'
import { DelegateListKusama, DelegateListPolkadot } from '@/lib/constants'

type DelegatesContextProps = {
children: React.ReactNode | React.ReactNode[]
Expand Down Expand Up @@ -33,8 +32,8 @@ const DelegateContextProvider = ({ children }: DelegatesContextProps) => {
const response = await (
await fetch(
network === 'polkadot' || network === 'polkadot-lc'
? DelegeeListPolkadot
: DelegeeListKusama,
? DelegateListPolkadot
: DelegateListKusama,
)!
).json()
setDelegates(response)
Expand Down
58 changes: 49 additions & 9 deletions src/contexts/NetworkContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState } from 'react'
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from 'react'
import { dot, fastWestend, ksm, westend } from '@polkadot-api/descriptors'
import {
ChainDefinition,
Expand All @@ -16,8 +22,9 @@ import { startFromWorker } from 'polkadot-api/smoldot/from-worker'
import { getChainInformation } from '@/lib/utils'
import { AssetType } from '@/lib/types'
import networks from '@/assets/networks.json'
import { SELECTED_NETWORK_KEY } from '@/lib/constants'
import { DEFAULT_NETWORK, SELECTED_NETWORK_KEY } from '@/lib/constants'
import { useLocalStorage } from 'usehooks-ts'
import { useSearchParams } from 'react-router-dom'

type NetworkContextProps = {
children: React.ReactNode | React.ReactNode[]
Expand All @@ -43,14 +50,19 @@ export type TrackList = Record<number, string>
export interface INetworkContext {
lightClientLoaded: boolean
isLight: boolean
setNetwork: React.Dispatch<React.SetStateAction<SupportedNetworkNames>>
selectNetwork: (network: string, shouldResetAccountAddress?: boolean) => void
client: PolkadotClient | undefined
api: TypedApi<typeof dot | typeof ksm> | undefined
network: SupportedNetworkNames
network?: SupportedNetworkNames
assetInfo: AssetType
trackList: TrackList
}

const isSupportedNetwork = (
network: string,
): network is SupportedNetworkNames =>
!!descriptorName[network as SupportedNetworkNames]

const NetworkContext = createContext<INetworkContext | undefined>(undefined)

const NetworkContextProvider = ({ children }: NetworkContextProps) => {
Expand All @@ -66,15 +78,43 @@ const NetworkContextProvider = ({ children }: NetworkContextProps) => {
const [trackList, setTrackList] = useState<TrackList>({})

const [assetInfo, setAssetInfo] = useState<AssetType>({} as AssetType)
const [network, setNetwork] = useState<SupportedNetworkNames>(
(localStorageNetwork as SupportedNetworkNames) || 'polkadot',
const [network, setNetwork] = useState<SupportedNetworkNames | undefined>()
const [searchParams, setSearchParams] = useSearchParams({ network: '' })

const selectNetwork = useCallback(
(network: string) => {
if (!isSupportedNetwork(network)) {
console.error('This network is not supported', network)
selectNetwork(DEFAULT_NETWORK)
return
}

setNetwork(network)
setSearchParams((prev) => {
prev.set('network', network)
return prev
})
setLocalStorageNetwork(network)
},
[setLocalStorageNetwork, setSearchParams],
)

useEffect(() => {
setLocalStorageNetwork(network)
}, [network, setLocalStorageNetwork])
if (!network) {
const queryStringNetwork = searchParams.get('network')

// in this order we prefer the network in query string
// or the local storage or the default
const selected =
queryStringNetwork || localStorageNetwork || DEFAULT_NETWORK

selectNetwork(selected)
}
}, [localStorageNetwork, network, searchParams, selectNetwork])

useEffect(() => {
if (!network) return

let client: PolkadotClient

if (network === 'polkadot-lc' || network === 'kusama-lc') {
Expand Down Expand Up @@ -142,7 +182,7 @@ const NetworkContextProvider = ({ children }: NetworkContextProps) => {
lightClientLoaded,
isLight,
network,
setNetwork,
selectNetwork,
client,
api,
assetInfo,
Expand Down
9 changes: 5 additions & 4 deletions src/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { useAccounts } from './contexts/AccountsContext'
import { useEffect, useState } from 'react'
import { SupportedNetworkNames, useNetwork } from './contexts/NetworkContext'
import { useTheme } from './components/theme-provider'
import { Link } from 'react-router-dom'
import { Link, useLocation } from 'react-router-dom'
import { FaCheckCircle, FaGithub } from 'react-icons/fa'
import { TbLoaderQuarter } from 'react-icons/tb'

Expand All @@ -49,12 +49,13 @@ if (import.meta.env.DEV) {
}

export const Header = () => {
const { network, setNetwork, lightClientLoaded, isLight } = useNetwork()
const { network, selectNetwork, lightClientLoaded, isLight } = useNetwork()
const { accounts, selectAccount, selectedAccount } = useAccounts()
const [, disconnectAll] = useWalletDisconnector()
const [isConnectionDialiogOpen, setIsConnectionDialiogOpen] = useState(false)
// eslint-disable-next-line
const { theme, setTheme } = useTheme()
const { search } = useLocation()

useEffect(() => {
if (!selectedAccount?.address && accounts.length > 0) {
Expand All @@ -77,7 +78,7 @@ export const Header = () => {
{routes.map((r) => (
<Link
key={r.name}
to={`/${r.link || ''}`}
to={`/${r.link || ''}${search}`}
className="flex items-center gap-4 px-2.5 text-muted-foreground hover:text-foreground"
>
<r.icon className="h-5 w-5" />
Expand Down Expand Up @@ -155,7 +156,7 @@ export const Header = () => {
<DropdownMenuItem
className="cursor-pointer"
key={name}
onClick={() => setNetwork(name)}
onClick={() => selectNetwork(name)}
>
{display}
</DropdownMenuItem>
Expand Down
20 changes: 6 additions & 14 deletions src/lib/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export const THEME_KEY = 'delegit.theme'
export const SELECTED_ACCOUNT_KEY = 'delegit.selectedAccount'
export const SELECTED_NETWORK_KEY = 'delegit.selectedNetwork'

export const DEFAULT_NETWORK = 'polkadot'

const THRESHOLD = BigInt(500)
const DEFAULT_TIME = BigInt(6000)
const ONE_DAY = BigInt(24 * 60 * 60 * 1000)
Expand All @@ -23,17 +25,11 @@ const lockPeriod: Record<string, number> = {
Locked6x: 32,
}

const AppVersion = '0.1.1'
const DappName = 'Delegit'
const SiteUrl = 'https://delegit.xyz'

const DelegeeListPolkadot =
const DelegateListPolkadot =
'https://raw.githubusercontent.com/novasamatech/opengov-delegate-registry/master/registry/polkadot.json'
const DelegeeListKusama =
const DelegateListKusama =
'https://raw.githubusercontent.com/novasamatech/opengov-delegate-registry/master/registry/kusama.json'

const GithubOwner = 'delegit-xyz'

const msgs: Record<string, MsgType> = {
api: {
title: 'API Error.',
Expand All @@ -55,12 +51,8 @@ export {
DEFAULT_TIME,
ONE_DAY,
lockPeriod,
AppVersion,
DappName,
SiteUrl,
DelegeeListPolkadot,
DelegeeListKusama,
GithubOwner,
DelegateListPolkadot,
DelegateListKusama,
// Alert messsages
msgs,
}
7 changes: 5 additions & 2 deletions src/navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const linkStyle = (pathname: string, link: string) => {

export const Navigation = () => {
const { lightClientLoaded, isLight } = useNetwork()
const { pathname } = useLocation()
const { pathname, search } = useLocation()
const { theme, setTheme } = useTheme()

return (
Expand All @@ -46,7 +46,10 @@ export const Navigation = () => {
return (
<Tooltip key={r.name}>
<TooltipTrigger asChild>
<Link to={link} className={linkStyle(pathname, link)}>
<Link
to={`${link}${search}`}
className={linkStyle(pathname, link)}
>
<r.icon className="h-5 w-5" />
<span className="sr-only">{r.name}</span>
</Link>
Expand Down
7 changes: 4 additions & 3 deletions src/pages/Delegate/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SetStateAction, useEffect, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { useAccounts } from '@/contexts/AccountsContext'
import { Slider } from '@/components/ui/slider'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'

import { ArrowLeft } from 'lucide-react'
import { msgs } from '@/lib/constants'
Expand Down Expand Up @@ -37,6 +37,7 @@ export const Delegate = () => {
const [isTxInitiated, setIsTxInitiated] = useState(false)
const getDelegateTx = useGetDelegateTx()
const navigate = useNavigate()
const { search } = useLocation()

const { display: convictionTimeDisplay, multiplier: convictionMultiplier } =
getConvictionLockTimeDisplay(convictionNo)
Expand Down Expand Up @@ -122,7 +123,7 @@ export const Delegate = () => {
}

if (event.type === 'finalized') {
navigate('/')
navigate(`/${search}`)
setIsTxInitiated(false)
}
})
Expand All @@ -148,7 +149,7 @@ export const Delegate = () => {
/>
)}

<Link to="/home" className="flex items-center gap-2 text-primary">
<Link to={`/${search}`} className="flex items-center gap-2 text-primary">
<ArrowLeft className="h-4 w-4" />
To all delegates
</Link>
Expand Down

0 comments on commit 692497d

Please sign in to comment.