diff options
author | polwex <polwex@sortug.com> | 2025-05-21 14:00:28 +0700 |
---|---|---|
committer | polwex <polwex@sortug.com> | 2025-05-21 14:00:28 +0700 |
commit | e839a5f61f0faa21ca8b4bd5767f7575d5e576ee (patch) | |
tree | 53e5bcc3977b6ebef687521a7ac387a89aeb21c8 /src/components | |
parent | 4f2bd597beaa778476b84c10b571db1b13524301 (diff) |
the card flip animation is legit
Diffstat (limited to 'src/components')
-rw-r--r-- | src/components/Flashcard/Card.tsx | 121 | ||||
-rw-r--r-- | src/components/Flashcard/Deck.tsx | 151 | ||||
-rw-r--r-- | src/components/Flashcard/cards.css | 86 | ||||
-rw-r--r-- | src/components/Login2.tsx | 22 | ||||
-rw-r--r-- | src/components/ParseForm.tsx | 222 | ||||
-rw-r--r-- | src/components/ui/progress.tsx | 29 |
6 files changed, 616 insertions, 15 deletions
diff --git a/src/components/Flashcard/Card.tsx b/src/components/Flashcard/Card.tsx new file mode 100644 index 0000000..7cada24 --- /dev/null +++ b/src/components/Flashcard/Card.tsx @@ -0,0 +1,121 @@ +"use client"; + +import { CardResponse } from "@/lib/types/cards"; + +// export default function ({ user }: { user: { name: string; id: number } }) { +// const [state, formAction, isPending] = useActionState(postLogout, 0); +// return ( +// <form action={formAction}> +// <Card> +// <CardHeader> +// <CardTitle>Profile</CardTitle> +// {state} +// </CardHeader> +// <CardContent> +// <p>Username: {user.name}</p> +// <p>User ID: {user.id}</p> +// </CardContent> +// <CardFooter> +// <Button type="submit">Log out</Button> +// </CardFooter> +// </Card> +// </form> +// ); +// } +// "use client"; + +// --- Flashcard Component --- +interface FlashcardProps { + data: CardResponse; + isFlipped: boolean; + onFlip: () => void; + animationDirection: + | "enter-left" + | "enter-right" + | "exit-left" + | "exit-right" + | "none"; +} + +const Flashcard: React.FC<FlashcardProps> = ({ + data, + isFlipped, + onFlip, + animationDirection, +}) => { + const getAnimationClass = () => { + switch (animationDirection) { + case "enter-right": + return "animate-slide-in-right"; + case "enter-left": + return "animate-slide-in-left"; + case "exit-right": + return "animate-slide-out-right"; + case "exit-left": + return "animate-slide-out-left"; + default: + return ""; + } + }; + + return ( + <div + className={`w-full max-w-md h-80 perspective group ${getAnimationClass()}`} + onClick={onFlip} + > + <div + className={`relative w-full h-full rounded-xl shadow-xl transition-transform duration-700 ease-in-out transform-style-preserve-3d cursor-pointer ${ + isFlipped ? "rotate-y-180" : "" + }`} + > + {/* Front of the card */} + <div className="absolute w-full h-full bg-white dark:bg-slate-800 rounded-xl backface-hidden flex flex-col justify-between items-center p-6"> + <span className="text-xs text-slate-500 dark:text-slate-400 self-start"> + {data.expression.ipa.map((ip, i) => ( + <span key={ip.ipa + i} className="ipa"> + {ip.ipa} + </span> + ))} + </span> + <p className="text-3xl md:text-4xl font-semibold text-slate-800 dark:text-slate-100 text-center"> + {data.expression.spelling} + </p> + <div className="w-full h-6"> + {" "} + {/* Placeholder for spacing, mimics bottom controls */} + <span className="text-xs text-slate-400 dark:text-slate-500 self-end invisible"> + Flip + </span> + </div> + </div> + + {/* Back of the card */} + <div className="absolute w-full h-full bg-slate-50 dark:bg-slate-700 rounded-xl backface-hidden rotate-y-180 flex flex-col justify-between items-center p-6"> + <span className="text-lg text-slate-500 dark:text-slate-400 self-start"> + {data.expression.senses.map((ss, i) => ( + <div key={`ss${i}`}> + {ss.senses.map((sss, i) => ( + <div key={`sss${i}`}> + {sss.glosses.map((ssss, i) => ( + <p key={ssss + i}>{ssss}</p> + ))} + </div> + ))} + </div> + ))} + </span> + <p className="text-3xl md:text-4xl font-semibold text-slate-800 dark:text-slate-100 text-center"> + {data.note} + </p> + <div className="w-full h-6"> + <span className="text-xs text-slate-400 dark:text-slate-500 self-end invisible"> + Flip + </span> + </div> + </div> + </div> + </div> + ); +}; + +export default Flashcard; diff --git a/src/components/Flashcard/Deck.tsx b/src/components/Flashcard/Deck.tsx new file mode 100644 index 0000000..d3c736f --- /dev/null +++ b/src/components/Flashcard/Deck.tsx @@ -0,0 +1,151 @@ +"use client"; + +import { CardResponse, DeckResponse } from "@/lib/types/cards"; +import React, { useCallback, useEffect, useState } from "react"; +import { Button } from "../ui/button"; +import { ChevronLeftIcon, ChevronRightIcon, RotateCcwIcon } from "lucide-react"; +import "./cards.css"; +import Flashcard from "./Card"; + +// --- Main App Component --- +function Deck({ data }: { data: DeckResponse }) { + const [currentPage, setCurrentPage] = useState<number>(0); + const [currentIndex, setCurrentIndex] = useState<number>(0); + const [isFlipped, setIsFlipped] = useState<boolean>(false); + const [animationDirection, setAnimationDirection] = useState< + "enter-left" | "enter-right" | "exit-left" | "exit-right" | "none" + >("none"); + const flashcards = data.cards; + const [isAnimating, setIsAnimating] = useState<boolean>(false); + + const handleFlip = () => { + if (isAnimating) return; + setIsFlipped(!isFlipped); + }; + + const handleNext = useCallback(() => { + if (isAnimating || currentIndex >= flashcards.length - 1) return; + setIsAnimating(true); + setIsFlipped(false); // Flip back to front before changing card + setAnimationDirection("exit-left"); + + setTimeout(() => { + setCurrentIndex((prevIndex) => + Math.min(prevIndex + 1, flashcards.length - 1), + ); + setAnimationDirection("enter-right"); + setTimeout(() => { + setAnimationDirection("none"); + setIsAnimating(false); + }, 500); // Duration of enter animation + }, 500); // Duration of exit animation + }, [currentIndex, flashcards.length, isAnimating]); + + const handlePrev = useCallback(() => { + if (isAnimating || currentIndex <= 0) return; + setIsAnimating(true); + setIsFlipped(false); // Flip back to front + setAnimationDirection("exit-right"); + + setTimeout(() => { + setCurrentIndex((prevIndex) => Math.max(prevIndex - 1, 0)); + setAnimationDirection("enter-left"); + setTimeout(() => { + setAnimationDirection("none"); + setIsAnimating(false); + }, 500); // Duration of enter animation + }, 500); // Duration of exit animation + }, [currentIndex, isAnimating]); + + // Keyboard navigation + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (isAnimating) return; + if (event.key === "ArrowRight") { + handleNext(); + } else if (event.key === "ArrowLeft") { + handlePrev(); + } else if (event.key === " " || event.key === "Enter") { + // Space or Enter to flip + event.preventDefault(); // Prevent scrolling if space is pressed + handleFlip(); + } + }; + + window.addEventListener("keydown", handleKeyDown); + return () => { + window.removeEventListener("keydown", handleKeyDown); + }; + }, [handleNext, handlePrev, isAnimating]); + + if (flashcards.length === 0) { + return ( + <div className="min-h-screen bg-slate-50 dark:bg-slate-900 flex flex-col items-center justify-center p-4 font-inter text-slate-800 dark:text-slate-200"> + <p>No flashcards available.</p> + </div> + ); + } + + const currentCard = flashcards[currentIndex]; + if (!currentCard) return <p>wtf</p>; + + return ( + <div className="min-h-screen bg-slate-100 dark:bg-slate-900 flex flex-col items-center justify-center p-4 font-inter transition-colors duration-300"> + <div className="w-full max-w-md mb-8 relative"> + {/* This div is for positioning the card and managing overflow during animations */} + <div className="relative h-80"> + {" "} + {/* Ensure this matches card height */} + <Flashcard + key={currentCard.id} // Important for re-rendering on card change with animation + data={currentCard} + isFlipped={isFlipped} + onFlip={handleFlip} + animationDirection={animationDirection} + /> + </div> + </div> + + <div className="flex items-center justify-between w-full max-w-md mb-6"> + <Button + onClick={handlePrev} + disabled={currentIndex === 0 || isAnimating} + variant="outline" + size="icon" + aria-label="Previous card" + > + <ChevronLeftIcon /> + </Button> + <div className="text-center"> + <p className="text-sm text-slate-600 dark:text-slate-400"> + Card {currentIndex + 1} of {flashcards.length} + </p> + <Button + onClick={handleFlip} + variant="ghost" + size="sm" + className="mt-1 text-slate-600 dark:text-slate-400" + disabled={isAnimating} + > + <RotateCcwIcon className="w-4 h-4 mr-2" /> Flip Card + </Button> + </div> + <Button + onClick={handleNext} + disabled={currentIndex === flashcards.length - 1 || isAnimating} + variant="outline" + size="icon" + aria-label="Next card" + > + <ChevronRightIcon /> + </Button> + </div> + + <div className="text-xs text-slate-500 dark:text-slate-400 mt-8"> + Use Arrow Keys (← →) to navigate, Space/Enter to flip. + </div> + </div> + ); +} + +export default Deck; diff --git a/src/components/Flashcard/cards.css b/src/components/Flashcard/cards.css new file mode 100644 index 0000000..2f75ad6 --- /dev/null +++ b/src/components/Flashcard/cards.css @@ -0,0 +1,86 @@ +body { + font-family: "Inter", sans-serif; +} + +.perspective { + perspective: 1000px; +} + +.transform-style-preserve-3d { + transform-style: preserve-3d; +} + +.backface-hidden { + backface-visibility: hidden; + -webkit-backface-visibility: hidden; + /* Safari */ +} + +.rotate-y-180 { + transform: rotateY(180deg); +} + +/* Slide animations */ +@keyframes slide-in-right { + from { + transform: translateX(100%); + opacity: 0; + } + + to { + transform: translateX(0); + opacity: 1; + } +} + +.animate-slide-in-right { + animation: slide-in-right 0.5s ease-out forwards; +} + +@keyframes slide-in-left { + from { + transform: translateX(-100%); + opacity: 0; + } + + to { + transform: translateX(0); + opacity: 1; + } +} + +.animate-slide-in-left { + animation: slide-in-left 0.5s ease-out forwards; +} + +@keyframes slide-out-left { + from { + transform: translateX(0); + opacity: 1; + } + + to { + transform: translateX(-100%); + opacity: 0; + } +} + +.animate-slide-out-left { + animation: slide-out-left 0.5s ease-in forwards; +} + +@keyframes slide-out-right { + from { + transform: translateX(0); + opacity: 1; + } + + to { + transform: translateX(100%); + opacity: 0; + } +} + +.animate-slide-out-right { + animation: slide-out-right 0.5s ease-in forwards; +}
\ No newline at end of file diff --git a/src/components/Login2.tsx b/src/components/Login2.tsx index ef3a603..6c26efc 100644 --- a/src/components/Login2.tsx +++ b/src/components/Login2.tsx @@ -11,19 +11,9 @@ import { CardFooter, CardTitle, } from "@/components/ui/card"; -import { - Form, - FormControl, - FormDescription, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; -import { useRouter } from "waku"; export default function AuthScreen() { const [isReg, setReg] = useState(false); @@ -52,15 +42,17 @@ function OOldform({ isReg, toggle }: { isReg: boolean; toggle: () => void }) { else setStrings(logstrings); }, [isReg]); + // const [state, formAction, isPending] = useActionState<FormState, FormData>( + // isReg ? postRegister : postLogin, + // { error: "" }, + // "/login", + // ); const [state, formAction, isPending] = useActionState<FormState, FormData>( - isReg ? postRegister : postLogin, + postLogin, { error: "" }, "/login", ); - // const nav = useRouter(); - // useEffect(() => { - // if (state.success) nav.replace("/"); - // }, [state]); + console.log({ state }); return ( <form action={formAction}> <div className="flex flex-col gap-6"> diff --git a/src/components/ParseForm.tsx b/src/components/ParseForm.tsx new file mode 100644 index 0000000..3e6f3e7 --- /dev/null +++ b/src/components/ParseForm.tsx @@ -0,0 +1,222 @@ +// src/components/SorlangPage.tsx +"use client"; // For Next.js App Router, if applicable + +import React, { + useState, + useRef, + useTransition, + useEffect, + useCallback, + startTransition, +} from "react"; +import { Button } from "@/components/ui/button"; +import { Textarea } from "@/components/ui/textarea"; +import { + Card, + CardContent, + CardFooter, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Loader2 } from "lucide-react"; // Loading spinner +import { useRouter } from "waku"; + +const SorlangPage: React.FC = () => { + const [textValue, setTextValue] = useState<string>(""); + const [pastedImageUrl, setPastedImageUrl] = useState<string | null>(null); + const [pastedImageFile, setPastedImageFile] = useState<File | null>(null); // Store the file for extraction + const [isAnalyzing, setIsAnalyzing] = useState<boolean>(false); + const [isExtracting, setIsExtracting] = useState<boolean>(false); + + const textareaRef = useRef<HTMLTextAreaElement>(null); + + // Cleanup object URL when component unmounts or image changes + useEffect(() => { + return () => { + if (pastedImageUrl) { + URL.revokeObjectURL(pastedImageUrl); + } + }; + }, [pastedImageUrl]); + + const handlePaste = useCallback( + (event: ClipboardEvent) => { + const items = event.clipboardData?.items; + console.log({ items }); + if (!items) return; + + let imageFound = false; + for (const item of items) { + if (item.kind === "file" && item.type.startsWith("image/")) { + event.preventDefault(); // Prevent pasting image data as text + const file = item.getAsFile(); + if (file) { + if (pastedImageUrl) { + URL.revokeObjectURL(pastedImageUrl); // Revoke previous if any + } + const newImageUrl = URL.createObjectURL(file); + setPastedImageUrl(newImageUrl); + setPastedImageFile(file); + imageFound = true; + } + break; // Handle first image found + } + } + + // // If no image was found, let the default text paste happen + // // Or, if you want to explicitly handle text paste: + // if (!imageFound) { + // // Let the default textarea paste handle it, or: + // // event.preventDefault(); + // // const text = event.clipboardData.getData('text/plain'); + // // setTextValue(prev => prev + text); // Or replace, depending on desired behavior + // // setPastedImageUrl(null); // Clear image if text is pasted + // // setPastedImageFile(null); + // } + }, + [pastedImageUrl], + ); + useEffect(() => { + window.addEventListener("paste", handlePaste); + return () => { + window.removeEventListener("paste", handlePaste); + }; + }, [handlePaste]); + + const router = useRouter(); + async function fetchNLP(text: string, app: "spacy" | "stanza") { + const opts = { + method: "POST", + headers: { "Content-type": "application/json" }, + body: JSON.stringify({ text, app }), + }; + const res = await fetch("/api/nlp", opts); + const j = await res.json(); + console.log("j", j); + if ("ok" in j) { + sessionStorage.setItem(`${app}res`, JSON.stringify(j.ok)); + } + } + + const handleProcessText = async () => { + setIsAnalyzing(true); + const text = textValue.trim(); + if (!text) { + alert("Text area is empty!"); + return; + } + await Promise.all([fetchNLP(text, "spacy"), fetchNLP(text, "stanza")]); + router.push("/zoom"); + setIsAnalyzing(false); + }; + + // const [isPending, startTransition] = useTransition(); + const handleExtractTextFromImage = async () => { + if (!pastedImageFile) { + alert("No image to extract text from!"); + return; + } + setIsExtracting(true); + const formData = new FormData(); + formData.append("file", pastedImageFile, pastedImageFile.name); + console.log("Extracting text from image:", pastedImageFile.name); + const res = await fetch("/api/formdata/ocr", { + method: "POST", + body: formData, + }); + const j = await res.json(); + console.log("ocr res", j); + if ("ok" in j) { + setTextValue((t) => t + j.ok.join("\n")); + } + setIsExtracting(false); + // handleClearImage(); + }; + + // setPastedImageUrl(null); + // setPastedImageFile(null); + + const handleClearImage = () => { + if (pastedImageUrl) { + URL.revokeObjectURL(pastedImageUrl); + } + setPastedImageUrl(null); + setPastedImageFile(null); + }; + + return ( + <div className="flex min-h-screen flex-col items-center justify-center bg-background p-4"> + <Card className="w-full max-w-2xl"> + <CardHeader> + <CardTitle className="text-center text-3xl font-bold"> + Sorlang + </CardTitle> + </CardHeader> + <CardContent className="space-y-6"> + <Textarea + ref={textareaRef} + value={textValue} + onChange={(e) => setTextValue(e.target.value)} + placeholder="Paste text here, or paste an image..." + className="min-h-[200px] w-full text-base" + aria-label="Input text area" + /> + + {pastedImageUrl && ( + <div className="mt-4 p-4 border rounded-md bg-muted/40"> + <div className="flex justify-between items-start mb-2"> + <h3 className="text-lg font-semibold">Pasted Image:</h3> + <Button + variant="ghost" + size="sm" + onClick={handleClearImage} + className="text-xs" + > + Clear Image + </Button> + </div> + <img + src={pastedImageUrl} + alt="Pasted content" + className="max-w-full max-h-60 mx-auto rounded-md border" + /> + </div> + )} + </CardContent> + <CardFooter className="flex flex-col sm:flex-row justify-center gap-4"> + {pastedImageUrl ? ( + <Button + onClick={handleExtractTextFromImage} + disabled={isExtracting} + className="w-full sm:w-auto" + > + {isExtracting ? ( + <> + <Loader2 className="mr-2 h-4 w-4 animate-spin" /> + Extracting... + </> + ) : ( + "Extract Text from Image" + )} + </Button> + ) : ( + <Button onClick={handleProcessText} className="w-full sm:w-auto"> + {isAnalyzing ? ( + <> + <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Analyzing... + </> + ) : ( + "Process Text" + )} + </Button> + )} + </CardFooter> + </Card> + <footer className="mt-8 text-center text-sm text-muted-foreground"> + <p>© {new Date().getFullYear()} Sorlang App. All rights reserved.</p> + </footer> + </div> + ); +}; + +export default SorlangPage; diff --git a/src/components/ui/progress.tsx b/src/components/ui/progress.tsx new file mode 100644 index 0000000..10af7e6 --- /dev/null +++ b/src/components/ui/progress.tsx @@ -0,0 +1,29 @@ +import * as React from "react" +import * as ProgressPrimitive from "@radix-ui/react-progress" + +import { cn } from "@/lib/utils" + +function Progress({ + className, + value, + ...props +}: React.ComponentProps<typeof ProgressPrimitive.Root>) { + return ( + <ProgressPrimitive.Root + data-slot="progress" + className={cn( + "bg-primary/20 relative h-2 w-full overflow-hidden rounded-full", + className + )} + {...props} + > + <ProgressPrimitive.Indicator + data-slot="progress-indicator" + className="bg-primary h-full w-full flex-1 transition-all" + style={{ transform: `translateX(-${100 - (value || 0)}%)` }} + /> + </ProgressPrimitive.Root> + ) +} + +export { Progress } |