From b2fc404159f537eda948584d9b47b04e7d98df0d Mon Sep 17 00:00:00 2001 From: Sebastian G Date: Wed, 18 Nov 2026 08:31:43 +0100 Subject: [PATCH] feat: fix global ABI at 5% and simplify page banners - Replace computed global ABI with configurable FIXED_ABI_PCT remove unused ABI calculation hooks, server action and /api/metrics/abi/context route - Position simulator shows ABI and RIF figures without waiting for RIF price - Make page banners and the Collective Possibilities banner non-dismissible - Add compact layout for title-only page banners --- src/app/api/metrics/abi/context/route.ts | 60 ---------- src/app/backing/BackingPage.tsx | 2 +- src/app/btc-vault/BtcVaultPage.tsx | 2 +- .../BuildersBanner/BuildersBanner.test.tsx | 9 -- .../BuildersBanner/BuildersBanner.tsx | 1 - .../components/Table/BuildersTableTitle.tsx | 10 +- .../CollectiveRewardsPage.tsx | 2 +- .../DashboardMetrics/DashboardMetrics.tsx | 3 +- .../PositionSimulator/PositionSimulator.tsx | 3 +- .../RewardsActionsSection.tsx | 3 +- .../shared/actions/fetchABIData.ts | 78 ------------- .../shared/hooks/getCyclePayout.ts | 23 ---- .../collective-rewards/shared/hooks/index.ts | 3 - .../shared/hooks/useGetABI.ts | 104 +----------------- .../shared/hooks/useGetABIFromChain.ts | 80 -------------- .../shared/hooks/useGetABIWithGraph.ts | 26 ----- .../shared/hooks/useGetABIWithStateSync.ts | 48 -------- .../CommunitiesBanner/CommunitiesBanner.tsx | 2 +- .../DelegationBanner/DelegationBanner.tsx | 2 +- .../DelegationDetailsSection.tsx | 2 +- .../MyRewardsBanner/MyRewardsBanner.test.tsx | 20 +--- .../MyRewardsBanner/MyRewardsBanner.tsx | 1 - .../ProposalsBanner/ProposalsBanner.test.tsx | 11 +- .../ProposalsBanner/ProposalsBanner.tsx | 1 - .../AnnualBackerIncentivesLoader.tsx | 29 +---- .../TreasuryBanner/TreasuryBanner.tsx | 2 +- .../CollectivePossibilities.test.tsx | 84 +------------- .../CollectivePossibilities.tsx | 71 +----------- .../PossibilitiesDock.tsx | 15 +-- .../CollectivePossibilities/constants.ts | 1 - .../CollectivePossibilities/useScrollDock.ts | 7 +- .../collective-balances-section/index.tsx | 6 +- src/app/user/latest-collective/index.tsx | 6 +- .../my-holdings/MyActivityAndBalances.tsx | 8 +- src/app/vault/VaultPage.tsx | 2 +- .../DismissButton/DismissButton.tsx | 6 +- .../PageBanner/BannerDecorativeSquares.tsx | 31 ------ src/components/PageBanner/PageBanner.test.tsx | 45 ++------ src/components/PageBanner/PageBanner.tsx | 47 ++------ src/components/PageBanner/PageTitle.test.tsx | 3 +- src/components/PageBanner/PageTitle.tsx | 15 +-- src/components/PageBanner/index.ts | 1 - .../PersistedCollapsible.test.tsx | 5 +- .../PersistedCollapsible.tsx | 13 +-- src/lib/constants.ts | 7 +- src/proxy.test.ts | 2 - src/proxy.ts | 4 +- 47 files changed, 78 insertions(+), 828 deletions(-) delete mode 100644 src/app/api/metrics/abi/context/route.ts delete mode 100644 src/app/collective-rewards/shared/actions/fetchABIData.ts delete mode 100644 src/app/collective-rewards/shared/hooks/getCyclePayout.ts delete mode 100644 src/app/collective-rewards/shared/hooks/useGetABIFromChain.ts delete mode 100644 src/app/collective-rewards/shared/hooks/useGetABIWithGraph.ts delete mode 100644 src/app/collective-rewards/shared/hooks/useGetABIWithStateSync.ts delete mode 100644 src/components/PageBanner/BannerDecorativeSquares.tsx diff --git a/src/app/api/metrics/abi/context/route.ts b/src/app/api/metrics/abi/context/route.ts deleted file mode 100644 index d126e740a1..0000000000 --- a/src/app/api/metrics/abi/context/route.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { NextResponse } from 'next/server' - -import { db } from '@/lib/db' -import { logger } from '@/lib/logger' - -const DB_COMMAND_COALESCE = ` - COALESCE( - json_build_object( - 'next', "BackerRewardPercentage"."next"::text, - 'previous', "BackerRewardPercentage"."previous"::text, - 'cooldownEndTime', "BackerRewardPercentage"."cooldownEndTime"::text - ), - '{}' - ) -` - -export async function GET() { - try { - const [builders, cycles] = await Promise.all([ - db('Builder') - .join('BuilderState', 'Builder.id', '=', 'BuilderState.builder') - .join('BackerRewardPercentage', 'Builder.id', '=', 'BackerRewardPercentage.builder') - .select({ address: 'Builder.id' }, 'Builder.totalAllocation', { - backerRewardPct: db.raw(DB_COMMAND_COALESCE), - stateFlags: db.raw(` - COALESCE( - json_build_object( - 'initialized', "BuilderState"."initialized", - 'kycApproved', "BuilderState"."kycApproved", - 'communityApproved', "BuilderState"."communityApproved", - 'kycPaused', "BuilderState"."kycPaused", - 'selfPaused', "BuilderState"."selfPaused" - ), - '{}' - ) - `), - }) - .where('BuilderState.initialized', '=', true) - .orderByRaw('"Builder"."totalAllocation"::numeric DESC'), - db('Cycle') - .select('Cycle.id') - .select({ - rewardPerToken: db.raw(` - COALESCE( - json_object_agg(convert_from("CycleRewardPerToken"."token", 'utf8'), "CycleRewardPerToken"."amount"::text), - '{}' - ) - `), - }) - .innerJoin('CycleRewardPerToken', 'Cycle.id', '=', 'CycleRewardPerToken.cycle') - .orderBy('currentCycleStart', 'desc') - .groupBy('Cycle.id'), - ]) - - return NextResponse.json({ builders, cycles }) - } catch (err) { - logger.error({ err, route: '/api/metrics/abi/context' }, 'Database error') - return NextResponse.json({ error: 'Database error' }, { status: 500 }) - } -} diff --git a/src/app/backing/BackingPage.tsx b/src/app/backing/BackingPage.tsx index 311411f5f4..50fbc217b7 100644 --- a/src/app/backing/BackingPage.tsx +++ b/src/app/backing/BackingPage.tsx @@ -175,7 +175,7 @@ export const BackingPage = () => { return (
- + {!hasAllocations && (
{ data-testid={NAME} // TODO: DAO-2029 Standardize data-test-ids to using kebab-case only className="flex flex-col items-start w-full h-full gap-6 rounded-sm" > - + {/* Active Request Zone - F7 (STORY-EPIC-7-001) */} diff --git a/src/app/builders/components/BuildersBanner/BuildersBanner.test.tsx b/src/app/builders/components/BuildersBanner/BuildersBanner.test.tsx index 35ff8ae8b3..5d8a895025 100644 --- a/src/app/builders/components/BuildersBanner/BuildersBanner.test.tsx +++ b/src/app/builders/components/BuildersBanner/BuildersBanner.test.tsx @@ -33,13 +33,4 @@ describe('BuildersBanner', () => { fireEvent.click(screen.getByTestId('ApplyForGrantButton')) expect(push).toHaveBeenCalledWith('/proposals/new?type=Grants') }) - - it('hides the banner when dismissed, without persisting the choice', () => { - render() - - fireEvent.click(screen.getByTestId('DismissBannerButton')) - - expect(screen.queryByTestId('BuildersBanner')).not.toBeInTheDocument() - expect(Object.keys(localStorage)).toHaveLength(0) - }) }) diff --git a/src/app/builders/components/BuildersBanner/BuildersBanner.tsx b/src/app/builders/components/BuildersBanner/BuildersBanner.tsx index 9c081230f4..5c84a56297 100644 --- a/src/app/builders/components/BuildersBanner/BuildersBanner.tsx +++ b/src/app/builders/components/BuildersBanner/BuildersBanner.tsx @@ -12,7 +12,6 @@ export const BuildersBanner = ({ className }: CommonComponentProps) => { return ( -
- -
- All Builders -
-
+
+ All Builders +
{isDesktop ? ( (
- +
diff --git a/src/app/collective-rewards/components/DashboardMetrics/DashboardMetrics.tsx b/src/app/collective-rewards/components/DashboardMetrics/DashboardMetrics.tsx index 3724a51e0e..c7e33e7b1e 100644 --- a/src/app/collective-rewards/components/DashboardMetrics/DashboardMetrics.tsx +++ b/src/app/collective-rewards/components/DashboardMetrics/DashboardMetrics.tsx @@ -23,8 +23,7 @@ export const DashboardMetrics = ({ className }: { className?: string }) => { paidAllTime={paidAllTime} buildersCount={buildersCount} strifPrice={strifPrice} - // `useGetABI` yields 0, not "loading", while the RIF price is still missing. - isLoading={isLoading || isAbiLoading || !prices[RIF]?.price} + isLoading={isLoading || isAbiLoading} className={className} /> )} diff --git a/src/app/collective-rewards/components/PositionSimulator/PositionSimulator.tsx b/src/app/collective-rewards/components/PositionSimulator/PositionSimulator.tsx index d5c00c0444..968630e3cf 100644 --- a/src/app/collective-rewards/components/PositionSimulator/PositionSimulator.tsx +++ b/src/app/collective-rewards/components/PositionSimulator/PositionSimulator.tsx @@ -37,6 +37,7 @@ const Figure = ({ label, value, sub }: { label: string; value: string; sub: stri export interface PositionSimulatorProps { /** `null` while it loads. */ abiPct: number | null + /** USD figures show `—` while it is 0 (price not loaded yet). */ rifPrice: number className?: string } @@ -105,7 +106,7 @@ export const PositionSimulator = ({ abiPct, rifPrice, className }: PositionSimul
( )} diff --git a/src/app/collective-rewards/shared/actions/fetchABIData.ts b/src/app/collective-rewards/shared/actions/fetchABIData.ts deleted file mode 100644 index cd4e0be4cf..0000000000 --- a/src/app/collective-rewards/shared/actions/fetchABIData.ts +++ /dev/null @@ -1,78 +0,0 @@ -'use server' - -import { gql as apolloGQL } from '@apollo/client' -import { unstable_cache } from 'next/cache' - -import { CACHE_REVALIDATE_SECONDS } from '@/lib/constants' -import { client } from '@/shared/components/ApolloClient' - -import { BuilderData } from '../hooks/useGetABI' - -const query = apolloGQL` - query AbiMetricsData { - builders( - where: {state_: {initialized: true}} - orderBy: totalAllocation - orderDirection: desc - ) { - address: id - totalAllocation - backerRewardPct: backerRewardPercentage { - next - previous - cooldownEndTime - } - stateFlags: state { - communityApproved - initialized - kycApproved - kycPaused - selfPaused - } - } - cycles(orderBy: currentCycleStart, orderDirection: desc) { - id - currentCycleStart - rewardPerToken { - amount - token - } - } - } -` - -interface RewardPerToken { - amount: string - token: string -} - -interface CycleData { - id: string - currentCycleStart: number - rewardPerToken: RewardPerToken[] -} - -export interface ResponseABIData { - builders: BuilderData[] - cycles: CycleData[] -} -async function fetchABIData() { - const { data } = await client.query({ query }) - if (!data) { - throw new Error('Failed to fetch ABI data from subgraph') - } - - return { - builders: data.builders, - cycles: data.cycles.map(cycle => ({ - ...cycle, - rewardPerToken: Object.fromEntries(cycle.rewardPerToken.map(r => [r.token, r.amount])), - })), - } -} - -/** Fetches builders and reward cycles from the Collective Rewards subgraph (cached). */ -export const getCachedABIData = unstable_cache(fetchABIData, ['cached_abi_data'], { - revalidate: CACHE_REVALIDATE_SECONDS, - tags: ['cached_abi_data'], -}) diff --git a/src/app/collective-rewards/shared/hooks/getCyclePayout.ts b/src/app/collective-rewards/shared/hooks/getCyclePayout.ts deleted file mode 100644 index 7be7bc6717..0000000000 --- a/src/app/collective-rewards/shared/hooks/getCyclePayout.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { parseEther } from 'viem' - -import { WeiPerEther } from '@/lib/constants' - -export const getCyclePayout = ( - rifPrice: number, - rbtcPrice: number, - usdrifPrice: number, - rifRewards: bigint, - rbtcRewards: bigint, - usdrifRewards: bigint, -) => { - const rifPriceInWei = parseEther(rifPrice.toString()) - const rbtcPriceInWei = parseEther(rbtcPrice.toString()) - const usdrifPriceInWei = parseEther(usdrifPrice.toString()) - - const rifAmount = rifRewards ?? 0n - const rbtcAmount = rbtcRewards ?? 0n - const usdrifAmount = usdrifRewards ?? 0n - return ( - (rifAmount * rifPriceInWei + rbtcAmount * rbtcPriceInWei + usdrifAmount * usdrifPriceInWei) / WeiPerEther - ) -} diff --git a/src/app/collective-rewards/shared/hooks/index.ts b/src/app/collective-rewards/shared/hooks/index.ts index 26b194e22a..433c6130e3 100644 --- a/src/app/collective-rewards/shared/hooks/index.ts +++ b/src/app/collective-rewards/shared/hooks/index.ts @@ -1,7 +1,4 @@ export * from './useGetABI' -export * from './useGetABIFromChain' -export * from './useGetABIWithGraph' -export * from './useGetABIWithStateSync' export * from './useGetBackerABI' export * from './useGetLastCycleRewardsFromChain' export * from './useGetLastCycleRewardsWithStateSync' diff --git a/src/app/collective-rewards/shared/hooks/useGetABI.ts b/src/app/collective-rewards/shared/hooks/useGetABI.ts index eddfe3a6b4..64484d8424 100644 --- a/src/app/collective-rewards/shared/hooks/useGetABI.ts +++ b/src/app/collective-rewards/shared/hooks/useGetABI.ts @@ -1,15 +1,5 @@ -import { useMemo } from 'react' -import { Address } from 'viem' - -import { getBackerRewardPercentage } from '@/app/collective-rewards/rewards/utils/getBackerRewardPercentage' import Big from '@/lib/big' -import { ABI_CYCLES_LIMIT, CYCLES_PER_YEAR, RBTC, RIF, USDRIF, WeiPerEther } from '@/lib/constants' -import { TOKENS } from '@/lib/tokens' -import { usePricesContext } from '@/shared/context/PricesContext' - -import { BuilderStateFlags } from '../../types' -import { isBuilderRewardable } from '../../utils' -import { getCyclePayout } from './getCyclePayout' +import { CYCLES_PER_YEAR, WeiPerEther } from '@/lib/constants' export interface CycleData { id: string @@ -17,24 +7,6 @@ export interface CycleData { rewardPerToken: Record } -interface BackerRewardPercentageData { - next: string - previous: string - cooldownEndTime: string -} - -export interface BuilderData { - address: Address - backerRewardPct: BackerRewardPercentageData - totalAllocation: string - stateFlags: BuilderStateFlags -} - -export interface AbiData { - builders: BuilderData[] - cycles: CycleData[] -} - /** Per-cycle rate compounded over `CYCLES_PER_YEAR`, as a percentage. Inverse: `getCycleRateFromAbi`. */ export const calculateAbi = (rewardsPerStRif: Big, rifPrice: number): Big => { if (!rifPrice) { @@ -54,77 +26,3 @@ export const getCycleRateFromAbi = (abiPct: number | null): number | null => { return Math.pow(1 + abiPct / 100, 1 / CYCLES_PER_YEAR) - 1 } - -export const useGetABI = (abiData: AbiData | undefined) => { - const { prices } = usePricesContext() - - return useMemo(() => { - if (!abiData?.builders || !abiData.cycles?.length) { - return Big(0) - } - - const { builders, cycles } = abiData - - const rifPrice = prices[RIF]?.price ?? 0 - const rbtcPrice = prices[RBTC]?.price ?? 0 - const usdrifPrice = prices[USDRIF]?.price ?? 0 - - // Compute the average cycle payout for the last cycles (limited by ABI_CYCLES_LIMIT) - const lastCycles = cycles.slice(0, ABI_CYCLES_LIMIT) - const cyclePayout = - lastCycles.length === 0 - ? Big(0) - : lastCycles - .map(cycle => { - const rewardPerToken = cycle.rewardPerToken - return Big( - getCyclePayout( - rifPrice, - rbtcPrice, - usdrifPrice, - BigInt(rewardPerToken[TOKENS.rif.address.toLowerCase()] ?? 0n), - BigInt(rewardPerToken[TOKENS.rbtc.address.toLowerCase()] ?? 0n), - BigInt(rewardPerToken[TOKENS.usdrif.address.toLowerCase()] ?? 0n), - ).toString(), - ) - }) - .reduce((acc, payout) => acc.plus(payout), Big(0)) - .div(lastCycles.length) - - const sumTotalAllocation = builders.reduce( - (acc, builder) => acc.plus(Big(builder?.totalAllocation ?? 0)), - Big(0), - ) - - if (sumTotalAllocation.eq(0)) { - return Big(0) - } - - // We use the multiplication with the current backer rewards % to avoid losing precision - // Thats why we don't need to multiply by 100 - const top5Builders = builders.filter(b => isBuilderRewardable(b.stateFlags)).slice(0, 5) - const top5BuildersTotalAllocation = top5Builders.reduce( - (acc, { totalAllocation }) => acc.plus(Big(totalAllocation)), - Big(0), - ) - const weightedAverageBuilderRewardsPct = top5Builders.reduce( - (acc, { backerRewardPct, totalAllocation }) => { - const currentBackerRewardPercentage = backerRewardPct - ? getBackerRewardPercentage( - BigInt(backerRewardPct.previous ?? 0n), - BigInt(backerRewardPct.next ?? 0n), - BigInt(backerRewardPct.cooldownEndTime ?? 0n), - ).current.toString() - : 0 - return acc.plus( - Big(totalAllocation).mul(Big(currentBackerRewardPercentage)).div(top5BuildersTotalAllocation), - ) - }, - Big(0), - ) - - const rewardsPerStRif = cyclePayout.mul(weightedAverageBuilderRewardsPct).div(sumTotalAllocation) - - return calculateAbi(rewardsPerStRif, rifPrice) - }, [abiData, prices]) -} diff --git a/src/app/collective-rewards/shared/hooks/useGetABIFromChain.ts b/src/app/collective-rewards/shared/hooks/useGetABIFromChain.ts deleted file mode 100644 index 09964ce5a3..0000000000 --- a/src/app/collective-rewards/shared/hooks/useGetABIFromChain.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { useMemo } from 'react' - -import { filterBuildersByState, useBuilderContext } from '@/app/collective-rewards/user' -import { TOKENS } from '@/lib/tokens' -import { useReadGauges } from '@/shared/hooks/contracts' - -import { CompleteBuilder } from '../../types' -import { BuilderData, useGetABI } from './useGetABI' -import { useGetRewardDistributionRewardsLogs } from './useGetRewardsDistributionRewards' - -export const useGetABIFromChain = () => { - const { builders, isLoading: buildersLoading, error: buildersError } = useBuilderContext() - - const activeBuilders = filterBuildersByState(builders) - - const gauges = activeBuilders.map(({ gauge }) => gauge) - const { - data: totalAllocation, - isLoading: totalAllocationLoading, - error: totalAllocationError, - } = useReadGauges({ addresses: gauges, functionName: 'totalAllocation' }) - - const { - data: rewardDistributionRewardsLogs, - isLoading: rewardDistributionRewardsLogsLoading, - error: rewardDistributionRewardsLogsError, - } = useGetRewardDistributionRewardsLogs() - - const cycles = rewardDistributionRewardsLogs - .sort((a, b) => Number(b.blockNumber) - Number(a.blockNumber)) - .map(log => ({ - id: log.blockNumber.toString(), - currentCycleStart: Number(log.timeStamp), - rewardPerToken: { - [TOKENS.rif.address.toLowerCase()]: log.args.rifAmount_.toString(), - [TOKENS.rbtc.address.toLowerCase()]: log.args.nativeAmount_.toString(), - [TOKENS.usdrif.address.toLowerCase()]: log.args.usdrifAmount_.toString(), - }, - })) - - const buildersData = useMemo(() => { - return activeBuilders - .reduce>((acc, { address, backerRewardPct, stateFlags }, i) => { - const allocation = totalAllocation[i] ?? 0n - - if (!allocation || !backerRewardPct) { - return acc - } - - acc.push({ - address, - totalAllocation: allocation.toString(), - backerRewardPct: { - next: backerRewardPct.next.toString(), - previous: backerRewardPct.previous.toString(), - cooldownEndTime: backerRewardPct.cooldownEndTime.toString(), - }, - stateFlags, - }) - - return acc - }, []) - .sort((a, b) => (BigInt(b.totalAllocation) > BigInt(a.totalAllocation) ? 1 : -1)) - }, [activeBuilders, totalAllocation]) - - const isLoading = buildersLoading || rewardDistributionRewardsLogsLoading || totalAllocationLoading - - const error = buildersError ?? rewardDistributionRewardsLogsError ?? totalAllocationError - - const abi = useGetABI({ - builders: buildersData, - cycles, - }) - - return { - data: abi, - isLoading, - error, - } -} diff --git a/src/app/collective-rewards/shared/hooks/useGetABIWithGraph.ts b/src/app/collective-rewards/shared/hooks/useGetABIWithGraph.ts deleted file mode 100644 index 29e8ace63b..0000000000 --- a/src/app/collective-rewards/shared/hooks/useGetABIWithGraph.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { useQuery } from '@tanstack/react-query' - -import { AVERAGE_BLOCKTIME } from '@/lib/constants' - -import { getCachedABIData } from '../actions/fetchABIData' -import { useGetABI } from './useGetABI' - -export const useGetMetricsAbiWithGraph = () => { - const { - data: abiData, - isLoading: abiDataIsLoading, - error: abiDataError, - } = useQuery({ - queryFn: () => getCachedABIData(), - queryKey: ['abiData'], - refetchInterval: AVERAGE_BLOCKTIME, - }) - - const data = useGetABI(abiData) - - return { - data, - isLoading: abiDataIsLoading, - error: abiDataError, - } -} diff --git a/src/app/collective-rewards/shared/hooks/useGetABIWithStateSync.ts b/src/app/collective-rewards/shared/hooks/useGetABIWithStateSync.ts deleted file mode 100644 index b1857b8b94..0000000000 --- a/src/app/collective-rewards/shared/hooks/useGetABIWithStateSync.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { keepPreviousData, useQuery } from '@tanstack/react-query' -import Big from 'big.js' - -import { AVERAGE_BLOCKTIME } from '@/lib/constants' - -import { AbiData, useGetABI } from './useGetABI' -import { useStateSyncHealthCheck } from './useStateSyncHealthCheck' - -export const useGetMetricsAbiWithStateSync = () => { - const { - data: isStateSyncHealthy, - isLoading: healthCheckIsLoading, - error: healthCheckError, - } = useStateSyncHealthCheck({ - initialData: true, - }) - - const { - data: abiData, - isLoading: abiDataIsLoading, - error: abiDataError, - } = useQuery({ - queryFn: async () => { - const response = await fetch('/api/metrics/abi/context') - if (!response.ok) { - // TODO: propagate server errors - throw new Error('Failed to fetch ABI data') - } - return response.json() - }, - queryKey: ['abiData'], - refetchInterval: AVERAGE_BLOCKTIME, - placeholderData: keepPreviousData, - enabled: !healthCheckIsLoading && isStateSyncHealthy, - }) - - const data = useGetABI(abiData) - - const unhealthyStateSyncError = - (!healthCheckIsLoading && !isStateSyncHealthy && new Error('Unhealthy state sync')) || null - - const hasData = !!abiData - return { - data: hasData ? data : Big(0), - isLoading: healthCheckIsLoading || abiDataIsLoading, - error: hasData ? null : healthCheckError || abiDataError || unhealthyStateSyncError, - } -} diff --git a/src/app/communities/components/CommunitiesBanner/CommunitiesBanner.tsx b/src/app/communities/components/CommunitiesBanner/CommunitiesBanner.tsx index faae5b33eb..3107649730 100644 --- a/src/app/communities/components/CommunitiesBanner/CommunitiesBanner.tsx +++ b/src/app/communities/components/CommunitiesBanner/CommunitiesBanner.tsx @@ -4,5 +4,5 @@ import { CommonComponentProps } from '@/components/commonProps' import { PageBanner } from '@/components/PageBanner' export const CommunitiesBanner = ({ className }: CommonComponentProps) => ( - + ) diff --git a/src/app/delegate/components/DelegationBanner/DelegationBanner.tsx b/src/app/delegate/components/DelegationBanner/DelegationBanner.tsx index d9edee668e..8a59ffd09e 100644 --- a/src/app/delegate/components/DelegationBanner/DelegationBanner.tsx +++ b/src/app/delegate/components/DelegationBanner/DelegationBanner.tsx @@ -4,5 +4,5 @@ import { CommonComponentProps } from '@/components/commonProps' import { PageBanner } from '@/components/PageBanner' export const DelegationBanner = ({ className }: CommonComponentProps) => ( - + ) diff --git a/src/app/delegate/sections/DelegateContentSection/DelegationDetailsSection.tsx b/src/app/delegate/sections/DelegateContentSection/DelegationDetailsSection.tsx index 819340d9b0..6684b11d68 100644 --- a/src/app/delegate/sections/DelegateContentSection/DelegationDetailsSection.tsx +++ b/src/app/delegate/sections/DelegateContentSection/DelegationDetailsSection.tsx @@ -66,7 +66,7 @@ export const DelegationDetailsSection = ({ onShowReclaim, onShowDelegates }: Pro />
{/* Banner here with delegation perks, on the ember artwork rather than the molten - background of the page banner, which already carries the decorative squares. */} + background of the page banner. */}
{ expect(screen.getByTestId('whitepaper-link')).toHaveAttribute('href', currentLinks.rewardsWhitepaper) }) - - it('hides the banner when dismissed, without persisting the choice', () => { - render() - - fireEvent.click(screen.getByRole('button', { name: /dismiss/i })) - - expect(screen.queryByTestId('MyRewardsBanner')).not.toBeInTheDocument() - expect(Object.keys(localStorage)).toHaveLength(0) - }) - - it('comes back on the next page load', () => { - const { unmount } = render() - fireEvent.click(screen.getByRole('button', { name: /dismiss/i })) - unmount() - - render() - expect(screen.getByTestId('MyRewardsBanner')).toBeInTheDocument() - }) }) diff --git a/src/app/my-rewards/components/MyRewardsBanner/MyRewardsBanner.tsx b/src/app/my-rewards/components/MyRewardsBanner/MyRewardsBanner.tsx index d0d1ce9912..9e65361bb2 100644 --- a/src/app/my-rewards/components/MyRewardsBanner/MyRewardsBanner.tsx +++ b/src/app/my-rewards/components/MyRewardsBanner/MyRewardsBanner.tsx @@ -8,7 +8,6 @@ import { Span } from '@/components/Typography' export const MyRewardsBanner = ({ className }: CommonComponentProps) => ( { expect(screen.getByTestId('ActiveProposalsCount')).toHaveTextContent('4') expect(screen.getByTestId('TotalProposalsCount')).toHaveTextContent('910') }) - - it('hides the banner when dismissed, without persisting the choice', () => { - renderBanner() - - fireEvent.click(screen.getByTestId('DismissBannerButton')) - - expect(screen.queryByTestId('ProposalsBanner')).not.toBeInTheDocument() - expect(Object.keys(localStorage)).toHaveLength(0) - }) }) diff --git a/src/app/proposals/components/ProposalsBanner/ProposalsBanner.tsx b/src/app/proposals/components/ProposalsBanner/ProposalsBanner.tsx index 9101fefec4..38e45e851d 100644 --- a/src/app/proposals/components/ProposalsBanner/ProposalsBanner.tsx +++ b/src/app/proposals/components/ProposalsBanner/ProposalsBanner.tsx @@ -51,7 +51,6 @@ export const ProposalsBanner = ({ className, fallbackCounts }: ProposalsBannerPr return ( diff --git a/src/app/shared/components/AnnualBackersIncentivesLoader/AnnualBackerIncentivesLoader.tsx b/src/app/shared/components/AnnualBackersIncentivesLoader/AnnualBackerIncentivesLoader.tsx index 5597d9b58c..860d77e96a 100644 --- a/src/app/shared/components/AnnualBackersIncentivesLoader/AnnualBackerIncentivesLoader.tsx +++ b/src/app/shared/components/AnnualBackersIncentivesLoader/AnnualBackerIncentivesLoader.tsx @@ -1,34 +1,13 @@ import Big from 'big.js' -import { ReactNode, useMemo } from 'react' +import { ReactNode } from 'react' -import { - useGetABIFromChain, - useGetMetricsAbiWithGraph, - useGetMetricsAbiWithStateSync, -} from '@/app/collective-rewards/shared' -import { useHandleErrors } from '@/app/collective-rewards/utils' -import { withDataFallback } from '@/app/shared/components/Fallback/' -import { useFeatureFlags } from '@/shared/context/FeatureFlag' +import { FIXED_ABI_PCT } from '@/lib/constants' interface AnnualBackerIncentivesLoaderProps { render: (props: { data: Big; isLoading: boolean }) => ReactNode } -const useFallbackWithErrors = () => { - const { data, isLoading, error } = useGetABIFromChain() - useHandleErrors({ error, title: 'Error loading ABI metrics' }) - return { data, isLoading, error } -} - +/** Renders the global ABI, a fixed configurable value (`FIXED_ABI_PCT`). */ export const AnnualBackerIncentivesLoader = ({ render }: AnnualBackerIncentivesLoaderProps) => { - const { - flags: { use_state_sync }, - } = useFeatureFlags() - - // TODO: remove conditional hooks - const usePrimary = use_state_sync ? useGetMetricsAbiWithStateSync : useGetMetricsAbiWithGraph - - const Loader = useMemo(() => withDataFallback(usePrimary, useFallbackWithErrors), [usePrimary]) - - return + return <>{render({ data: Big(FIXED_ABI_PCT), isLoading: false })} } diff --git a/src/app/treasury/components/TreasuryBanner/TreasuryBanner.tsx b/src/app/treasury/components/TreasuryBanner/TreasuryBanner.tsx index fb7cb5984f..0ef5b3d5af 100644 --- a/src/app/treasury/components/TreasuryBanner/TreasuryBanner.tsx +++ b/src/app/treasury/components/TreasuryBanner/TreasuryBanner.tsx @@ -4,5 +4,5 @@ import { CommonComponentProps } from '@/components/commonProps' import { PageBanner } from '@/components/PageBanner' export const TreasuryBanner = ({ className }: CommonComponentProps) => ( - + ) diff --git a/src/app/user/components/CollectivePossibilities/CollectivePossibilities.test.tsx b/src/app/user/components/CollectivePossibilities/CollectivePossibilities.test.tsx index 175db6ba18..436332fbe9 100644 --- a/src/app/user/components/CollectivePossibilities/CollectivePossibilities.test.tsx +++ b/src/app/user/components/CollectivePossibilities/CollectivePossibilities.test.tsx @@ -5,7 +5,6 @@ import { TopBarDockProvider, useTopBarDock } from '@/components/MainContainer/To import type { ConnectWorkflowProps } from '@/shared/walletConnection/types' import { CollectivePossibilities } from './CollectivePossibilities' -import { DISMISSED_STORAGE_KEY } from './constants' import { FRAME_FALLBACK_MS } from './useScrollDock' vi.mock('@/shared/walletConnection/connection/ConnectWorkflow', () => ({ @@ -35,15 +34,11 @@ const TopBar = () => { ) } -let linkTops: Record = {} - const renderOnPage = () => render( - Holdings - Latest from the Collective , ) @@ -77,11 +72,8 @@ describe('CollectivePossibilities', () => { mockReducedMotion(false) vi.stubGlobal('ResizeObserver', LaidOutResizeObserver) - localStorage.clear() - bannerTop = 136 bannerHeight = BANNER_HEIGHT - linkTops = { '#holdings': 500, '#latest': 700 } setScrollY(0) vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) { if (this.getAttribute('data-testid') === 'TopBarSlot') { @@ -91,9 +83,6 @@ describe('CollectivePossibilities', () => { const scale = Number((this as HTMLElement).style.transform.match(/scale\(([\d.]+)\)/)?.[1] ?? 1) return DOMRect.fromRect({ y: bannerTop, height: bannerHeight * scale }) } - if (this.tagName === 'A') { - return DOMRect.fromRect({ y: linkTops[this.getAttribute('href') ?? ''], height: 20 }) - } return DOMRect.fromRect() }) vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(function (this: HTMLElement) { @@ -123,13 +112,10 @@ describe('CollectivePossibilities', () => { expect(screen.getByRole('region', { name: 'THE COLLECTIVE POSSIBILITIES' })).toBeInTheDocument() }) - it('labels both X buttons after what they dismiss', () => { + it('cannot be dismissed', () => { renderOnPage() - expect(screen.getByTestId('DismissPossibilitiesButton')).toHaveAccessibleName( - "Dismiss the Don't Miss banner", - ) - expect(screen.getByTestId('DismissDockButton')).toHaveAccessibleName('Dismiss the connect prompt') + expect(screen.queryByRole('button', { name: /dismiss/i })).not.toBeInTheDocument() }) it('makes the top bar sticky and parks a closed, inert dock in its slot', () => { @@ -307,49 +293,6 @@ describe('CollectivePossibilities', () => { expect(screen.getByTestId('PossibilitiesDock')).toHaveAttribute('data-docked', 'true') }) - it('removes the banner and the dock from the banner X', () => { - renderOnPage() - - fireEvent.click(screen.getByTestId('DismissPossibilitiesButton')) - - expect(screen.queryByTestId('CollectivePossibilities')).not.toBeInTheDocument() - expect(screen.queryByTestId('PossibilitiesDock')).not.toBeInTheDocument() - expect(screen.getByTestId('TopBar')).toHaveAttribute('data-active', 'false') - }) - - it('removes the banner and the dock from the dock X', () => { - renderOnPage() - scrollBannerTo(-160) - - fireEvent.click(screen.getByTestId('DismissDockButton')) - - expect(screen.queryByTestId('CollectivePossibilities')).not.toBeInTheDocument() - expect(screen.queryByTestId('PossibilitiesDock')).not.toBeInTheDocument() - expect(screen.getByTestId('TopBar')).toHaveAttribute('data-docked', 'false') - }) - - it('hands the focus to what follows the banner when its X goes', () => { - renderOnPage() - const dismiss = screen.getByTestId('DismissPossibilitiesButton') - dismiss.focus() - - fireEvent.click(dismiss) - - expect(screen.getByRole('link', { name: 'Holdings' })).toHaveFocus() - }) - - it('hands the focus to the first control on screen when the dock X goes far down the page', () => { - renderOnPage() - scrollBannerTo(-160) - linkTops['#holdings'] = -100 // scrolled past, above the viewport - const dismiss = screen.getByTestId('DismissDockButton') - dismiss.focus() - - fireEvent.click(dismiss) - - expect(screen.getByRole('link', { name: 'Latest from the Collective' })).toHaveFocus() - }) - it('hands the focus back to the banner Connect when the dock closes on it', () => { renderOnPage() scrollBannerTo(-160) @@ -360,27 +303,4 @@ describe('CollectivePossibilities', () => { expect(screen.getByTestId('PossibilitiesDock')).toHaveAttribute('inert') expect(screen.getByTestId('ConnectButton')).toHaveFocus() }) - - it('hands the focus back to the banner X when the dock closes on its X', () => { - renderOnPage() - scrollBannerTo(-160) - screen.getByTestId('DismissDockButton').focus() - - scrollBannerTo(-90) - - expect(screen.getByTestId('DismissPossibilitiesButton')).toHaveFocus() - }) - - it('remembers the dismissal across reloads', () => { - const { unmount } = renderOnPage() - fireEvent.click(screen.getByTestId('DismissPossibilitiesButton')) - unmount() - - expect(localStorage.getItem(DISMISSED_STORAGE_KEY)).toBe('true') - - renderOnPage() - expect(screen.queryByTestId('CollectivePossibilities')).not.toBeInTheDocument() - expect(screen.queryByTestId('PossibilitiesDock')).not.toBeInTheDocument() - expect(screen.getByTestId('TopBar')).toHaveAttribute('data-active', 'false') - }) }) diff --git a/src/app/user/components/CollectivePossibilities/CollectivePossibilities.tsx b/src/app/user/components/CollectivePossibilities/CollectivePossibilities.tsx index 8d1fa24ea9..b8de365a1b 100644 --- a/src/app/user/components/CollectivePossibilities/CollectivePossibilities.tsx +++ b/src/app/user/components/CollectivePossibilities/CollectivePossibilities.tsx @@ -1,17 +1,14 @@ 'use client' -import { useEffect, useId, useLayoutEffect, useRef } from 'react' +import { useEffect, useId, useRef } from 'react' import { createPortal } from 'react-dom' -import useLocalStorageState from 'use-local-storage-state' import { CommonComponentProps } from '@/components/commonProps' -import { DismissButton } from '@/components/DismissButton' import { useTopBarDock } from '@/components/MainContainer/TopBarDockProvider' import { cn } from '@/lib/utils' import { ConnectWorkflow } from '@/shared/walletConnection/connection/ConnectWorkflow' import { BannerConnectButton } from './ConnectCtaButton' -import { DISMISSED_STORAGE_KEY } from './constants' import { MotionLogo } from './MotionLogo' import { PossibilitiesDock } from './PossibilitiesDock' import { PosterArt } from './PosterArt' @@ -33,78 +30,27 @@ const POSSIBILITIES = [ }, ] -const FOCUSABLE_SELECTOR = [ - 'a[href]', - 'button:not([disabled])', - 'input:not([disabled])', - 'select:not([disabled])', - 'textarea:not([disabled])', - '[tabindex]:not([tabindex="-1"])', -].join(',') - -const getFocusablesAfter = (element: HTMLElement) => - [...document.querySelectorAll(FOCUSABLE_SELECTOR)].filter( - candidate => - Boolean(element.compareDocumentPosition(candidate) & Node.DOCUMENT_POSITION_FOLLOWING) && - !element.contains(candidate) && - candidate.getBoundingClientRect().bottom > 0, - ) - -const focusFirst = (candidates: HTMLElement[]) => { - for (const candidate of candidates) { - candidate.focus() - if (document.activeElement === candidate) return - } -} - export const CollectivePossibilities = ({ className }: CommonComponentProps) => { const titleId = useId() - const [isDismissed, setIsDismissed] = useLocalStorageState(DISMISSED_STORAGE_KEY, { defaultValue: false }) - const wrapperRef = useRef(null) const bannerRef = useRef(null) const tileRef = useRef(null) const actionsRef = useRef(null) - const nextFocusRef = useRef([]) const { slot, setActive, setDocked } = useTopBarDock() - const { isDocked, shouldAnimate } = useScrollDock({ - bannerRef, - tileRef, - anchor: slot, - isEnabled: !isDismissed, - }) + const { isDocked, shouldAnimate } = useScrollDock({ bannerRef, tileRef, anchor: slot }) useEffect(() => { - setActive(!isDismissed) + setActive(true) return () => setActive(false) - }, [isDismissed, setActive]) + }, [setActive]) useEffect(() => { setDocked(isDocked) return () => setDocked(false) }, [isDocked, setDocked]) - const dismiss = () => { - const wrapper = wrapperRef.current - const focused = document.activeElement - if (wrapper && focused && (wrapper.contains(focused) || slot?.contains(focused))) { - nextFocusRef.current = getFocusablesAfter(wrapper) - } - setIsDismissed(true) - } - - useLayoutEffect(() => { - if (!isDismissed) return - focusFirst(nextFocusRef.current) - nextFocusRef.current = [] - }, [isDismissed]) - - if (isDismissed) { - return null - } - return ( -
+
-
@@ -173,7 +113,6 @@ export const CollectivePossibilities = ({ className }: CommonComponentProps) => , slot, diff --git a/src/app/user/components/CollectivePossibilities/PossibilitiesDock.tsx b/src/app/user/components/CollectivePossibilities/PossibilitiesDock.tsx index 07d7ea4a35..3f108db6d7 100644 --- a/src/app/user/components/CollectivePossibilities/PossibilitiesDock.tsx +++ b/src/app/user/components/CollectivePossibilities/PossibilitiesDock.tsx @@ -2,7 +2,6 @@ import { type RefObject, useRef } from 'react' -import { DismissButton } from '@/components/DismissButton' import { cn } from '@/lib/utils' import { useInertHandoff } from '@/shared/hooks/useInertHandoff' import { ConnectWorkflow } from '@/shared/walletConnection/connection/ConnectWorkflow' @@ -14,16 +13,10 @@ import { EYEBROW_CLASSES } from './styles' interface PossibilitiesDockProps { isDocked: boolean shouldAnimate: boolean - onDismiss: () => void bannerActionsRef: RefObject } -export const PossibilitiesDock = ({ - isDocked, - shouldAnimate, - onDismiss, - bannerActionsRef, -}: PossibilitiesDockProps) => { +export const PossibilitiesDock = ({ isDocked, shouldAnimate, bannerActionsRef }: PossibilitiesDockProps) => { const dockRef = useRef(null) const isInert = useInertHandoff(!isDocked, dockRef, focused => { const dockActions = [...(dockRef.current?.querySelectorAll('button') ?? [])] @@ -68,12 +61,6 @@ export const PossibilitiesDock = ({
-
diff --git a/src/app/user/components/CollectivePossibilities/constants.ts b/src/app/user/components/CollectivePossibilities/constants.ts index a3e7f4e866..6c3266e47a 100644 --- a/src/app/user/components/CollectivePossibilities/constants.ts +++ b/src/app/user/components/CollectivePossibilities/constants.ts @@ -1,3 +1,2 @@ -export const DISMISSED_STORAGE_KEY = 'rc.holdings.dontMiss.dismissed' export const POSTER_SRC = '/images/dont-miss-poster.webp' export const VIDEO_SRC = '/videos/collective-motion-logo.mp4' diff --git a/src/app/user/components/CollectivePossibilities/useScrollDock.ts b/src/app/user/components/CollectivePossibilities/useScrollDock.ts index 8fca1e602f..e2b48261ee 100644 --- a/src/app/user/components/CollectivePossibilities/useScrollDock.ts +++ b/src/app/user/components/CollectivePossibilities/useScrollDock.ts @@ -44,10 +44,9 @@ interface UseScrollDockOptions { bannerRef: RefObject tileRef: RefObject anchor: HTMLElement | null - isEnabled: boolean } -export const useScrollDock = ({ bannerRef, tileRef, anchor, isEnabled }: UseScrollDockOptions) => { +export const useScrollDock = ({ bannerRef, tileRef, anchor }: UseScrollDockOptions) => { const [isDocked, setIsDocked] = useState(false) const [shouldAnimate, setShouldAnimate] = useState(false) const isDockedRef = useRef(false) @@ -56,7 +55,7 @@ export const useScrollDock = ({ bannerRef, tileRef, anchor, isEnabled }: UseScro useEffect(() => { const banner = bannerRef.current const tile = tileRef.current - if (!isEnabled || !anchor || !banner) return + if (!anchor || !banner) return let frame = 0 let fallback: ReturnType | undefined @@ -139,7 +138,7 @@ export const useScrollDock = ({ bannerRef, tileRef, anchor, isEnabled }: UseScro setIsDocked(false) setShouldAnimate(false) } - }, [anchor, bannerRef, tileRef, isEnabled, prefersReducedMotion]) + }, [anchor, bannerRef, tileRef, prefersReducedMotion]) return { isDocked, shouldAnimate } } diff --git a/src/app/user/components/collective-balances-section/index.tsx b/src/app/user/components/collective-balances-section/index.tsx index 2717b6794c..3c10ee4621 100644 --- a/src/app/user/components/collective-balances-section/index.tsx +++ b/src/app/user/components/collective-balances-section/index.tsx @@ -5,7 +5,6 @@ import { useTreasuryContext } from '@/app/treasury/contexts/TreasuryContext' import { useStRifHoldings } from '@/app/treasury/hooks/useStRifHoldings' import { formatTokenBalance, getTokenBalance } from '@/app/user/Balances/balanceUtils' import { useGetAddressTokens } from '@/app/user/Balances/hooks/useGetAddressTokens' -import { AccentSquare } from '@/components/AccentSquare' import { BalanceInfo } from '@/components/BalanceInfo' import { Header } from '@/components/Typography' import Big from '@/lib/big' @@ -47,10 +46,7 @@ export const CollectiveBalancesSection = () => { return (
-
- -
THE COLLECTIVE BALANCES
-
+
THE COLLECTIVE BALANCES
-
- -
THE LATEST IN THE COLLECTIVE
-
+
THE LATEST IN THE COLLECTIVE
PROPOSALS
{activeProposal ? ( diff --git a/src/app/user/my-holdings/MyActivityAndBalances.tsx b/src/app/user/my-holdings/MyActivityAndBalances.tsx index 0b57df7189..602d44f14d 100644 --- a/src/app/user/my-holdings/MyActivityAndBalances.tsx +++ b/src/app/user/my-holdings/MyActivityAndBalances.tsx @@ -2,7 +2,6 @@ import { useHandleErrors } from '@/app/collective-rewards/utils' import { SectionContainerWithSpinner } from '@/app/communities/components/SectionContainer' -import { AccentSquare } from '@/components/AccentSquare' import { BalancesSection } from '../Balances/BalancesSection' import { MyBacking } from './components/backing' @@ -12,12 +11,7 @@ const Separator = () =>
- - {isUserBuilder ? 'MY ACTIVITY & BALANCES' : 'MY BALANCES'} - - ) + const sectionTitle = isUserBuilder ? 'MY ACTIVITY & BALANCES' : 'MY BALANCES' useHandleErrors({ error, title: 'Error fetching builder status' }) diff --git a/src/app/vault/VaultPage.tsx b/src/app/vault/VaultPage.tsx index 32dc7c9e5a..b4285afd88 100644 --- a/src/app/vault/VaultPage.tsx +++ b/src/app/vault/VaultPage.tsx @@ -13,7 +13,7 @@ export const VaultPage = () => { return (
- +
diff --git a/src/components/DismissButton/DismissButton.tsx b/src/components/DismissButton/DismissButton.tsx index 19fbfbf28e..2080849853 100644 --- a/src/components/DismissButton/DismissButton.tsx +++ b/src/components/DismissButton/DismissButton.tsx @@ -2,14 +2,14 @@ import { CloseIconKoto } from '@/components/Icons' import { cn } from '@/lib/utils' export interface DismissButtonProps { - /** Describes what gets dismissed, e.g. "Dismiss the Builders banner". */ + /** Describes what gets dismissed, e.g. "Dismiss the notification". */ 'aria-label': string onClick: () => void /** * The surface the button sits on, which decides the icon and border color. `quiet` is * for compact one-line notifications on dark: a muted X with no frame until hovered. */ - variant?: 'onDark' | 'onLight' | 'quiet' | 'round' | 'roundQuiet' + variant?: 'onDark' | 'onLight' | 'quiet' | 'round' className?: string 'data-testid'?: string } @@ -24,13 +24,11 @@ const VARIANT_CLASSES = { quiet: 'size-7 rounded-md border border-transparent text-warm-icon hover:border-v3-text-80/22 hover:text-banner-title', round: `${ROUND_CLASSES} border-v3-text-80/22`, - roundQuiet: `${ROUND_CLASSES} border-transparent`, } const STROKE_WIDTHS: Partial, string>> = { quiet: '2', round: '2.2', - roundQuiet: '2.2', } /** diff --git a/src/components/PageBanner/BannerDecorativeSquares.tsx b/src/components/PageBanner/BannerDecorativeSquares.tsx deleted file mode 100644 index df1b0599e4..0000000000 --- a/src/components/PageBanner/BannerDecorativeSquares.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { type IconProps } from '@/components/Icons/types' - -/** - * Three squares stepping up to the right, as in the banner designs: - * a muted one at the bottom, the primary orange in the middle and a light one on top. - * - * Squares are 10 units wide with a 3 unit gap, so the artwork scales from `width`/`height`. - * Purely decorative, so it is hidden from assistive technology and takes no label. - */ -export function BannerDecorativeSquares({ - width = 30, - height = 30, - ...props -}: Omit) { - return ( - - ) -} diff --git a/src/components/PageBanner/PageBanner.test.tsx b/src/components/PageBanner/PageBanner.test.tsx index da453ae236..5cc57ea251 100644 --- a/src/components/PageBanner/PageBanner.test.tsx +++ b/src/components/PageBanner/PageBanner.test.tsx @@ -1,9 +1,9 @@ -import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { cleanup, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it } from 'vitest' import { PageBanner } from './PageBanner' -const renderBanner = (props = {}) => render() +const renderBanner = (props = {}) => render() describe('PageBanner', () => { afterEach(cleanup) @@ -11,7 +11,7 @@ describe('PageBanner', () => { it('renders a title-only banner', () => { renderBanner() - expect(screen.getByText('Treasury')).toBeInTheDocument() + expect(screen.getByRole('heading', { level: 1, name: 'Treasury' })).toBeInTheDocument() expect(screen.getByTestId('PageBanner')).toBeInTheDocument() }) @@ -25,42 +25,17 @@ describe('PageBanner', () => { expect(screen.getByText('See the Whitepaper')).toBeInTheDocument() }) - it('hides the banner when dismissed, without persisting the choice', () => { - renderBanner() - - fireEvent.click(screen.getByTestId('DismissBannerButton')) - - expect(screen.queryByTestId('PageBanner')).not.toBeInTheDocument() - expect(Object.keys(localStorage)).toHaveLength(0) - }) + it('uses the compact layout only when the banner carries just the title', () => { + const { rerender } = renderBanner() + expect(screen.getByTestId('PageBanner').querySelector('[data-compact]')).toHaveAttribute('data-compact', 'true') - it('comes back on the next page load', () => { - const { unmount } = renderBanner() - fireEvent.click(screen.getByTestId('DismissBannerButton')) - unmount() - - renderBanner() - expect(screen.getByTestId('PageBanner')).toBeInTheDocument() + rerender() + expect(screen.getByTestId('PageBanner').querySelector('[data-compact]')).toHaveAttribute('data-compact', 'false') }) - it('keeps the title as a visually hidden heading once dismissed', () => { + it('cannot be dismissed', () => { renderBanner() - fireEvent.click(screen.getByTestId('DismissBannerButton')) - - expect(screen.getByRole('heading', { level: 1, name: 'Treasury' })).toHaveClass('sr-only') - }) - - it('shows the decorative squares on every banner', () => { - render() - - expect(screen.getByTestId('BannerDecorativeSquares')).toBeInTheDocument() - }) - - it('renders no dismiss button when it is not dismissible', () => { - render() - - expect(screen.getByText('Holdings')).toBeInTheDocument() - expect(screen.queryByTestId('DismissBannerButton')).not.toBeInTheDocument() + expect(screen.queryByRole('button')).not.toBeInTheDocument() }) }) diff --git a/src/components/PageBanner/PageBanner.tsx b/src/components/PageBanner/PageBanner.tsx index 7112eb7d2f..bd9d7d297e 100644 --- a/src/components/PageBanner/PageBanner.tsx +++ b/src/components/PageBanner/PageBanner.tsx @@ -1,22 +1,13 @@ -'use client' +import { ReactNode } from 'react' -import { ReactNode, useState } from 'react' - -import { DismissButton } from '@/components/DismissButton' import { MoltenBackground } from '@/components/MoltenBackground' import { Header, Paragraph } from '@/components/Typography' import { cn } from '@/lib/utils' import { BANNER_HEADER_OVERLAY, BANNER_MOBILE_OVERLAY, PAGE_TITLE_CLASSES } from './bannerAssets' -import { BannerDecorativeSquares } from './BannerDecorativeSquares' export interface PageBannerProps { title: string - /** - * Renders the dismiss button. The dismissal lasts for the session only: a reload - * brings the banner back. Omit it for a permanent banner. - */ - dismissible?: boolean /** Optional intro copy. Omit it for banners that only carry the page title. */ description?: ReactNode /** Rendered at the bottom right of the banner, typically an external link. */ @@ -29,11 +20,9 @@ export interface PageBannerProps { /** * Page hero: the still molten background shared by every page, title, intro copy and - * optional call to action. When dismissible, closing it hides the banner until the next - * page load; the title stays in the page as a visually hidden heading. + * optional call to action. A banner that only carries the title uses a compact layout. */ export const PageBanner = ({ - dismissible = false, title, description, bottomRight, @@ -41,16 +30,7 @@ export const PageBanner = ({ className, dataTestId = 'PageBanner', }: PageBannerProps) => { - const [isDismissed, setIsDismissed] = useState(false) - - if (dismissible && isDismissed) { - // The banner carries the page's only heading: keep it for assistive technology - return ( -
- {title} -
- ) - } + const isTitleOnly = !description && !bottomRight && !children return (
- - - {dismissible && ( - setIsDismissed(true)} - className="absolute right-4 top-4 z-base" - data-testid="DismissBannerButton" - /> - )} - -
+
diff --git a/src/components/PageBanner/PageTitle.test.tsx b/src/components/PageBanner/PageTitle.test.tsx index 3f645812a4..a818a4b485 100644 --- a/src/components/PageBanner/PageTitle.test.tsx +++ b/src/components/PageBanner/PageTitle.test.tsx @@ -6,11 +6,10 @@ import { PageTitle } from './PageTitle' describe('PageTitle', () => { afterEach(cleanup) - it('renders the page heading under the decorative squares', () => { + it('renders the page heading', () => { render(Staking History) const heading = screen.getByRole('heading', { level: 1, name: 'Staking History' }) expect(heading).toHaveAttribute('data-testid', 'StakingHistoryHeader') - expect(screen.getByTestId('BannerDecorativeSquares')).toHaveAttribute('aria-hidden', 'true') }) }) diff --git a/src/components/PageBanner/PageTitle.tsx b/src/components/PageBanner/PageTitle.tsx index d95b75c9eb..104a7ab7d5 100644 --- a/src/components/PageBanner/PageTitle.tsx +++ b/src/components/PageBanner/PageTitle.tsx @@ -4,7 +4,6 @@ import { Header } from '@/components/Typography' import { cn } from '@/lib/utils' import { PAGE_TITLE_CLASSES } from './bannerAssets' -import { BannerDecorativeSquares } from './BannerDecorativeSquares' interface PageTitleProps { children: ReactNode @@ -12,15 +11,9 @@ interface PageTitleProps { dataTestId?: string } -/** - * Title of a page that has no banner. Carries the same decorative squares and type as the - * banner titles, so every page opens the same way. - */ +/** Title of a page that has no banner. Uses the same type as the banner titles. */ export const PageTitle = ({ children, className, dataTestId }: PageTitleProps) => ( -
- -
- {children} -
-
+
+ {children} +
) diff --git a/src/components/PageBanner/index.ts b/src/components/PageBanner/index.ts index 6f0fa43a26..7251688811 100644 --- a/src/components/PageBanner/index.ts +++ b/src/components/PageBanner/index.ts @@ -1,5 +1,4 @@ export * from './bannerAssets' -export * from './BannerDecorativeSquares' export * from './BannerLink' export * from './PageBanner' export * from './PageTitle' diff --git a/src/components/PersistedCollapsible/PersistedCollapsible.test.tsx b/src/components/PersistedCollapsible/PersistedCollapsible.test.tsx index 86db8cc863..01de2bb6b4 100644 --- a/src/components/PersistedCollapsible/PersistedCollapsible.test.tsx +++ b/src/components/PersistedCollapsible/PersistedCollapsible.test.tsx @@ -46,11 +46,10 @@ describe('PersistedCollapsible', () => { expect(screen.getByTestId('Section')).toHaveAttribute('data-open', 'true') }) - it('renders the title as an h3 behind the accent square', () => { + it('renders the title as an h3', () => { render(
) - const heading = screen.getByRole('heading', { level: 3, name: 'Heading' }) - expect(heading.previousElementSibling).toBe(screen.getByTestId('AccentSquare')) + expect(screen.getByRole('heading', { level: 3, name: 'Heading' })).toBeInTheDocument() }) it('points the toggle at the body it shows and hides', () => { diff --git a/src/components/PersistedCollapsible/PersistedCollapsible.tsx b/src/components/PersistedCollapsible/PersistedCollapsible.tsx index 37cb15be27..c25425f2ad 100644 --- a/src/components/PersistedCollapsible/PersistedCollapsible.tsx +++ b/src/components/PersistedCollapsible/PersistedCollapsible.tsx @@ -3,7 +3,6 @@ import { ReactNode, useId, useSyncExternalStore } from 'react' import useLocalStorageState from 'use-local-storage-state' -import { AccentSquare } from '@/components/AccentSquare' import { ChevronDownIcon } from '@/components/Icons' import { Header, Span } from '@/components/Typography' import { cn } from '@/lib/utils' @@ -12,7 +11,7 @@ import { useNonce } from '@/shared/context/NonceContext' export interface PersistedCollapsibleProps { /** localStorage key that remembers whether the section is open. Unique per section. */ storageKey: string - /** Rendered as the section's h3, after the accent square. */ + /** Rendered as the section's h3. */ title: ReactNode children: ReactNode defaultOpen?: boolean @@ -103,13 +102,9 @@ export const PersistedCollapsible = ({ )} >
-
- {/* Centred on the first line of the h3 below, so it stays there when the title wraps */} - -
- {title} -
-
+
+ {title} +