chore(trading): competitions home page

feat(trading): competitions
This commit is contained in:
asiaznik
2024-01-19 16:31:49 -05:00
committed by Matthew Russell
parent b22854f4a5
commit 754e66f2ea
21 changed files with 1133 additions and 7 deletions
@@ -0,0 +1,140 @@
import { useEffect } from 'react';
import { titlefy } from '@vegaprotocol/utils';
import { usePageTitleStore } from '../../stores';
import { useT } from '../../lib/use-t';
import { ErrorBoundary } from '@sentry/react';
import { CompetitionsHeader } from '../../components/competitions/competitions-landing-banner';
import { Intent, Loader, TradingButton } from '@vegaprotocol/ui-toolkit';
import { useGames } from './hooks/use-games';
import { useCurrentEpochInfoQuery } from '../referrals/hooks/__generated__/Epoch';
import { Link, useNavigate } from 'react-router-dom';
import { Links } from '../../lib/links';
import {
CompetitionsAction,
CompetitionsActionsContainer,
} from '../../components/competitions/competitions-cta';
import { GamesContainer } from '../../components/competitions/games-container';
import { CompetitionsLeaderboard } from '../../components/competitions/competitions-leaderboard';
import { useTeams } from './hooks/use-teams';
import take from 'lodash/take';
export const CompetitionsHome = () => {
const t = useT();
const navigate = useNavigate();
const { data: epochData } = useCurrentEpochInfoQuery();
const currentEpoch = Number(epochData?.epoch.id);
const { data: gamesData, loading: gamesLoading } = useGames({
onlyActive: true,
currentEpoch,
});
const { data: teamsData, loading: teamsLoading } = useTeams({
sortByField: ['totalQuantumRewards'],
order: 'desc',
});
const { updateTitle } = usePageTitleStore((store) => ({
updateTitle: store.updateTitle,
}));
useEffect(() => {
updateTitle(titlefy([t('Competitions')]));
}, [updateTitle, t]);
return (
<ErrorBoundary>
<CompetitionsHeader title={t('Competitions')}>
<p className="text-lg mb-1">
{t(
'Be a team player! Participate in games and work together to rake in as much profit to win.'
)}
</p>
</CompetitionsHeader>
{/** Get started */}
<h2 className="text-2xl mb-6">{t('Get started')}</h2>
<CompetitionsActionsContainer>
<CompetitionsAction
variant="A"
title={t('Create a team')}
description={t(
'Lorem ipsum dolor sit amet, consectetur adipisicing elit placeat ipsum minus nemo error dicta.'
)}
actionElement={
<TradingButton
intent={Intent.Primary}
onClick={(e) => {
e.preventDefault();
navigate(Links.COMPETITIONS_CREATE_TEAM());
}}
>
{t('Create a public team')}
</TradingButton>
}
/>
<CompetitionsAction
variant="B"
title={t('Solo team / lone wolf')}
description={t(
'Lorem ipsum dolor sit amet, consectetur adipisicing elit placeat ipsum minus nemo error dicta.'
)}
actionElement={
<TradingButton
intent={Intent.Primary}
onClick={(e) => {
e.preventDefault();
navigate(Links.COMPETITIONS_CREATE_TEAM());
}}
>
{t('Create a private team')}
</TradingButton>
}
/>
<CompetitionsAction
variant="C"
title={t('Join a team')}
description={t(
'Lorem ipsum dolor sit amet, consectetur adipisicing elit placeat ipsum minus nemo error dicta.'
)}
actionElement={
<TradingButton
intent={Intent.Primary}
onClick={(e) => {
e.preventDefault();
navigate(Links.COMPETITIONS_TEAMS());
}}
>
{t('Choose a team')}
</TradingButton>
}
/>
</CompetitionsActionsContainer>
{/** List of available games */}
<h2 className="text-2xl mb-6">{t('Games')}</h2>
{gamesLoading ? (
<Loader size="small" />
) : (
<GamesContainer data={gamesData} currentEpoch={currentEpoch} />
)}
{/** The teams ranking */}
<div className="mb-6 flex flex-row items-baseline justify-between">
<h2 className="text-2xl">{t('Leaderboard')}</h2>
<Link to={Links.COMPETITIONS_TEAMS()} className="text-sm underline">
{t('View all teams')}
</Link>
</div>
{teamsLoading ? (
<Loader size="small" />
) : (
<CompetitionsLeaderboard data={take(teamsData, 10)} />
)}
</ErrorBoundary>
);
};
@@ -0,0 +1,230 @@
import { ErrorBoundary } from '@sentry/react';
import { CompetitionsHeader } from '../../components/competitions/competitions-header';
import { usePageTitleStore } from '../../stores';
import { useEffect, useRef, useState } from 'react';
import { useT } from '../../lib/use-t';
import { titlefy } from '@vegaprotocol/utils';
import { useTeams } from './hooks/use-teams';
import { CompetitionsLeaderboard } from '../../components/competitions/competitions-leaderboard';
import {
Input,
Loader,
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
export const CompetitionsTeams = () => {
const t = useT();
const { updateTitle } = usePageTitleStore((store) => ({
updateTitle: store.updateTitle,
}));
useEffect(() => {
updateTitle(titlefy([t('Competitions'), t('Teams')]));
}, [updateTitle, t]);
const { data: teamsData, loading: teamsLoading } = useTeams({
sortByField: ['totalQuantumRewards'],
order: 'desc',
});
const inputRef = useRef<HTMLInputElement>(null);
// const teamsData = [
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'cat lovers 2000',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'dog lovers 2000',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'we like vega',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'pure gold',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'diamond hands',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'to the moon',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'beyond cats',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'cat lovers 2000',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'cat lovers 2000',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'cat lovers 2000',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// {
// referrer: '12345678909876543212345678765432345676543234567',
// avatarUrl: 'http://placekitten.com/g/200/300',
// teamUrl: 'https://vega.xyz',
// closed: true,
// teamId: '123',
// name: 'cat lovers 2000',
// totalQuantumRewards: '1234567890',
// totalGamesPlayed: 12,
// totalQuantumVolume: '1234567890',
// gamesPlayed: [],
// createdAt: 123,
// createdAtEpoch: 123,
// },
// ];
const [filter, setFilter] = useState<string | null | undefined>(undefined);
return (
<ErrorBoundary>
<CompetitionsHeader title={t('Join a team')}>
<p className="text-lg mb-1">{t('Choose a team to get involved')}</p>x
</CompetitionsHeader>
<div className="mb-6 flex justify-end">
<div className="w-40 h-10 relative">
<span className="absolute z-10 pointer-events-none opacity-90 top-[5px] left-[5px]">
<VegaIcon name={VegaIconNames.SEARCH} size={18} />
</span>
<Input
ref={inputRef}
className="opacity-90 text-right"
placeholder={t('Name')}
onKeyUp={() => {
const value = inputRef.current?.value;
if (value != filter) setFilter(value);
}}
/>
</div>
</div>
<div>
{teamsLoading ? (
<Loader size="small" />
) : (
<CompetitionsLeaderboard
data={teamsData.filter((td) => {
if (filter && filter.length > 0) {
const re = new RegExp(filter, 'i');
return re.test(td.name);
}
return true;
})}
/>
)}
</div>
</ErrorBoundary>
);
};
@@ -0,0 +1,12 @@
query TeamReferees($teamId: ID!) {
teamReferees(teamId: $teamId) {
edges {
node {
teamId
referee
joinedAt
joinedAtEpoch
}
}
}
}
@@ -0,0 +1,16 @@
query Teams($teamId: ID, $partyId: ID) {
teams(teamId: $teamId, partyId: $partyId) {
edges {
node {
teamId
referrer
name
teamUrl
avatarUrl
createdAt
createdAtEpoch
closed
}
}
}
}
@@ -0,0 +1,13 @@
query TeamsStatistics($teamId: ID, $aggregationEpochs: Int) {
teamsStatistics(teamId: $teamId, aggregationEpochs: $aggregationEpochs) {
edges {
node {
teamId
totalQuantumVolume
totalQuantumRewards
totalGamesPlayed
gamesPlayed
}
}
}
}
@@ -0,0 +1,55 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type TeamRefereesQueryVariables = Types.Exact<{
teamId: Types.Scalars['ID'];
}>;
export type TeamRefereesQuery = { __typename?: 'Query', teamReferees?: { __typename?: 'TeamRefereeConnection', edges: Array<{ __typename?: 'TeamRefereeEdge', node: { __typename?: 'TeamReferee', teamId: string, referee: string, joinedAt: any, joinedAtEpoch: number } }> } | null };
export const TeamRefereesDocument = gql`
query TeamReferees($teamId: ID!) {
teamReferees(teamId: $teamId) {
edges {
node {
teamId
referee
joinedAt
joinedAtEpoch
}
}
}
}
`;
/**
* __useTeamRefereesQuery__
*
* To run a query within a React component, call `useTeamRefereesQuery` and pass it any options that fit your needs.
* When your component renders, `useTeamRefereesQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useTeamRefereesQuery({
* variables: {
* teamId: // value for 'teamId'
* },
* });
*/
export function useTeamRefereesQuery(baseOptions: Apollo.QueryHookOptions<TeamRefereesQuery, TeamRefereesQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<TeamRefereesQuery, TeamRefereesQueryVariables>(TeamRefereesDocument, options);
}
export function useTeamRefereesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<TeamRefereesQuery, TeamRefereesQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<TeamRefereesQuery, TeamRefereesQueryVariables>(TeamRefereesDocument, options);
}
export type TeamRefereesQueryHookResult = ReturnType<typeof useTeamRefereesQuery>;
export type TeamRefereesLazyQueryHookResult = ReturnType<typeof useTeamRefereesLazyQuery>;
export type TeamRefereesQueryResult = Apollo.QueryResult<TeamRefereesQuery, TeamRefereesQueryVariables>;
@@ -0,0 +1,61 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type TeamsQueryVariables = Types.Exact<{
teamId?: Types.InputMaybe<Types.Scalars['ID']>;
partyId?: Types.InputMaybe<Types.Scalars['ID']>;
}>;
export type TeamsQuery = { __typename?: 'Query', teams?: { __typename?: 'TeamConnection', edges: Array<{ __typename?: 'TeamEdge', node: { __typename?: 'Team', teamId: string, referrer: string, name: string, teamUrl: string, avatarUrl: string, createdAt: any, createdAtEpoch: number, closed: boolean } }> } | null };
export const TeamsDocument = gql`
query Teams($teamId: ID, $partyId: ID) {
teams(teamId: $teamId, partyId: $partyId) {
edges {
node {
teamId
referrer
name
teamUrl
avatarUrl
createdAt
createdAtEpoch
closed
}
}
}
}
`;
/**
* __useTeamsQuery__
*
* To run a query within a React component, call `useTeamsQuery` and pass it any options that fit your needs.
* When your component renders, `useTeamsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useTeamsQuery({
* variables: {
* teamId: // value for 'teamId'
* partyId: // value for 'partyId'
* },
* });
*/
export function useTeamsQuery(baseOptions?: Apollo.QueryHookOptions<TeamsQuery, TeamsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<TeamsQuery, TeamsQueryVariables>(TeamsDocument, options);
}
export function useTeamsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<TeamsQuery, TeamsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<TeamsQuery, TeamsQueryVariables>(TeamsDocument, options);
}
export type TeamsQueryHookResult = ReturnType<typeof useTeamsQuery>;
export type TeamsLazyQueryHookResult = ReturnType<typeof useTeamsLazyQuery>;
export type TeamsQueryResult = Apollo.QueryResult<TeamsQuery, TeamsQueryVariables>;
@@ -0,0 +1,58 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type TeamsStatisticsQueryVariables = Types.Exact<{
teamId?: Types.InputMaybe<Types.Scalars['ID']>;
aggregationEpochs?: Types.InputMaybe<Types.Scalars['Int']>;
}>;
export type TeamsStatisticsQuery = { __typename?: 'Query', teamsStatistics?: { __typename?: 'TeamsStatisticsConnection', edges: Array<{ __typename?: 'TeamStatisticsEdge', node: { __typename?: 'TeamStatistics', teamId: string, totalQuantumVolume: string, totalQuantumRewards: string, totalGamesPlayed: number, gamesPlayed: Array<string> } }> } | null };
export const TeamsStatisticsDocument = gql`
query TeamsStatistics($teamId: ID, $aggregationEpochs: Int) {
teamsStatistics(teamId: $teamId, aggregationEpochs: $aggregationEpochs) {
edges {
node {
teamId
totalQuantumVolume
totalQuantumRewards
totalGamesPlayed
gamesPlayed
}
}
}
}
`;
/**
* __useTeamsStatisticsQuery__
*
* To run a query within a React component, call `useTeamsStatisticsQuery` and pass it any options that fit your needs.
* When your component renders, `useTeamsStatisticsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useTeamsStatisticsQuery({
* variables: {
* teamId: // value for 'teamId'
* aggregationEpochs: // value for 'aggregationEpochs'
* },
* });
*/
export function useTeamsStatisticsQuery(baseOptions?: Apollo.QueryHookOptions<TeamsStatisticsQuery, TeamsStatisticsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<TeamsStatisticsQuery, TeamsStatisticsQueryVariables>(TeamsStatisticsDocument, options);
}
export function useTeamsStatisticsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<TeamsStatisticsQuery, TeamsStatisticsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<TeamsStatisticsQuery, TeamsStatisticsQueryVariables>(TeamsStatisticsDocument, options);
}
export type TeamsStatisticsQueryHookResult = ReturnType<typeof useTeamsStatisticsQuery>;
export type TeamsStatisticsLazyQueryHookResult = ReturnType<typeof useTeamsStatisticsLazyQuery>;
export type TeamsStatisticsQueryResult = Apollo.QueryResult<TeamsStatisticsQuery, TeamsStatisticsQueryVariables>;
@@ -0,0 +1,37 @@
import compact from 'lodash/compact';
import { useActiveRewardsQuery } from '../../../components/rewards-container/__generated__/Rewards';
import { isActiveReward } from '../../../components/rewards-container/active-rewards';
import { EntityScope, type TransferNode } from '@vegaprotocol/types';
const isScopedToTeams = (node: TransferNode) =>
node.transfer.kind.__typename === 'RecurringTransfer' &&
node.transfer.kind.dispatchStrategy?.entityScope ===
EntityScope.ENTITY_SCOPE_TEAMS;
export const useGames = ({
currentEpoch,
onlyActive,
}: {
currentEpoch: number;
onlyActive: boolean;
}) => {
const { data, loading, error } = useActiveRewardsQuery({
variables: {
isReward: true,
},
});
const games = compact(data?.transfersConnection?.edges?.map((n) => n?.node))
.map((n) => n as TransferNode)
.filter((node) => {
const recurring = node.transfer.kind.__typename !== 'RecurringTransfer';
const active = onlyActive ? isActiveReward(node, currentEpoch) : true;
return active && recurring && isScopedToTeams(node);
});
return {
data: games,
loading,
error,
};
};
@@ -0,0 +1,69 @@
import { useMemo } from 'react';
import { type TeamsQuery, useTeamsQuery } from './__generated__/Teams';
import {
type TeamsStatisticsQuery,
useTeamsStatisticsQuery,
} from './__generated__/TeamsStatistics';
import compact from 'lodash/compact';
import sortBy from 'lodash/sortBy';
import { type ArrayElement } from 'type-fest/source/internal';
type SortableField = keyof Omit<
ArrayElement<NonNullable<TeamsQuery['teams']>['edges']>['node'] &
ArrayElement<
NonNullable<TeamsStatisticsQuery['teamsStatistics']>['edges']
>['node'],
'__typename'
>;
type UseTeamsArgs = {
aggregationEpochs?: number;
sortByField?: SortableField[];
order?: 'asc' | 'desc';
};
const DEFAULT_AGGREGATION_EPOCHS = 10;
export const useTeams = ({
aggregationEpochs = DEFAULT_AGGREGATION_EPOCHS,
sortByField = ['createdAtEpoch'],
order = 'asc',
}: UseTeamsArgs) => {
const {
data: teamsData,
loading: teamsLoading,
error: teamsError,
} = useTeamsQuery();
const {
data: statsData,
loading: statsLoading,
error: statsError,
} = useTeamsStatisticsQuery({
variables: {
aggregationEpochs,
},
});
const teams = compact(teamsData?.teams?.edges).map((e) => e.node);
const stats = compact(statsData?.teamsStatistics?.edges).map((e) => e.node);
const data = useMemo(() => {
const data = teams.map((t) => ({
...t,
...stats.find((s) => s.teamId === t.teamId),
}));
const sorted = sortBy(data, sortByField);
if (order === 'desc') {
return sorted.reverse();
}
return sorted;
}, [teams, sortByField, order, stats]);
return {
data,
loading: teamsLoading && statsLoading,
error: teamsError || statsError,
};
};
@@ -0,0 +1,49 @@
import classNames from 'classnames';
import { type ComponentProps, type ReactElement, type ReactNode } from 'react';
import { DudeBadge } from './graphics/dude-badge';
export const BORDER_COLOR = 'border-vega-clight-500 dark:border-vega-cdark-500';
export const GRADIENT =
'bg-gradient-to-b from-vega-clight-800 dark:from-vega-cdark-800 to-transparent';
export const CompetitionsActionsContainer = ({
children,
}: {
children:
| ReactElement<typeof CompetitionsAction>
| Iterable<ReactElement<typeof CompetitionsAction>>;
}) => (
<div className="grid grid-rows-3 grid-cols-1 md:grid-rows-1 md:grid-cols-3 gap-6 mb-12">
{children}
</div>
);
export const CompetitionsAction = ({
variant,
title,
description,
actionElement,
children,
}: {
variant: ComponentProps<typeof DudeBadge>['variant'];
title: string;
description?: string;
actionElement: ReactNode;
children?: ReactNode;
}) => {
return (
<div
className={classNames(
BORDER_COLOR,
GRADIENT,
'border rounded-lg',
'p-6 flex flex-col items-center gap-6 text-center'
)}
>
<DudeBadge variant={variant} />
<h2 className="text-2xl">{title}</h2>
{description && <p className="text-muted">{description}</p>}
{actionElement}
</div>
);
};
@@ -0,0 +1,30 @@
import classNames from 'classnames';
import { AnimatedDudeWithWire } from '../../client-pages/referrals/graphics/dude';
import { type ReactNode } from 'react';
export const CompetitionsHeader = ({
title,
children,
}: {
title: string;
children?: ReactNode;
}) => {
return (
<div className={classNames('relative mb-10 lg:mb-20')}>
<div className="">
<div
aria-hidden
className="absolute top-20 right-[220px] md:right-[240px] max-sm:hidden"
>
<AnimatedDudeWithWire />
</div>
<div className="pt-10 lg:pt-20 sm:w-[50%]">
<h1 className="text-3xl _text-[6vw] lg:!text-6xl leading-[1em] font-alpha calt mb-10">
{title}
</h1>
{children}
</div>
</div>
</div>
);
};
@@ -0,0 +1,74 @@
import { Link } from 'react-router-dom';
import { Splash } from '@vegaprotocol/ui-toolkit';
import { getNumberFormat } from '@vegaprotocol/utils';
import { type useTeams } from '../../client-pages/competitions/hooks/use-teams';
import { useT } from '../../lib/use-t';
import { Table } from '../table';
import { Rank } from './graphics/rank';
import { Links } from '../../lib/links';
export const CompetitionsLeaderboard = ({
data,
}: {
data: ReturnType<typeof useTeams>['data'];
}) => {
const t = useT();
const num = (n?: number | string) =>
!n ? '-' : getNumberFormat(0).format(Number(n));
if (!data || data.length === 0) {
return <Splash>{t('Could not find any teams')}</Splash>;
}
return (
<Table
columns={[
{ name: 'rank', displayName: '#' },
{ name: 'avatar', displayName: '' },
{ name: 'team', displayName: t('Team') },
{ name: 'earned', displayName: t('Rewards earned') },
{ name: 'games', displayName: t('Total games') },
{ name: 'members', displayName: t('No. of members') },
{ name: 'status', displayName: t('Status') },
{ name: 'volume', displayName: t('Volume') },
]}
data={data.map((td, i) => {
// leaderboard place or medal
let rank: number | React.ReactNode = i + 1;
if (rank === 1) rank = <Rank variant="gold" />;
if (rank === 2) rank = <Rank variant="silver" />;
if (rank === 3) rank = <Rank variant="bronze" />;
// avatar TODO: Generated avatar if none provided
const avatar = td.avatarUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
className="w-[30px] h-[30px]"
src={td.avatarUrl}
alt={td.name}
referrerPolicy="no-referrer"
/>
) : null;
return {
rank,
avatar,
team: (
<Link
className="hover:underline"
to={Links.COMPETITIONS_TEAM(td.teamId)}
>
{td.name}
</Link>
),
earned: num(td.totalQuantumRewards),
games: num(td.totalGamesPlayed),
members: 0,
status: td.closed ? t('Closed') : t('Open'),
volume: num(td.totalQuantumVolume),
};
})}
></Table>
);
};
@@ -0,0 +1,39 @@
import { type TransferNode } from '@vegaprotocol/types';
import { ActiveRewardCard } from '../rewards-container/active-rewards';
import { useT } from '../../lib/use-t';
import { Splash } from '@vegaprotocol/ui-toolkit';
export const GamesContainer = ({
data,
currentEpoch,
}: {
data: TransferNode[];
currentEpoch: number;
}) => {
const t = useT();
if (!data || data.length === 0) {
return <Splash>{t('There are currently no games available.')}</Splash>;
}
return (
<div className="mb-12 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{data.map((game, i) => {
// TODO: Remove `kind` prop from ActiveRewardCard
const { transfer } = game;
if (
transfer.kind.__typename !== 'RecurringTransfer' ||
!transfer.kind.dispatchStrategy?.dispatchMetric
) {
return null;
}
return (
<ActiveRewardCard
key={i}
transferNode={game}
currentEpoch={currentEpoch}
kind={transfer.kind}
/>
);
})}
</div>
);
};
@@ -0,0 +1,40 @@
import classNames from 'classnames';
import { DudeWithFlag } from './dude-with-flag';
/**
* Pre-defined badge gradients
*/
export const BADGE_GRADIENT_VARIANT_A =
'bg-gradient-to-r from-vega-blue-500 via-vega-purple-500 to-vega-pink-500';
export const BADGE_GRADIENT_VARIANT_B =
'bg-gradient-to-r from-vega-purple-500 via-vega-green-500 to-vega-blue-500';
export const BADGE_GRADIENT_VARIANT_C =
'bg-gradient-to-r from-vega-blue-500 via-vega-purple-500 to-vega-green-500';
/** Badge */
export const DudeBadge = ({
variant,
className,
}: {
variant: 'A' | 'B' | 'C' | undefined;
className?: classNames.Argument;
}) => {
return (
<div
className={classNames(
'w-24 h-24 rounded-full bg-black relative',
'rotate-12',
{
[BADGE_GRADIENT_VARIANT_A]: variant === 'A',
[BADGE_GRADIENT_VARIANT_B]: variant === 'B',
[BADGE_GRADIENT_VARIANT_C]: variant === 'C',
},
className
)}
>
<DudeWithFlag className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 -rotate-12" />
</div>
);
};
@@ -0,0 +1,50 @@
import { theme } from '@vegaprotocol/tailwindcss-config';
type DudeWithFlagProps = {
flagColor?: string;
withStar?: boolean;
className?: string;
};
const DEFAULT_FLAG_COLOR = theme.colors.vega.green[500];
export const DudeWithFlag = ({
flagColor = DEFAULT_FLAG_COLOR,
withStar = true,
className,
}: DudeWithFlagProps) => {
return (
<svg
width="49"
height="43"
viewBox="0 0 49 43"
fill="none"
className={className}
>
{withStar && (
<>
<path d="M3.99992 0H2V1.99993H3.99992V0Z" fill="white" />
<path
d="M2 1.99993L0 1.99981V3.99974H1.99992L2 1.99993Z"
fill="white"
/>
<path
d="M3.99995 3.99992L1.99992 3.99974L2 5.99988H3.99995V3.99992Z"
fill="white"
/>
<path
d="M5.99997 1.99981L3.99992 1.99993L3.99995 3.99992L5.99997 3.99974V1.99981Z"
fill="white"
/>
</>
)}
<path
d="M32 4H11V33H15V43H20V33H23V43H28V33H32V4ZM20 17H15V12H20V17ZM28 17H23V12H28V17Z"
fill="white"
/>
<path d="M41 25L32 25L32 20L41 20L41 25Z" fill="white" />
<path d="M36 29V4H35V29" fill="white" />
<path d="M36 13H49L44.55 8.5L49 4H36V13Z" fill={flagColor} />
</svg>
);
};
@@ -0,0 +1,110 @@
import { useThemeSwitcher } from '@vegaprotocol/react-helpers';
import classNames from 'classnames';
export const Rank = ({
variant,
className,
}: {
variant?: 'gold' | 'silver' | 'bronze';
className?: classNames.Argument;
}) => {
const { theme } = useThemeSwitcher();
return (
<div
title={classNames({
'1': variant === 'gold',
'2': variant === 'silver',
'3': variant === 'bronze',
})}
className={classNames(
{
'text-yellow-300': variant === 'gold',
'text-vega-clight-500': variant === 'silver',
'text-vega-orange-500': variant === 'bronze',
'text-black dark:text-white': variant === undefined,
},
className
)}
>
<svg width="18" height="30" viewBox="0 0 18 30" fill="none">
<defs>
<linearGradient x1="0" y1="0" x2="100%" y2="100%" id="medal">
<stop offset="33%" stop-color="transparent" />
<stop offset="100%" stop-color="black" stop-opacity="50%" />
</linearGradient>
<clipPath id="shape">
<path d="M2 2H4V4H2V2Z" />
<path d="M2 2H4V4H2V2Z" />
<path d="M2 2H6V4H2V2Z" />
<path d="M2 2H6V4H2V2Z" />
<path d="M0 4H4V6H0V4Z" />
<path d="M0 4H4V6H0V4Z" />
<path d="M4 0H14V2H4V0Z" />
<path d="M4 0H14V2H4V0Z" />
<path d="M0 14V4H2V14H0Z" />
<path d="M0 14V4H2V14H0Z" />
<path d="M2 30L2 18H4L4 30H2Z" />
<path d="M2 30L2 18H4L4 30H2Z" />
<path d="M14 30L14 18H16L16 30H14Z" />
<path d="M14 30L14 18H16L16 30H14Z" />
<path d="M16 14L16 4H18V14H16Z" />
<path d="M16 14L16 4H18V14H16Z" />
<path d="M2 6V2H4V6H2Z" />
<path d="M2 6V2H4V6H2Z" />
<path d="M16 2V6H14V2H16Z" />
<path d="M16 2V6H14V2H16Z" />
<path d="M12 2H16L16 4H12V2Z" />
<path d="M12 2H16L16 4H12V2Z" />
<path d="M14 4H18V6H14V4Z" />
<path d="M14 4H18V6H14V4Z" />
<path d="M16 16H12V14H16V16Z" />
<path d="M16 16H12V14H16V16Z" />
<path d="M14 18H4L4 16L14 16L14 18Z" />
<path d="M14 18H4L4 16L14 16L14 18Z" />
<path d="M16 12V16H14V12H16Z" />
<path d="M16 12V16H14V12H16Z" />
<path d="M6 16H2V14H6V16Z" />
<path d="M6 16H2V14H6V16Z" />
<path d="M6 28H4L4 26H6V28Z" />
<path d="M6 28H4L4 26H6V28Z" />
<path d="M8 26H6L6 24H8V26Z" />
<path d="M8 26H6L6 24H8V26Z" />
<path d="M10 24H8V22H10V24Z" />
<path d="M10 24H8V22H10V24Z" />
<path d="M12 26H10L10 24H12V26Z" />
<path d="M12 26H10L10 24H12V26Z" />
<path d="M14 28H12L12 26H14V28Z" />
<path d="M14 28H12L12 26H14V28Z" />
<path d="M4 14H0L2.04189e-07 12H4V14Z" />
<path d="M4 14H0L2.04189e-07 12H4V14Z" />
<path d="M6 4H12V14H6V4Z" />
<path d="M6 4H12V14H6V4Z" />
<path d="M4 6H14V12H4V6Z" />
<path d="M4 6H14V12H4V6Z" />
</clipPath>
</defs>
<rect
rx="0"
ry="0"
width="18"
height="30"
fill="currentColor"
clipPath="url(#shape)"
/>
<rect
rx="0"
ry="0"
width="18"
height="30"
fill="url(#medal)"
clipPath="url(#shape)"
style={{ mixBlendMode: theme === 'dark' ? 'darken' : 'overlay' }}
/>
<g style={{ mixBlendMode: 'overlay' }}>
<path d="M10.5 6H8.5V8H10.5V6Z" fill="white" />
<path d="M12.5 8H10.5V10H12.5V8Z" fill="white" />
</g>
</svg>
</div>
);
};
@@ -202,6 +202,13 @@ const NavbarMenu = ({ onClick }: { onClick: () => void }) => {
{t('Portfolio')}
</NavbarLink>
</NavbarItem>
{featureFlags.TEAM_COMPETITION && (
<NavbarItem>
<NavbarLink to={Links.COMPETITIONS()} onClick={onClick}>
{t('Competitions')}
</NavbarLink>
</NavbarItem>
)}
{featureFlags.REFERRALS && (
<NavbarItem>
<NavbarLink end={false} to={Links.REFERRALS()} onClick={onClick}>
+18 -4
View File
@@ -15,11 +15,17 @@ type TableColumnDefinition = {
testId?: string;
};
type DataEntry = {
[key: TableColumnDefinition['name']]: ReactNode;
className?: string;
};
type TableProps = {
columns: TableColumnDefinition[];
data: Record<TableColumnDefinition['name'] | 'className', React.ReactNode>[];
data: DataEntry[];
noHeader?: boolean;
noCollapse?: boolean;
onRowClick?: (index: number) => void;
};
const INNER_BORDER_STYLE = `border-b ${BORDER_COLOR}`;
@@ -35,6 +41,7 @@ export const Table = forwardRef<
noHeader = false,
noCollapse = false,
className,
onRowClick,
...props
},
ref
@@ -81,12 +88,17 @@ export const Table = forwardRef<
>
{!noHeader && header}
<tbody>
{data.map((d, i) => (
{data.map((dataEntry, i) => (
<tr
key={i}
className={classNames(d['className'] as string, {
className={classNames(dataEntry['className'] as string, {
'max-md:flex flex-col w-full': !noCollapse,
})}
onClick={() => {
if (onRowClick) {
onRowClick(i);
}
}}
>
{columns.map(({ name, displayName, className, testId }, j) => (
<td
@@ -116,7 +128,9 @@ export const Table = forwardRef<
{displayName}
</span>
)}
<span data-testid={`${testId || name}-${i}`}>{d[name]}</span>
<span data-testid={`${testId || name}-${i}`}>
{dataEntry[name]}
</span>
</td>
))}
</tr>
+9
View File
@@ -17,6 +17,10 @@ export const Routes = {
REFERRALS_APPLY_CODE: '/referrals/apply-code',
REFERRALS_CREATE_CODE: '/referrals/create-code',
TEAM: '/competitions/team/:teamId',
COMPETITIONS: '/competitions',
COMPETITIONS_TEAMS: '/competitions/teams',
COMPETITIONS_CREATE_TEAM: '/competitions/teams/create',
COMPETITIONS_TEAM: '/competitions/teams/:teamId',
FEES: '/fees',
REWARDS: '/rewards',
} as const;
@@ -42,6 +46,11 @@ export const Links: ConsoleLinks = {
REFERRALS_APPLY_CODE: () => Routes.REFERRALS_APPLY_CODE,
REFERRALS_CREATE_CODE: () => Routes.REFERRALS_CREATE_CODE,
TEAM: (teamId: string) => trimEnd(Routes.TEAM.replace(':teamId', teamId)),
COMPETITIONS: () => Routes.COMPETITIONS,
COMPETITIONS_TEAMS: () => Routes.COMPETITIONS_TEAMS,
COMPETITIONS_CREATE_TEAM: () => Routes.COMPETITIONS_CREATE_TEAM,
COMPETITIONS_TEAM: (teamId: string) =>
Routes.COMPETITIONS_TEAM.replace(':teamId', teamId),
FEES: () => Routes.FEES,
REWARDS: () => Routes.REWARDS,
};
+16 -3
View File
@@ -14,7 +14,6 @@ import { Withdraw } from '../client-pages/withdraw';
import { Transfer } from '../client-pages/transfer';
import { Fees } from '../client-pages/fees';
import { Rewards } from '../client-pages/rewards';
import { Team } from '../client-pages/team';
import { Routes as AppRoutes } from '../lib/links';
import { LayoutWithSky } from '../client-pages/referrals/layout';
import { Referrals } from '../client-pages/referrals/referrals';
@@ -30,6 +29,8 @@ import { PortfolioSidebar } from '../client-pages/portfolio/portfolio-sidebar';
import { LiquiditySidebar } from '../client-pages/liquidity/liquidity-sidebar';
import { MarketsSidebar } from '../client-pages/markets/markets-sidebar';
import { useT } from '../lib/use-t';
import { CompetitionsHome } from '../client-pages/competitions/competitions-home';
import { CompetitionsTeams } from '../client-pages/competitions/competitions-teams';
// These must remain dynamically imported as pennant cannot be compiled by nextjs due to ESM
// Using dynamic imports is a workaround for this until pennant is published as ESM
@@ -95,8 +96,20 @@ export const useRouterConfig = (): RouteObject[] => {
: undefined,
featureFlags.TEAM_COMPETITION
? {
path: AppRoutes.TEAM,
element: <Team />,
path: AppRoutes.COMPETITIONS,
element: <LayoutWithSidebar sidebar={<PortfolioSidebar />} />,
children: [
{
element: <LayoutWithSky />,
children: [
{ index: true, element: <CompetitionsHome /> },
{
path: AppRoutes.COMPETITIONS_TEAMS,
element: <CompetitionsTeams />,
},
],
},
],
}
: undefined,
{