Skip to content
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
161 changes: 161 additions & 0 deletions apps/react/src/components/CardCarousel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import React, { useRef, useState, useLayoutEffect, useEffect } from 'react';
import { FlashCard } from './FlashCard';
import { CardWithAttempts } from 'MemoryFlashCore/src/redux/selectors/currDeckCardsWithAttempts';
import { User } from 'MemoryFlashCore/src/types/User';
import { isCardOwner } from '../utils/useIsCardOwner';
import useWindowResize from '../screens/StudyScreen/useWindowResize';
import { useAppSelector } from 'MemoryFlashCore/src/redux/store';
import { Confetti } from './feedback/Confetti';

const getBestTime = (card: CardWithAttempts) => {
const correctAttempts = card.attempts.filter((a) => a.correct);
if (correctAttempts.length === 0) return null;
return Math.min(...correctAttempts.map((a) => a.timeTaken));
};

interface CardCarouselProps {
cards: CardWithAttempts[];
index: number;
hideFutureCards: boolean;
user?: User | null;
activePresentationMode: string | null;
}

export const CardCarousel: React.FC<CardCarouselProps> = ({
cards,
index,
hideFutureCards,
user,
activePresentationMode,
}) => {
const cardRefs = useRef<HTMLDivElement[]>([]);
const cardContainerRef = useRef<HTMLDivElement | null>(null);
const [cardsTranslation, setCardsTranslation] = useState('');
const incorrect = useAppSelector((state) => state.scheduler.incorrect);
const [animationState, setAnimationState] = useState<'idle' | 'correct' | 'incorrect'>('idle');
const [showConfetti, setShowConfetti] = useState(false);
const prevIncorrectRef = useRef(incorrect);
const prevIndexRef = useRef(index);
const prevBestTimeRef = useRef<number | null>(null);

const updateTranslation = () => {
let totalWidth = 0;
const cardContainerWidth = cardContainerRef.current?.offsetWidth || 0;

cardRefs.current.slice(0, index + 1).forEach((ref, forEachIndex) => {
if (!ref) return;
let width = ref?.offsetWidth;
const computedStyle = window.getComputedStyle(ref);
const marginLeft = parseFloat(computedStyle.marginLeft) || 0;
const marginRight = parseFloat(computedStyle.marginRight) || 0;
width += marginLeft + marginRight;

if (forEachIndex === index) {
totalWidth += width / 2 || 0;
} else {
totalWidth += width || 0;
}
});

const translation = cardContainerWidth / 2 - totalWidth;
setCardsTranslation(`translateX(${translation}px)`);
};

useEffect(() => {
cardRefs.current = cardRefs.current.slice(0, cards.length);
}, [cards.length]);

useWindowResize(() => {
updateTranslation();
});

useLayoutEffect(() => {
setTimeout(() => {
updateTranslation();
}, 1000 / 30);
}, [cards.length, index, activePresentationMode]);

// Detect incorrect answer
useEffect(() => {
if (incorrect && !prevIncorrectRef.current) {
setAnimationState('incorrect');
const timer = setTimeout(() => setAnimationState('idle'), 400);
return () => clearTimeout(timer);
}
prevIncorrectRef.current = incorrect;
}, [incorrect]);

// Track best time for current card
useEffect(() => {
const currentCard = cards[index];
if (currentCard) {
prevBestTimeRef.current = getBestTime(currentCard);
}
}, [cards, index]);

// Detect correct answer and check for new record
useEffect(() => {
if (index > prevIndexRef.current && cards.length > 0) {
setAnimationState('correct');
const timer = setTimeout(() => setAnimationState('idle'), 300);

// Check if we beat the previous best time (card at prevIndex is now answered)
const answeredCard = cards[prevIndexRef.current];
if (answeredCard && prevBestTimeRef.current !== null) {
const newBestTime = getBestTime(answeredCard);
if (newBestTime !== null && newBestTime < prevBestTimeRef.current) {
setShowConfetti(true);
setTimeout(() => setShowConfetti(false), 100);
}
}

prevIndexRef.current = index;
return () => clearTimeout(timer);
}
prevIndexRef.current = index;
}, [index, cards]);

const cardOpacity = (_index: number) => {
if (_index === index) return 1;
if (_index > index && hideFutureCards) return 0;
if (_index === index + 1) return 0.75;
return 0.4;
};

const getCardAnimation = (_index: number) => {
if (_index !== index) return '';
if (animationState === 'correct') return 'animate-card-correct';
if (animationState === 'incorrect') return 'animate-card-incorrect';
return '';
};

return (
<div className="flex flex-1 relative" ref={cardContainerRef}>
<Confetti show={showConfetti} />
<div
className="flex items-center"
style={{
transform: cardsTranslation,
transition: 'transform 0.5s ease',
}}
>
{cards.map((card, i) => {
const isOwner = isCardOwner(card, user ?? undefined);
const isActive = i === index;
return (
<FlashCard
key={card._id + i}
ref={(el) => (cardRefs.current[i] = el!)}
placement={isActive ? 'cur' : i < index ? 'answered' : 'scheduled'}
card={card}
className={`card-shadow-2 ${getCardAnimation(i)}`}
opacity={cardOpacity(i)}
showEdit={isOwner && isActive}
showDelete={isOwner && isActive}
/>
);
})}
</div>
</div>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ export const AnyOctaveAnswerValidator: React.FC<{ card: Card }> = ({ card }) =>
if (!answerNotesChroma.includes(onNotesChroma[i])) {
dispatch(recordAttempt(false));
dispatch(midiActions.addWrongNote(onNotes[i].number));
dispatch(midiActions.waitUntilEmpty());
return;
}
}

if (onNotes.length === answer.notes.length) {
dispatch(midiActions.requestClearClickedNotes());
dispatch(recordAttempt(true));
console.log('Correct!');
}
Expand Down
50 changes: 50 additions & 0 deletions apps/react/src/components/feedback/Confetti.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React, { useEffect, useState } from 'react';

interface ConfettiPiece {
id: number;
left: number;
color: string;
delay: number;
duration: number;
}

const COLORS = ['#22c55e', '#3b82f6', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899'];

export const Confetti: React.FC<{ show: boolean }> = ({ show }) => {
const [pieces, setPieces] = useState<ConfettiPiece[]>([]);

useEffect(() => {
if (show) {
const newPieces: ConfettiPiece[] = Array.from({ length: 30 }, (_, i) => ({
id: i,
left: Math.random() * 100,
color: COLORS[Math.floor(Math.random() * COLORS.length)],
delay: Math.random() * 0.3,
duration: 0.8 + Math.random() * 0.4,
}));
setPieces(newPieces);
const timer = setTimeout(() => setPieces([]), 1500);
return () => clearTimeout(timer);
}
}, [show]);

if (pieces.length === 0) return null;

return (
<div className="absolute inset-0 pointer-events-none overflow-hidden z-50">
{pieces.map((piece) => (
<div
key={piece.id}
className="absolute w-2 h-2 rounded-sm animate-confetti"
style={{
left: `${piece.left}%`,
top: '50%',
backgroundColor: piece.color,
animationDelay: `${piece.delay}s`,
animationDuration: `${piece.duration}s`,
}}
/>
))}
</div>
);
};
31 changes: 31 additions & 0 deletions apps/react/src/components/feedback/NetworkStateWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import React from 'react';
import { useNetworkState } from 'MemoryFlashCore/src/redux/selectors/useNetworkState';
import { Spinner } from './Spinner';
import { BasicErrorCard } from './ErrorCard';

interface NetworkStateWrapperProps {
networkKey: string;
children: React.ReactNode;
showSpinnerWhen?: 'always' | 'no-children';
hasData?: boolean;
}

export const NetworkStateWrapper: React.FC<NetworkStateWrapperProps> = ({
networkKey,
children,
showSpinnerWhen = 'no-children',
hasData = true,
}) => {
const { isLoading, error } = useNetworkState(networkKey);
const showSpinner =
isLoading &&
(showSpinnerWhen === 'always' || (showSpinnerWhen === 'no-children' && !hasData));

return (
<>
<Spinner show={showSpinner} />
<BasicErrorCard error={error} />
{children}
</>
);
};
1 change: 1 addition & 0 deletions apps/react/src/components/feedback/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './Spinner';
export * from './Toast';
export * from './ErrorCard';
export * from './EmptyState';
export * from './NetworkStateWrapper';
9 changes: 7 additions & 2 deletions apps/react/src/components/keyboard/KeyBoard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const CustomisedKey: React.FC<{
const pressed = onNotes.find((note) => note.number === midi) !== undefined;
const { cards, index } = useAppSelector(sessionCardsSelector);
const card = cards[index];
const pendingClear = useAppSelector((state) => state.midi.pendingClearClickedNotes);

const noteIsCorrect = !useAppSelector((state) => state.midi.wrongNotes).includes(midi);
let whiteKeyStartColor = '#FFF';
Expand Down Expand Up @@ -81,12 +82,16 @@ const CustomisedKey: React.FC<{
}
}}
onMouseUp={() => {
if (!noteIsCorrect || !card) {
// Remove on mouse up if:
// 1. It's a wrong note (so user can fix mistakes), OR
// 2. Chord was just completed (pendingClear is true)
if (pressed && (!noteIsCorrect || pendingClear)) {
dispatch(midiActions.removeNote(midi));
}
}}
onMouseLeave={() => {
if ((pressed && !noteIsCorrect) || !card) {
// Only remove wrong notes on mouse leave
if (pressed && !noteIsCorrect) {
dispatch(midiActions.removeNote(midi));
}
}}
Expand Down
55 changes: 55 additions & 0 deletions apps/react/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,58 @@ body,
.dark .recharts-tooltip-label {
@apply text-black;
}

/* Card animations */
@keyframes card-correct {
0% {
transform: scale(1);
}
50% {
transform: scale(1.05);
}
100% {
transform: scale(1);
}
}

@keyframes card-incorrect {
0%,
100% {
transform: translateY(0);
}
20% {
transform: translateY(-4px);
}
40% {
transform: translateY(4px);
}
60% {
transform: translateY(-3px);
}
80% {
transform: translateY(2px);
}
}

.animate-card-correct {
animation: card-correct 0.3s ease-in-out;
}

.animate-card-incorrect {
animation: card-incorrect 0.4s ease-in-out;
}

@keyframes confetti {
0% {
transform: translateY(0) rotate(0deg) scale(1);
opacity: 1;
}
100% {
transform: translateY(-150px) rotate(720deg) scale(0);
opacity: 0;
}
}

.animate-confetti {
animation: confetti 1s ease-out forwards;
}
Loading