jsx Copy code
import React, { useEffect, useState, useRef } from "react";
const PRELOADED_CARDS = [
{ id: 1, front: "नमस्ते", back: "Hello", reviewed: 0, correct: 0 },
{ id: 2, front: "धन्यवाद", back: "Thank you", reviewed: 0, correct: 0 },
{ id: 3, front: "कृपया", back: "Please", reviewed: 0, correct: 0 },
{ id: 4, front: "मित्र", back: "Friend", reviewed: 0, correct: 0 },
{ id: 5, front: "पानी", back: "Water", reviewed: 0, correct: 0 },
{ id: 6, front: "घर", back: "Home", reviewed: 0, correct: 0 },
{ id: 7, front: "सपना", back: "Dream", reviewed: 0, correct: 0 },
{ id: 8, front: "समय", back: "Time", reviewed: 0, correct: 0 },
{ id: 9, front: "ख़ुशी", back: "Happiness", reviewed: 0, correct: 0 },
{ id: 10, front: "पुस्तक", back: "Book", reviewed: 0, correct: 0 },
];
function saveToStorage(cards) {
localStorage.setItem("flashcards", JSON.stringify(cards));
}
function loadFromStorage() {
const data = localStorage.getItem("flashcards");
if (!data) {
return null;
}
try {
return JSON.parse(data);
} catch {
return null;
}
}
function Sidebar({ activePage, setActivePage }) {
const baseStyle = {
cursor: "pointer",
padding: 12,
borderLeft: "4px solid transparent",
marginBottom: 8,
userSelect: "none",
fontWeight: "bold",
transition: "background-color 0.2s ease",
};
const activeStyle = {
...baseStyle,
borderLeft: "4px solid #2196f3",
backgroundColor: "#e3f2fd",
};
return (
<div
style={{
width: 180,
borderRight: "1px solid #ccc",
padding: "20px 8px",
boxSizing: "border-box",
height: "100vh",
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
backgroundColor: "#fafafa",
display: "flex",
flexDirection: "column",
}}
>
<div
onClick={() => setActivePage("review")}
style={activePage === "review" ? activeStyle : baseStyle}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter") setActivePage("review");
}}
aria-label="Go to review page"
>
Review
</div>
<div
onClick={() => setActivePage("search")}
style={activePage === "search" ? activeStyle : baseStyle}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter") setActivePage("search");
}}
aria-label="Go to search page"
>
Search
</div>
<div
onClick={() => setActivePage("create")}
style={activePage === "create" ? activeStyle : baseStyle}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter") setActivePage("create");
}}
aria-label="Go to create cards page"
>
Create Cards
</div>
<div
onClick={() => setActivePage("stats")}
style={activePage === "stats" ? activeStyle : baseStyle}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter") setActivePage("stats");
}}
aria-label="Go to statistics page"
>
Statistics
</div>
<footer
style={{
marginTop: "auto",
fontSize: 12,
color: "#777",
textAlign: "center",
padding: "8px 0",
}}
>
Flashcard App © 2024
</footer>
</div>
);
}
function Card3D({ front, back, flipped }) {
const containerStyle = {
perspective: 800,
width: 320,
height: 200,
userSelect: "none",
};
const cardStyle = {
width: "100%",
height: "100%",
position: "relative",
textAlign: "center",
cursor: "pointer",
transition: "transform 0.6s cubic-bezier(0.4, 0, 0.2, 1)",
transformStyle: "preserve-3d",
transform: flipped ? "rotateY(180deg)" : "rotateY(0deg)",
borderRadius: 10,
boxShadow: "0 4px 8px rgba(0,0,0,0.2)",
backgroundColor: "#ffffff",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: 28,
fontWeight: "600",
color: "#222",
padding: 24,
boxSizing: "border-box",
userSelect: "none",
};
const sideStyle = {
position: "absolute",
width: "100%",
height: "100%",
borderRadius: 10,
backfaceVisibility: "hidden",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 24,
boxSizing: "border-box",
userSelect: "none",
};
const frontStyle = {
...sideStyle,
backgroundColor: "#2196f3",
color: "white",
};
const backStyle = {
...sideStyle,
backgroundColor: "#4caf50",
color: "white",
transform: "rotateY(180deg)",
};
return (
<div style={containerStyle} aria-live="polite" aria-atomic="true">
<div style={cardStyle} aria-label={flipped ? `Answer: ${back}` : `Question: ${front}`}>
<div style={frontStyle}>{front}</div>
<div style={backStyle}>{back}</div>
</div>
</div>
);
}
function Review({
cards,
onUpdateCard,
}) {
const [currentIndex, setCurrentIndex] = useState(0);
const [flipped, setFlipped] = useState(false);
const currentCard = cards[currentIndex] || null;
const reviewRef = useRef(null);
useEffect(() => {
setFlipped(false);
}, [currentIndex]);
useEffect(() => {
function onKeyDown(e) {
if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
if (e.code === "Space") {
e.preventDefault();
setFlipped((f) => !f);
} else if (e.code === "ArrowRight") {
e.preventDefault();
setCurrentIndex((idx) => (idx + 1) % cards.length);
} else if (e.code === "ArrowLeft") {
e.preventDefault();
setCurrentIndex((idx) => (idx - 1 + cards.length) % cards.length);
}
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [cards.length]);
if (cards.length === 0)
return (
<div
style={{
padding: 20,
fontSize: 18,
color: "#777",
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
}}
>
No flashcards available. Please create some cards first.
</div>
);
function markCorrect(correct) {
if (!currentCard) return;
const updatedCard = {
...currentCard,
reviewed: (currentCard.reviewed || 0) + 1,
correct: (currentCard.correct || 0) + (correct ? 1 : 0),
};
onUpdateCard(updatedCard);
setCurrentIndex((idx) => (idx + 1) % cards.length);
setFlipped(false);
}
return (
<div
ref={reviewRef}
style={{
height: "100%",
padding: 24,
display: "flex",
flexDirection: "column",
alignItems: "center",
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
userSelect: "none",
}}
>
<h2 style={{ marginBottom: 8 }}>Review Flashcards</h2>
<div style={{ marginBottom: 14 }}>
<small>
Card {currentIndex + 1} / {cards.length} (Press Space to flip, Arrow Left/Right to navigate)
</small>
</div>
<div
onClick={() => setFlipped((f) => !f)}
style={{
outline: "none",
}}
tabIndex={0}
aria-label={
flipped
? `Back side, translation is ${currentCard.back}, click or press Space to flip`
: `Front side, word is ${currentCard.front}, click or press Space to flip`
}
onKeyDown={(e) => {
if (e.code === "Space" || e.key === " ") {
e.preventDefault();
setFlipped((f) => !f);
}
}}
>
<Card3D front={currentCard.front} back={currentCard.back} flipped={flipped} />
</div>
{flipped && (
<div
style={{
marginTop: 20,
display: "flex",
gap: 12,
}}
>
<button
onClick={() => markCorrect(true)}
style={{
padding: "10px 20px",
backgroundColor: "#4caf50",
border: "none",
color: "white",
fontWeight: "bold",
borderRadius: 6,
cursor: "pointer",
minWidth: 100,
}}
aria-label="Mark as correct"
>
Correct
</button>
<button
onClick={() => markCorrect(false)}
style={{
padding: "10px 20px",
backgroundColor: "#f44336",
border: "none",
color: "white",
fontWeight: "bold",
borderRadius: 6,
cursor: "pointer",
minWidth: 100,
}}
aria-label="Mark as incorrect"
>
Incorrect
</button>
</div>
)}
</div>
);
}
function Search({ cards }) {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
useEffect(() => {
if (!query.trim()) {
setResults([]);
return;
}
const lowered = query.toLowerCase();
const filtered = cards.filter(
(c) =>
c.front.toLowerCase().includes(lowered) ||
c.back.toLowerCase().includes(lowered)
);
setResults(filtered);
}, [query, cards]);
return (
<div
style={{
padding: "20px 24px",
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
height: "100%",
boxSizing: "border-box",
}}
>
<h2 style={{ marginBottom: 12 }}>Search Flashcards</h2>
<input
type="search"
aria-label="Search flashcards"
placeholder="Type to search front or back..."
value={query}
onChange={(e) => setQuery(e.target.value)}
style={{
width: "100%",
fontSize: 18,
padding: "10px 14px",
borderRadius: 6,
border: "1.8px solid #ccc",
outlineColor: "#2196f3",
marginBottom: 16,
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
boxSizing: "border-box",
}}
/>
{query.trim() && results.length === 0 && (
<p style={{ color: "#777" }}>No cards match your search.</p>
)}
<ul
style={{
listStyle: "none",
paddingLeft: 0,
maxHeight: 400,
overflowY: "auto",
marginTop: 4,
}}
aria-live="polite"
aria-relevant="additions"
>
{results.map((card) => (
<li
key={card.id}
style={{
background: "#f7f7f7",
marginBottom: 8,
padding: 12,
borderRadius: 6,
boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
}}
tabIndex={0}
aria-label={`Hindi word or phrase: ${card.front} - English translation: ${card.back}`}
>
<div style={{ fontSize: 18, fontWeight: "600" }}>{card.front}</div>
<div style={{ fontSize: 15, color: "#555" }}>{card.back}</div>
</li>
))}
</ul>
</div>
);
}
function CreateCards({ onAddCard }) {
const [front, setFront] = useState("");
const [back, setBack] = useState("");
const [error, setError] = useState("");
function onSubmit(e) {
e.preventDefault();
if (!front.trim() || !back.trim()) {
setError("Both front and back are required.");
return;
}
setError("");
onAddCard({
front: front.trim(),
back: back.trim(),
reviewed: 0,
correct: 0,
});
setFront("");
setBack("");
}
return (
<div
style={{
padding: 20,
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
maxWidth: 480,
margin: "auto",
}}
>
<h2 style={{ marginBottom: 12 }}>Create New Flashcard</h2>
<form onSubmit={onSubmit} noValidate>
<label htmlFor="front" style={{ display: "block", marginBottom: 6, fontWeight: "600" }}>
Front (Hindi word/phrase)
</label>
<input
id="front"
type="text"
value={front}
onChange={(e) => setFront(e.target.value)}
style={{
width: "100%",
padding: "8px 12px",
fontSize: 18,
borderRadius: 6,
border: "1px solid #ccc",
marginBottom: 16,
outlineColor: "#2196f3",
boxSizing: "border-box",
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
}}
aria-required="true"
/>
<label htmlFor="back" style={{ display: "block", marginBottom: 6, fontWeight: "600" }}>
Back (English translation)
</label>
<input
id="back"
type="text"
value={back}
onChange={(e) => setBack(e.target.value)}
style={{
width: "100%",
padding: "8px 12px",
fontSize: 18,
borderRadius: 6,
border: "1px solid #ccc",
marginBottom: 16,
outlineColor: "#2196f3",
boxSizing: "border-box",
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
}}
aria-required="true"
/>
{error && (
<div
role="alert"
style={{ color: "#f44336", marginBottom: 12, fontWeight: "600" }}
>
{error}
</div>
)}
<button
type="submit"
style={{
padding: "12px 24px",
fontSize: 18,
borderRadius: 6,
border: "none",
backgroundColor: "#2196f3",
color: "white",
cursor: "pointer",
fontWeight: "bold",
}}
aria-label="Add flashcard"
>
Add Flashcard
</button>
</form>
</div>
);
}
function Stats({ cards }) {
const [canvasWidth, setCanvasWidth] = useState(400);
const [canvasHeight, setCanvasHeight] = useState(250);
const canvasRef = useRef(null);
// Prepare stats data: count total reviews and correctness over time could be tricky since no timestamps given,
// So we do aggregate stats
const totalReviewed = cards.reduce((sum, c) => sum + (c.reviewed || 0), 0);
const totalCorrect = cards.reduce((sum, c) => sum + (c.correct || 0), 0);
// Calculate percentage correct
const percentCorrect = totalReviewed ? Math.round((totalCorrect / totalReviewed) * 100) : 0;
// For graph: Let's plot the cards individually on a bar graph to show reviews and correctness percentage per card.
// We'll normalize the bars to max reviews among cards.
const maxReviewed = cards.reduce((max, c) => Math.max(max, c.reviewed || 0), 0);
// Responsive canvas width based on container width
useEffect(() => {
function updateSize() {
const w = Math.min(window.innerWidth - 220, 600);
const h = 280;
setCanvasWidth(w);
setCanvasHeight(h);
}
updateSize();
window.addEventListener("resize", updateSize);
return () => window.removeEventListener("resize", updateSize);
}, []);
// Draw graph
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// Draw title
ctx.fillStyle = "#222";
ctx.font = "16px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
ctx.fillText("Reviews and Correctness per Card", 10, 24);
if (cards.length === 0) {
ctx.font = "18px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
ctx.fillStyle = "#777";
ctx.fillText("No cards to display", 10, 100);
return;
}
if (maxReviewed === 0) {
ctx.font = "18px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
ctx.fillStyle = "#777";
ctx.fillText("No reviews done yet", 10, 100);
return;
}
const margin = 40;
const graphWidth = canvasWidth - margin * 2;
const graphHeight = canvasHeight - margin * 2;
// Draw axes
ctx.strokeStyle = "#888";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(margin, canvasHeight - margin);
ctx.lineTo(margin, margin);
ctx.lineTo(canvasWidth - margin, margin);
ctx.stroke();
// Draw y-axis labels for reviews counts: 0 to maxReviewed in steps
ctx.fillStyle = "#555";
ctx.font = "12px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
const yStepCount = 5;
for (let i = 0; i <= yStepCount; i++) {
const val = Math.round((maxReviewed / yStepCount) * i);
const y = canvasHeight - margin - (graphHeight / yStepCount) * i;
ctx.fillText(val.toString(), margin - 30, y + 4);
// horizontal grid line
ctx.strokeStyle = "#eee";
ctx.beginPath();
ctx.moveTo(margin - 5, y);
ctx.lineTo(canvasWidth - margin, y);
ctx.stroke();
}
// Draw x-axis labels: Use first 10 chars of front text
const barWidth = graphWidth / cards.length / 2;
cards.forEach((card, idx) => {
const xCenter = margin + (idx + 0.5) * (graphWidth / cards.length);
// Reviews bar (blue)
const reviewsHeight = maxReviewed ? (card.reviewed / maxReviewed) * graphHeight : 0;
ctx.fillStyle = "#2196f3";
ctx.fillRect(
xCenter - barWidth,
canvasHeight - margin - reviewsHeight,
barWidth - 4,
reviewsHeight
);
// Correctness bar (%) in green side-by-side small bar
const correctnessPercent = card.reviewed
? card.correct / card.reviewed
: 0;
const correctHeight = correctnessPercent * graphHeight;
ctx.fillStyle = "#4caf50";
ctx.fillRect(
xCenter + 4,
canvasHeight - margin - correctHeight,
barWidth - 4,
correctHeight
);
// label (first 10 chars of front)
ctx.fillStyle = "#222";
ctx.font = "11px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
ctx.textAlign = "center";
const label = card.front.length > 10 ? card.front.slice(0, 10) + "…" : card.front;
ctx.fillText(label, xCenter, canvasHeight - margin + 14);
});
// Legend
ctx.textAlign = "start";
ctx.fillStyle = "#2196f3";
ctx.fillRect(canvasWidth - margin - 130, margin + 10, 14, 14);
ctx.fillStyle = "#222";
ctx.fillText("Reviews", canvasWidth - margin - 110, margin + 22);
ctx.fillStyle = "#4caf50";
ctx.fillRect(canvasWidth - margin - 130, margin + 32, 14, 14);
ctx.fillStyle = "#222";
ctx.fillText("Correctness %", canvasWidth - margin - 110, margin + 44);
}, [cards, canvasWidth, canvasHeight, maxReviewed]);
return (
<div
style={{
padding: 20,
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
height: "100%",
boxSizing: "border-box",
maxWidth: 650,
margin: "auto",
}}
>
<h2 style={{ marginBottom: 16 }}>Statistics</h2>
<div
role="region"
aria-label="Summary statistics"
style={{
marginBottom: 24,
fontSize: 18,
fontWeight: "600",
}}
>
<p>
Total Cards Reviewed: <strong>{totalReviewed}</strong>
</p>
<p>
Percentage Correct:{" "}
<strong>{totalReviewed ? percentCorrect + "%" : "N/A"}</strong>
</p>
</div>
<canvas
ref={canvasRef}
width={canvasWidth}
height={canvasHeight}
aria-label="Graph showing number of reviews and correctness percentage per card"
role="img"
style={{ maxWidth: "100%", border: "1px solid #ccc", borderRadius: 8 }}
/>
</div>
);
}
export default function FlashcardApp() {
// Cards state with id, front, back, reviewed, correct counters
const [cards, setCards] = useState(() => {
const saved = loadFromStorage();
if (saved && Array.isArray(saved)) {
// Validate data shape a bit
if (
saved.every(
(c) =>
typeof c.id === "number" &&
typeof c.front === "string" &&
typeof c.back === "string"
)
) {
return saved;
}
}
return PRELOADED_CARDS;
});
const [activePage, setActivePage] = useState("review");
// When cards update, save to localStorage
useEffect(() => {
saveToStorage(cards);
}, [cards]);
// Add handler new card
function addCard(newCard) {
setCards((cards) => {
const newId = cards.length ? Math.max(...cards.map((c) => c.id)) + 1 : 1;
return [...cards, { ...newCard, id: newId }];
});
setActivePage("review");
}
// Update card with statistics after review mark
function updateCard(updatedCard) {
setCards((cards) =>
cards.map((c) => (c.id === updatedCard.id ? updatedCard : c))
);
}
return (
<div
style={{
display: "flex",
height: "100vh",
backgroundColor: "#fff",
color: "#222",
overflow: "hidden",
}}
>
<Sidebar activePage={activePage} setActivePage={setActivePage} />
<main
style={{
flex: 1,
overflowY: "auto",
backgroundColor: "#f4f6f8",
minHeight: "100vh",
}}
>
{activePage === "review" && (
<Review cards={cards} onUpdateCard={updateCard} />
)}
{activePage === "search" && <Search cards={cards} />}
{activePage === "create" && <CreateCards onAddCard={addCard} />}
{activePage === "stats" && <Stats cards={cards} />}
</main>
</div>
);
}