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

Fix available hearts #491

Merged
merged 3 commits into from
May 17, 2024
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
36 changes: 30 additions & 6 deletions packages/berlin/src/pages/Comments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import CommentsTable from '../components/tables/comment-table';
import CommentsColumns from '../components/columns/comments-columns';
import IconButton from '../components/icon-button';
import Textarea from '../components/textarea';
import { INITIAL_HEARTS } from '../utils/constants';

type LocalUserVotes = ResponseUserVotesType | { optionId: string; numOfVotes: number }[];

Expand All @@ -52,8 +53,6 @@ function Comments() {
const queryClient = useQueryClient();
const { cycleId, optionId } = useParams();
const { user } = useUser();
const availableHearts = useAppStore((state) => state.availableHearts);
const setAvailableHearts = useAppStore((state) => state.setAvailableHearts);
const [localUserVotes, setLocalUserVotes] = useState<LocalUserVotes>([]);
const [localOptionHearts, setLocalOptionHearts] = useState(0);
const [comment, setComment] = useState('');
Expand All @@ -65,6 +64,10 @@ function Comments() {
enabled: !!optionId,
});

const availableHearts =
useAppStore((state) => state.availableHearts[option?.questionId || '']) ?? INITIAL_HEARTS;
const setAvailableHearts = useAppStore((state) => state.setAvailableHearts);

const { data: userVotes } = useQuery({
queryKey: ['votes', cycleId],
queryFn: () => fetchUserVotes(cycleId || ''),
Expand All @@ -82,7 +85,6 @@ function Comments() {
queryKey: ['option', optionId, 'comments'],
queryFn: () => fetchComments({ optionId: optionId || '' }),
enabled: !!optionId,
// refetchInterval: 5000, // Poll every 5 seconds
diegoalzate marked this conversation as resolved.
Show resolved Hide resolved
});

const sortedComments = useMemo(() => {
Expand All @@ -97,11 +99,17 @@ function Comments() {

useEffect(() => {
if (optionId) {
const sumOfAllVotes = userVotes?.reduce((acc, option) => acc + option.numOfVotes, 0) || 0;
const hearts = userVotes?.find((option) => optionId === option.optionId)?.numOfVotes || 0;
setLocalOptionHearts(hearts);
setLocalUserVotes([{ optionId: optionId, numOfVotes: hearts }]);
// update the available hearts
setAvailableHearts({
questionId: option?.questionId ?? '',
hearts: Math.max(0, INITIAL_HEARTS - sumOfAllVotes),
});
}
}, [optionId, userVotes]);
}, [optionId, userVotes, setAvailableHearts, option?.questionId]);

const { mutate: mutateComments } = useMutation({
mutationFn: postComment,
Expand All @@ -113,15 +121,31 @@ function Comments() {
});

const handleVoteWrapper = (optionId: string) => {
if (availableHearts === 0) {
toast.error('No hearts left to give');
return;
}

setLocalOptionHearts((prevLocalOptionHearts) => prevLocalOptionHearts + 1);
setLocalUserVotes((prevLocalUserVotes) => handleLocalVote(optionId, prevLocalUserVotes));
setAvailableHearts(handleAvailableHearts(availableHearts, 'vote'));
setAvailableHearts({
questionId: option?.questionId ?? '',
hearts: handleAvailableHearts(availableHearts, 'vote'),
});
};

const handleUnVoteWrapper = (optionId: string) => {
if (availableHearts === INITIAL_HEARTS) {
toast.error('No votes to left to remove');
return;
}

setLocalOptionHearts((prevLocalOptionHearts) => Math.max(0, prevLocalOptionHearts - 1));
setLocalUserVotes((prevLocalUserVotes) => handleLocalUnVote(optionId, prevLocalUserVotes));
setAvailableHearts(handleAvailableHearts(availableHearts, 'unVote'));
setAvailableHearts({
questionId: option?.questionId ?? '',
hearts: handleAvailableHearts(availableHearts, 'unVote'),
});
};

const { mutate: mutateVotes } = useMutation({
Expand Down
43 changes: 32 additions & 11 deletions packages/berlin/src/pages/Cycle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,11 @@ import BackButton from '../components/back-button';
import Button from '../components/button';
import CycleColumns from '../components/columns/cycle-columns';
import OptionCard from '../components/option-card';
import { FIVE_MINUTES_IN_SECONDS, INITIAL_HEARTS } from '../utils/constants';
diegoalzate marked this conversation as resolved.
Show resolved Hide resolved

type Order = 'asc' | 'desc';
type LocalUserVotes = ResponseUserVotesType | { optionId: string; numOfVotes: number }[];

const initialHearts = 20;
const fiveMinutesInSeconds = 300;

function Cycle() {
const queryClient = useQueryClient();
const { user } = useUser();
Expand All @@ -58,7 +56,10 @@ function Cycle() {
enabled: !!user?.id && !!cycleId,
retry: false,
});
const { availableHearts, setAvailableHearts } = useAppStore((state) => state);
const availableHearts =
useAppStore((state) => state.availableHearts[cycle?.forumQuestions[0].id || '']) ??
INITIAL_HEARTS;
const setAvailableHearts = useAppStore((state) => state.setAvailableHearts);
const [startAt, setStartAt] = useState<string | null>(null);
const [endAt, setEndAt] = useState<string | null>(null);
const [localUserVotes, setLocalUserVotes] = useState<LocalUserVotes>([]);
Expand All @@ -83,7 +84,7 @@ function Cycle() {
case 'upcoming':
return `Vote opens in: ${formattedTime}`;
case 'open':
if (time && time <= fiveMinutesInSeconds) {
if (time && time <= FIVE_MINUTES_IN_SECONDS) {
return `Vote closes in: ${formattedTime}`;
} else if (time === 0) {
return 'Vote has ended.';
Expand All @@ -94,12 +95,16 @@ function Cycle() {
}
}, [cycleState, time, formattedTime]);

const updateVotesAndHearts = (votes: ResponseUserVotesType) => {
const updateInitialVotesAndHearts = (votes: ResponseUserVotesType) => {
const givenVotes = votes
.map((option) => option.numOfVotes)
.reduce((prev, curr) => prev + curr, 0);

setAvailableHearts(initialHearts - givenVotes);
setAvailableHearts({
questionId: cycle?.forumQuestions[0].id || '',
hearts: Math.max(0, INITIAL_HEARTS - givenVotes),
});

setLocalUserVotes(votes);
};

Expand All @@ -122,7 +127,7 @@ function Cycle() {

useEffect(() => {
if (userVotes?.length) {
updateVotesAndHearts(userVotes);
updateInitialVotesAndHearts(userVotes);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userVotes]);
Expand All @@ -142,13 +147,29 @@ function Cycle() {
});

const handleVoteWrapper = (optionId: string) => {
if (availableHearts === 0) {
toast.error('No hearts left to give');
return;
}

setLocalUserVotes((prevLocalUserVotes) => handleLocalVote(optionId, prevLocalUserVotes));
setAvailableHearts(handleAvailableHearts(availableHearts, 'vote'));
setAvailableHearts({
questionId: cycle?.forumQuestions[0].id ?? '',
hearts: handleAvailableHearts(availableHearts, 'vote'),
});
};

const handleUnVoteWrapper = (optionId: string) => {
if (availableHearts === INITIAL_HEARTS) {
toast.error('No votes to left to remove');
return;
}

setLocalUserVotes((prevLocalUserVotes) => handleLocalUnVote(optionId, prevLocalUserVotes));
setAvailableHearts(handleAvailableHearts(availableHearts, 'unVote'));
setAvailableHearts({
questionId: cycle?.forumQuestions[0].id ?? '',
hearts: handleAvailableHearts(availableHearts, 'unVote'),
});
};

const handleSaveVotesWrapper = () => {
Expand Down Expand Up @@ -224,7 +245,7 @@ function Cycle() {
You have <Bold>{availableHearts}</Bold> hearts left to give away:
</Body>
<FlexRow $gap="0.25rem" $wrap>
{Array.from({ length: initialHearts }).map((_, id) => (
{Array.from({ length: INITIAL_HEARTS }).map((_, id) => (
<img
key={id}
src={id < availableHearts ? '/icons/heart-full.svg' : '/icons/heart-empty.svg'}
Expand Down
13 changes: 8 additions & 5 deletions packages/berlin/src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ interface AppState {
onboardingStatus: COMPLETION_STATUS;
userStatus: COMPLETION_STATUS;
theme: 'light' | 'dark';
availableHearts: number;
availableHearts: {
[questionId: string]: number;
};
setUserStatus: (status: COMPLETION_STATUS) => void;
setOnboardingStatus: (status: COMPLETION_STATUS) => void;
setAvailableHearts: (hearts: number) => void;
setAvailableHearts: ({ hearts, questionId }: { questionId: string; hearts: number }) => void;
toggleTheme: () => void;
reset: () => void;
}
Expand All @@ -23,17 +25,18 @@ export const useAppStore = create<AppState>()(
userStatus: 'INCOMPLETE',
eventRegistrationStatus: 'INCOMPLETE',
theme: 'dark', // Default theme is dark
availableHearts: 20, // Set the initial hearts value
availableHearts: {}, // Set the initial hearts value
setUserStatus: (status: COMPLETION_STATUS) => set(() => ({ userStatus: status })),
setOnboardingStatus: (status: COMPLETION_STATUS) =>
set(() => ({ onboardingStatus: status })),
setAvailableHearts: (hearts: number) => set(() => ({ availableHearts: hearts })),
setAvailableHearts: ({ hearts, questionId }) =>
set((state) => ({ availableHearts: { ...state.availableHearts, [questionId]: hearts } })),
toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })),
reset: () =>
set(() => ({
userStatus: 'INCOMPLETE',
eventRegistrationStatus: 'INCOMPLETE',
availableHearts: 20,
availableHearts: {},
})),
}),
{ name: 'lexicon-store' },
Expand Down
2 changes: 2 additions & 0 deletions packages/berlin/src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const INITIAL_HEARTS = 20;
export const FIVE_MINUTES_IN_SECONDS = 300;
Loading