Skip to content

Commit

Permalink
fix: 修复切换问题
Browse files Browse the repository at this point in the history
1. 修复「全国、全球」按钮切换
2. 修复页面切换
  • Loading branch information
XYShaoKang committed Sep 21, 2024
1 parent 6a6d81e commit 49f03fe
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 48 deletions.
12 changes: 4 additions & 8 deletions src/content/pages/ranking/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,21 +58,17 @@ const LegacyApp: FC = () => {
})
).unwrap()
const userInfos = res.total_rank.map(a => {
if (a.data_region.toLocaleLowerCase() === 'cn') {
return {
region: a.data_region,
username: a.user_slug,
}
}
return {
region: a.data_region,
username: a.username,
username: a.user_slug,
oldUsername: a.username,
}
})
if (hasMyRank) {
userInfos.unshift({
region: 'CN',
username: (window as any).LeetCodeData.userStatus.username,
username: (window as any).LeetCodeData.userStatus.user_slug,
oldUsername: (window as any).LeetCodeData.userStatus.username,
})
}
setUserInfos(userInfos)
Expand Down
19 changes: 8 additions & 11 deletions src/content/pages/ranking/BetaApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const BetaApp: FC = () => {
const options = useAppSelector(selectOptions)
const [titleRoot, setTitleRoot] = useState<HTMLElement>()
const [rows, setRows] = useState<HTMLElement[]>()
const [param] = useUrlChange()
const [param] = useUrlChange(true)
const dispatch = useAppDispatch()
const hasMyRank = !!rows?.[0]?.parentElement?.className.includes(
'from-ranking-primary'
Expand All @@ -45,15 +45,10 @@ export const BetaApp: FC = () => {
).unwrap()

const userInfos = res.total_rank.map(a => {
if (a.data_region.toLocaleLowerCase() === 'cn') {
return {
region: a.data_region,
username: a.user_slug,
}
}
return {
region: a.data_region,
username: a.username,
username: a.user_slug,
oldUsername: a.username,
}
})
if (hasMyRank) {
Expand All @@ -63,6 +58,7 @@ export const BetaApp: FC = () => {
userInfos.unshift({
region: 'CN',
username,
oldUsername: username,
})
}
setUserInfos(userInfos)
Expand All @@ -75,8 +71,6 @@ export const BetaApp: FC = () => {

useEffectMount(async state => {
const handleChange = debounce(async () => {
// const parent = await findElement('.table-responsive>table>thead>tr')
// console.log('handleChange')
const el = await findElementByXPath(
'//*[@id="__next"]//div[text()="用户名"]',
el => {
Expand All @@ -103,14 +97,17 @@ export const BetaApp: FC = () => {
.children as unknown as HTMLElement[]
if (state.isMount) {
setTitleRoot(trs[0])
// console.log([...trs].slice(1).map(a=>a.children[0]))
setRows([...trs].slice(1).map(a => a.children[0]) as HTMLElement[])
}
}
}, 100)
handleChange()

window.addEventListener('urlchange', handleChange)
const el = await findElementByXPath(
'//*[@id="__next"]//button[text()="全国"]'
)
el.parentElement!.addEventListener('click', handleChange)
}, [])

useEffect(() => {
Expand Down
64 changes: 45 additions & 19 deletions src/content/pages/ranking/Item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { css } from 'styled-components/macro'
import { debounce } from 'src/utils'

import { selectUserPredict, selectContestInfo } from './rankSlice'
import { findElementByXPath } from '@/utils'

type ItmeType = {
contestSlug: string
Expand All @@ -25,24 +26,38 @@ export type PageParamType = {
region: 'local' | 'global'
}

function getParam(): PageParamType {
function getParam(beta?: boolean): PageParamType {
const [, contestId, , pageStr = '1'] = location.pathname
.split('/')
.filter(Boolean)
const page = Number(pageStr)
const checkbox = document.querySelector(
'.checkbox>label>input'
) as HTMLInputElement
const region = checkbox?.checked ? 'global' : 'local'
let region: 'local' | 'global' = 'local'
if (beta) {
const btn = document.evaluate(
'//*[@id="__next"]//button[text()="全国"]',
document,
null,
XPathResult['FIRST_ORDERED_NODE_TYPE'],
null
).singleNodeValue as HTMLButtonElement
if (btn && btn.dataset.state !== 'active') {
region = 'global'
}
} else {
const checkbox = document.querySelector(
'.checkbox>label>input'
) as HTMLInputElement
region = checkbox?.checked ? 'global' : 'local'
}

return { contestId, page, region }
}

export function useUrlChange(): [PageParamType] {
const [param, setParam] = useState(getParam())
export function useUrlChange(beta?: boolean): [PageParamType] {
const [param, setParam] = useState(getParam(beta))
useEffectMount(state => {
const handle = debounce(() => {
if (state.isMount) setParam(getParam())
if (state.isMount) setParam(getParam(beta))
}, 100)
window.addEventListener('urlchange', handle)
state.unmount.push(() => {
Expand All @@ -51,19 +66,30 @@ export function useUrlChange(): [PageParamType] {
})
}, [])
// 是否选中「显示全球」
useEffectMount(state => {
const checkbox = document.querySelector(
'.checkbox>label>input'
) as HTMLInputElement
if (!checkbox) return
useEffectMount(async state => {
const handle = debounce((_e: Event) => {
if (state.isMount) setParam(getParam())
if (state.isMount) setParam(getParam(beta))
}, 100)
checkbox.addEventListener('change', handle)
state.unmount.push(() => {
handle.cancel()
checkbox.removeEventListener('change', handle)
})
if (beta) {
const el = await findElementByXPath(
'//*[@id="__next"]//button[text()="全国"]'
)
el.parentElement!.addEventListener('click', handle)
state.unmount.push(() => {
handle.cancel()
el.parentElement!.removeEventListener('change', handle)
})
} else {
const checkbox = document.querySelector(
'.checkbox>label>input'
) as HTMLInputElement
if (!checkbox) return
checkbox.addEventListener('change', handle)
state.unmount.push(() => {
handle.cancel()
checkbox.removeEventListener('change', handle)
})
}
})
return [param]
}
Expand Down
14 changes: 11 additions & 3 deletions src/content/pages/ranking/Predict.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const PredictItem = memo(function PredictItem({
...props
}: PredictItemProps) {
const { username, region } = useUser(hasMyRank, index, row, beta)
const [{ contestId: contestSlug }] = useUrlChange()
const [{ contestId: contestSlug }] = useUrlChange(beta)

return (
<Item
Expand All @@ -52,12 +52,20 @@ const Predict = memo(function Predict({
userInfos,
...props
}: PredictProps) {
const [{ contestId }] = useUrlChange()
const [{ contestId }] = useUrlChange(props.beta)
const options = useAppSelector(selectOptions)

const dispatch = useAppDispatch()
useEffect(() => {
dispatch(fetchPrediction({ contestSlug: contestId, users: userInfos }))
dispatch(
fetchPrediction({
contestSlug: contestId,
users: userInfos.map(a => ({
region: a.region,
username: a.oldUsername!,
})),
})
)
}, [dispatch, contestId, JSON.stringify(userInfos)])

const showPredict = !!options?.contestRankingPage.showPredict
Expand Down
4 changes: 2 additions & 2 deletions src/content/pages/ranking/RealTimePredict.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const RealTimePredictItem: FC<RealTimePredictItemProps> = ({
...props
}) => {
const { username, region } = useUser(hasMyRank, index, row, beta)
const [{ contestId: contestSlug }] = useUrlChange()
const [{ contestId: contestSlug }] = useUrlChange(beta)

usePredict({
username,
Expand Down Expand Up @@ -55,7 +55,7 @@ export const RealTimePredict: FC<RealTimePredictProps> = ({
hasMyRank,
...props
}) => {
const [{ contestId: contestSlug }] = useUrlChange()
const [{ contestId: contestSlug }] = useUrlChange(props.beta)
useFetchPreviousRatingData(contestSlug)

const borderColor = props.beta ? '#888' : '#ddd'
Expand Down
9 changes: 4 additions & 5 deletions src/content/pages/ranking/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
selectFetchContestRankingState,
} from './rankSlice'

export type User = { region: string; username: string }
export type User = { region: string; username: string; oldUsername?: string }

/** 获取当前行的用户信息
*
Expand All @@ -43,11 +43,10 @@ export function getUsername(
const a = row.children[0].children[0].children[0] as HTMLAnchorElement
if (a.host === 'leetcode.com') {
region = 'US'
username = a.pathname.split('/').filter(Boolean)[0]
} else {
region = 'CN'
username = a.pathname.split('/').filter(Boolean)[1]
}
username = a.pathname.split('/').filter(Boolean)[1]
} else {
const a = row.children[1].children[0] as HTMLAnchorElement
if (a.host === 'leetcode.com') {
Expand All @@ -72,13 +71,13 @@ export const useRowChange = (
useEffect(() => {
const handleChange = debounce(() => {
onChange()
}, 10)
}, 100)
handleChange()
const observer = new MutationObserver(handleChange)
const a = beta
? row.children[0].children[0].children[0].children[0]
: row.children[1].children[0]
observer.observe(a, { attributes: true })
observer.observe(a, { attributes: true, childList: true })
return () => {
handleChange.cancel()
observer.disconnect()
Expand Down

0 comments on commit 49f03fe

Please sign in to comment.