Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add achievement overview and leaderboard #5169

Merged
merged 9 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions app/actions/AchievementActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { userSchema } from 'app/reducers';
import { User } from './ActionTypes';
import callAPI from './callAPI';
import type { PublicUser } from 'app/store/models/User';

export function fetchLeaderboardUsers({ next = false }: { next: boolean }) {
return callAPI<PublicUser[]>({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this type include the achievements?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe it is? The PublicUser has both achievements and achievementsScore

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, right! So this just fetches the normal PublicUser-data for all the users on the leaderboard?

types: User.FETCH_LEADERBOARD,
endpoint: `/achievements/leaderboard/`,
pagination: {
fetchNext: next,
},
schema: [userSchema],
method: 'GET',
meta: {
errorMessage: 'Henting av brukere feilet',
},
});
}
1 change: 1 addition & 0 deletions app/actions/ActionTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ export const NotificationsFeed = {
*/
export const User = {
FETCH: generateStatuses('User.FETCH') as AAT,
FETCH_LEADERBOARD: generateStatuses('User.FETCH_LEADERBOARD') as AAT,
UPDATE: generateStatuses('User.UPDATE') as AAT,
PASSWORD_CHANGE: generateStatuses('User.PASSWORD_CHANGE') as AAT,
LOGIN: generateStatuses('User.LOGIN') as AAT,
Expand Down
22 changes: 20 additions & 2 deletions app/reducers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,25 @@ const legoAdapter = createLegoAdapter(EntityType.Users);

const usersSlice = createSlice({
name: EntityType.Users,
initialState: legoAdapter.getInitialState(),
initialState: legoAdapter.getInitialState({ fetchingAchievements: false }),
reducers: {},
extraReducers: legoAdapter.buildReducers({
fetchActions: [User.FETCH],
fetchActions: [User.FETCH, User.FETCH_LEADERBOARD],
extraCases: (addCase) => {
addCase(Event.SOCKET_EVENT_UPDATED, (state, action: AnyAction) => {
const users = normalize(action.payload, eventSchema).entities.users!;
if (!users) return;
legoAdapter.upsertMany(state, users);
});
addCase(User.FETCH_LEADERBOARD.BEGIN, (state) => {
state.fetchingAchievements = true;
});
addCase(User.FETCH_LEADERBOARD.SUCCESS, (state) => {
state.fetchingAchievements = false;
});
addCase(User.FETCH_LEADERBOARD.FAILURE, (state) => {
state.fetchingAchievements = false;
});
},
extraMatchers: (addMatcher) => {
addMatcher(
Expand Down Expand Up @@ -97,3 +106,12 @@ export const selectUserWithGroups = createSelector(
};
},
);

export const selectUsersWithAchievementsScore = createSelector(
selectUserEntities,
(userEntities) => {
return Object.values(userEntities).filter(
(user) => user.achievementsScore != null,
);
},
);
88 changes: 88 additions & 0 deletions app/routes/achievements/components/Leaderboard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { usePreparedEffect } from '@webkom/react-prepare';
import { Link } from 'react-router-dom';
import { fetchLeaderboardUsers } from 'app/actions/AchievementActions';
import { ContentMain } from 'app/components/Content';
import Table from 'app/components/Table';
import { selectPaginationNext } from 'app/reducers/selectors';
import { selectUsersWithAchievementsScore } from 'app/reducers/users';
import { useAppDispatch, useAppSelector } from 'app/store/hooks';
import { EntityType } from 'app/store/models/entities';
import type { ColumnProps } from 'app/components/Table';
import type { PublicUser } from 'app/store/models/User';

type RankedUser = PublicUser & {
rank: number;
};

const Leaderboard = () => {
const dispatch = useAppDispatch();

const { pagination } = useAppSelector((state) =>
selectPaginationNext({
endpoint: '/achievements/leaderboard/',
entity: EntityType.Users,
query: {},
})(state),
);

usePreparedEffect(
'fetchLeaderboardUsers',
() => {
dispatch(fetchLeaderboardUsers({ next: true }));
},
[dispatch],
);
const users = useAppSelector((state) =>
selectUsersWithAchievementsScore(state),
);
const rankedUsers: RankedUser[] = users
.slice()
.sort((a, b) => b.achievementsScore - a.achievementsScore)
.map((user, index) => ({
...user,
rank: index + 1,
}));

const columns: ColumnProps<RankedUser>[] = [
{
title: 'Rangering',
dataIndex: 'rank',
search: false,
render: (_, user: RankedUser) => <>{user.rank}</>,
},
{
title: 'Navn',
dataIndex: 'name',
search: false,
inlineFiltering: false,
render: (_, user: RankedUser) => (
<Link to={`/users/${user.username}`}>{user.username}</Link>
),
},
{
title: 'Fullføringsprosent',
dataIndex: 'score',
search: false,
inlineFiltering: false,
render: (_, user: RankedUser) => <>{user.achievementsScore}%</>,
sorter: (a: RankedUser, b: RankedUser) =>
b.achievementsScore - a.achievementsScore,
},
];

return (
<ContentMain>
<Table
columns={columns}
data={rankedUsers}
loading={pagination.fetching}
hasMore={pagination.hasMore}
onLoad={() => {
dispatch(fetchLeaderboardUsers({ next: true }));
}}
/>
</ContentMain>
);
};

export default Leaderboard;
31 changes: 31 additions & 0 deletions app/routes/achievements/components/Overview.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
@import url('~app/styles/variables.css');

.listWrapper {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-md);

@media (--mobile-device) {
flex-direction: column;
gap: var(--spacing-xs);
}
}

.listItem {
display: flex;
align-items: center;
padding: var(--spacing-md);
margin-left: calc(-1 * var(--spacing-md));
gap: var(--spacing-md);
border-radius: var(--border-radius-lg);
color: var(--lego-font-color);
width: 50%;

@media (--small-viewport) {
width: 100%;
}
}

.description {
color: var(--secondary-font-color);
}
89 changes: 89 additions & 0 deletions app/routes/achievements/components/Overview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Flex } from '@webkom/lego-bricks';
import { Trophy } from 'lucide-react';
import { ContentMain } from 'app/components/Content';
import AchievementsInfo, {
rarityToColorMap,
} from 'app/utils/achievementConstants';
import useQuery from 'app/utils/useQuery';
import styles from './Overview.module.css';

const Overview = () => {
const { query } = useQuery({
min_rarity: 'any',
max_rarity: 'any',
sort: 'none',
sort_order: 'asc',
});

const allTrophies = Object.entries(AchievementsInfo).flatMap(
([key, achievements]) =>
achievements.map((achievement, index) => ({
...achievement,
identifier: key,
level: index,
})),
);

const filteredTrophies = allTrophies.filter((trophy) => {
const rarity = trophy.rarity;
const minRarity =
query.min_rarity !== 'any' ? parseInt(query.min_rarity, 10) : 0;
const maxRarity =
query.max_rarity !== 'any' ? parseInt(query.max_rarity, 10) : Infinity;
return rarity >= minRarity && rarity <= maxRarity;
});

const sortedTrophies = [...filteredTrophies].sort((a, b) => {
let comparison = 0;
if (query.sort === 'rarity') comparison = a.rarity - b.rarity;
if (query.sort === 'alphabetical')
comparison = a.name.localeCompare(b.name);
if (query.sort === 'hidden')
comparison = a.hidden === b.hidden ? 0 : a.hidden ? -1 : 1;

return query.sort_order === 'desc' ? -comparison : comparison;
});
Comment on lines +18 to +45
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason we are explicitly storing each list?
I get that it's nice to divide clearly up into filtering and sorting, but it might be better to just define the filter and sorting lambda's instead and then do

const trophies = 
	Obejct.entries(Achievements)
	.flatMap(flatMapper)
	.filter(trophyFilter)
	.sort(trophyComparator)

where flatMapper, trophyFilter, and trophyComparator are just named lambdas:

const trophyFilter: (trophy: Trophy) => boolean = (trophy)  => {
//...
} 

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An named lambda for the flatMapper isn't really that important though


return (
<ContentMain>
<Flex className={styles.listWrapper}>
{sortedTrophies.map((e) => (
<Flex className={styles.listItem} key={e.name + e.rarity}>
<Trophy
size={40}
color={
rarityToColorMap[
AchievementsInfo[e.identifier][e.level].rarity
] ?? 'Gold'
}
style={
AchievementsInfo[e.identifier][e.level].rarity >= 4
? {
filter: `drop-shadow(0px 0px ${
AchievementsInfo[e.identifier][e.level].rarity - 1
}px ${
rarityToColorMap[
AchievementsInfo[e.identifier][e.level].rarity
]
})`,
}
: {}
}
/>
<Flex column gap="var(--spacing-sm)" className="secondaryFontColor">
<h3>{e.name}</h3>
<span className={styles.description}>
{e.hidden ? '?????????' : e.description}
</span>
<span className={styles.description}>
Sjeldenhet: {e.rarity + 1}
</span>
</Flex>
</Flex>
))}
</Flex>
</ContentMain>
);
};

export default Overview;
Loading
Loading