Skip to content

Commit

Permalink
feat: sort messages by priority
Browse files Browse the repository at this point in the history
  • Loading branch information
alfetopito committed Dec 17, 2024
1 parent 001aa98 commit 35fb182
Showing 1 changed file with 34 additions and 10 deletions.
44 changes: 34 additions & 10 deletions apps/cowswap-frontend/src/common/hooks/useAnnouncements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,43 @@ function useAnnouncements(chainId: SupportedChainId): Announcements {
return useMemo(() => {
const env = isProdLike ? 'prod' : 'staging' // Should match what's set on CMS!

return allAnnouncements.reduce<Announcements>((acc, announcement) => {
const showForEveryChain = announcement.chainIds.length === 0
const showForEveryEnv = announcement.envs.length === 0
return allAnnouncements
.filter((announcement) => {
const showForEveryChain = announcement.chainIds.length === 0
const showForEveryEnv = announcement.envs.length === 0

const matchesChainId = announcement.chainIds.some((announcementChain) => announcementChain === chainId)
const matchesEnv = announcement.envs.some((announcementEnv) => announcementEnv === env)
const matchesChainId = announcement.chainIds.some((announcementChain) => announcementChain === chainId)
const matchesEnv = announcement.envs.some((announcementEnv) => announcementEnv === env)

if ((showForEveryChain || matchesChainId) && (showForEveryEnv || matchesEnv)) {
acc[chainId] = announcement
}
return (showForEveryChain || matchesChainId) && (showForEveryEnv || matchesEnv)
})
.sort((a, b) => {
// A bit of duplication, yes, but this is to sort the filtered results and have some priority:
// 1. first the most specific, with chain and env set
// 2. second the ones with chain and any env
// 3. third the ones with env and any chain
// 4. lastly, the ones with any chain and any env

return acc
}, [])
const showForEveryChainA = a.chainIds.length === 0
const showForEveryEnvA = a.envs.length === 0
const matchesChainIdA = a.chainIds.some((announcementChain) => announcementChain === chainId)
const matchesEnvA = a.envs.some((announcementEnv) => announcementEnv === env)

const showForEveryChainB = b.chainIds.length === 0
const showForEveryEnvB = b.envs.length === 0
const matchesChainIdB = b.chainIds.some((announcementChain) => announcementChain === chainId)
const matchesEnvB = b.envs.some((announcementEnv) => announcementEnv === env)

if (matchesChainIdA && matchesEnvA) return -1
if (matchesChainIdB && matchesEnvB) return 1
if (matchesChainIdA && showForEveryEnvA) return -1
if (matchesChainIdB && showForEveryEnvB) return 1
if (showForEveryChainA && matchesEnvA) return -1
if (showForEveryChainB && matchesEnvB) return 1
if (showForEveryChainA && showForEveryEnvA) return -1
if (showForEveryChainB && showForEveryEnvB) return 1
return 0
})
}, [chainId, allAnnouncements])
}

Expand Down

0 comments on commit 35fb182

Please sign in to comment.