From e839a5f61f0faa21ca8b4bd5767f7575d5e576ee Mon Sep 17 00:00:00 2001 From: polwex Date: Wed, 21 May 2025 14:00:28 +0700 Subject: the card flip animation is legit --- bun.lock | 10 +- message.txt | 3 + package.json | 2 +- src/actions/login.ts | 57 +++-- src/components/Flashcard/Card.tsx | 121 +++++++++ src/components/Flashcard/Deck.tsx | 151 ++++++++++++ src/components/Flashcard/cards.css | 86 +++++++ src/components/Login2.tsx | 22 +- src/components/ParseForm.tsx | 222 +++++++++++++++++ src/components/ui/progress.tsx | 29 +++ src/lib/db/index.ts | 92 ++++--- src/lib/db/schema.sql | 11 +- src/lib/db/seed.ts | 494 +++++++++++++++++++++++++++++++++++++ src/lib/hooks/useCookie.ts | 35 +++ src/lib/resources/lang.ts | 8 + src/lib/server/cookie.ts | 52 ++-- src/lib/server/cookiebridge.ts | 76 +++--- src/lib/server/setcookie.ts | 16 +- src/lib/types/cards.ts | 210 ++++++++++++++++ src/lib/types/index.ts | 2 +- src/lib/useful_thai.json | 1 + src/pages.gen.ts | 14 ++ src/pages/index.tsx | 106 +++++++- src/pages/lang/[slug].tsx | 74 ++++++ src/pages/lesson/[slug].tsx | 66 +++++ src/pages/login.tsx | 29 +-- src/pages/logintest/Form.tsx | 53 ++++ src/pages/logintest/ServerForm.tsx | 67 +++++ src/pages/logintest/funcs.ts | 24 ++ src/pages/logintest/index.tsx | 24 ++ src/pages/parse.tsx | 26 ++ src/picker/App.tsx | 2 +- src/zoom/ServerWord.tsx | 12 +- waku.config.ts | 4 +- 34 files changed, 2013 insertions(+), 188 deletions(-) create mode 100644 message.txt create mode 100644 src/components/Flashcard/Card.tsx create mode 100644 src/components/Flashcard/Deck.tsx create mode 100644 src/components/Flashcard/cards.css create mode 100644 src/components/ParseForm.tsx create mode 100644 src/components/ui/progress.tsx create mode 100644 src/lib/db/seed.ts create mode 100644 src/lib/hooks/useCookie.ts create mode 100644 src/lib/resources/lang.ts create mode 100644 src/lib/types/cards.ts create mode 120000 src/lib/useful_thai.json create mode 100644 src/pages/lang/[slug].tsx create mode 100644 src/pages/lesson/[slug].tsx create mode 100644 src/pages/logintest/Form.tsx create mode 100644 src/pages/logintest/ServerForm.tsx create mode 100644 src/pages/logintest/funcs.ts create mode 100644 src/pages/logintest/index.tsx create mode 100644 src/pages/parse.tsx diff --git a/bun.lock b/bun.lock index c436aff..32c90fc 100644 --- a/bun.lock +++ b/bun.lock @@ -4,10 +4,10 @@ "": { "name": "waku", "dependencies": { - "@edge-runtime/cookies": "^6.0.0", "@hookform/resolvers": "^5.0.1", "@radix-ui/react-dialog": "^1.1.13", "@radix-ui/react-label": "^2.1.6", + "@radix-ui/react-progress": "^1.1.7", "@radix-ui/react-select": "^2.2.4", "@radix-ui/react-slot": "^1.2.2", "class-variance-authority": "^0.7.1", @@ -85,8 +85,6 @@ "@babel/types": ["@babel/types@7.27.1", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-+EzkxvLNfiUeKMgy/3luqfsCWFRXLb7U6wNQTk60tovuckwB15B191tJWvpp4HjiQWdJkCxO3Wbvc6jlk3Xb2Q=="], - "@edge-runtime/cookies": ["@edge-runtime/cookies@6.0.0", "", {}, "sha512-VVO/8AwC2qVbygLb2IOkX1zWFx2yWIHzFv4D602CTnoRffd/+cdcXqpSydKaedFrk7a1dRYXbWwjzfV/gwZ2Gw=="], - "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.4", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1VCICWypeQKhVbE9oW/sJaAmjLxhVqacdkvPLEjwlttjfwENRSClS8EjBz0KzRyFSCPDIkuXW34Je/vk7zdB7Q=="], "@esbuild/android-arm": ["@esbuild/android-arm@0.25.4", "", { "os": "android", "cpu": "arm" }, "sha512-QNdQEps7DfFwE3hXiU4BZeOV68HHzYwGd0Nthhd3uCkkEKK7/R6MTgM0P7H7FAs5pU/DIWsviMmEGxEoxIZ+ZQ=="], @@ -225,6 +223,8 @@ "@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.2", "", { "dependencies": { "@radix-ui/react-slot": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-uHa+l/lKfxuDD2zjN/0peM/RhhSmRjr5YWdk/37EnSv1nJ88uvG85DPexSm8HdFQROd2VdERJ6ynXbkCFi+APw=="], + "@radix-ui/react-progress": ["@radix-ui/react-progress@1.1.7", "", { "dependencies": { "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vPdg/tF6YC/ynuBIJlk1mm7Le0VgW6ub6J2UWnTQ7/D23KXcPI1qy+0vBkgKgd38RCMJavBXpB83HPNFMTb0Fg=="], + "@radix-ui/react-select": ["@radix-ui/react-select@2.2.4", "", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.2", "@radix-ui/react-collection": "1.1.6", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.9", "@radix-ui/react-focus-guards": "1.1.2", "@radix-ui/react-focus-scope": "1.1.6", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.6", "@radix-ui/react-portal": "1.1.8", "@radix-ui/react-primitive": "2.1.2", "@radix-ui/react-slot": "1.2.2", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/OOm58Gil4Ev5zT8LyVzqfBcij4dTHYdeyuF5lMHZ2bIp0Lk9oETocYiJ5QC0dHekEQnK6L/FNJCceeb4AkZ6Q=="], "@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.2", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-y7TBO4xN4Y94FvcWIOIh18fM4R1A8S4q1jhoz4PNzOoHsFcN8pogcFmZrTYAm4F9VRUrWP/Mw7xSKybIeRI+CQ=="], @@ -855,6 +855,8 @@ "@anthropic-ai/sdk/@types/node": ["@types/node@18.19.100", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-ojmMP8SZBKprc3qGrGk8Ujpo80AXkrP7G2tOT4VWr5jlr5DHjsJF+emXJz+Wm0glmy4Js62oKMdZZ6B9Y+tEcA=="], + "@radix-ui/react-progress/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.4.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.0.2", "tslib": "^2.4.0" }, "bundled": true }, "sha512-4m62DuCE07lw01soJwPiBGC0nAww0Q+RY70VZ+n49yDIO13yyinhbWCeNnaob0lakDtWQzSdtNWzJeOJt2ma+g=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.4.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-pBPWdu6MLKROBX05wSNKcNb++m5Er+KQ9QkB+WVM+pW2Kx9hoSrVTnu3BdkI5eBLZoKu/J6mW/B6i6bJB2ytXQ=="], @@ -877,6 +879,8 @@ "@anthropic-ai/sdk/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="], + "@radix-ui/react-progress/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "groq-sdk/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="], "openai/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="], diff --git a/message.txt b/message.txt new file mode 100644 index 0000000..402d946 --- /dev/null +++ b/message.txt @@ -0,0 +1,3 @@ +WHY ISNT THIS SHIT WORKING FOR FUCKS SAKE + +pepe from server! \ No newline at end of file diff --git a/package.json b/package.json index 9fec0ca..8b39a03 100644 --- a/package.json +++ b/package.json @@ -9,10 +9,10 @@ "start": "bunx --bun waku start" }, "dependencies": { - "@edge-runtime/cookies": "^6.0.0", "@hookform/resolvers": "^5.0.1", "@radix-ui/react-dialog": "^1.1.13", "@radix-ui/react-label": "^2.1.6", + "@radix-ui/react-progress": "^1.1.7", "@radix-ui/react-select": "^2.2.4", "@radix-ui/react-slot": "^1.2.2", "class-variance-authority": "^0.7.1", diff --git a/src/actions/login.ts b/src/actions/login.ts index 4ceb13f..ee15fe6 100644 --- a/src/actions/login.ts +++ b/src/actions/login.ts @@ -1,9 +1,7 @@ "use server"; -import { AsyncRes } from "@/lib/types"; +import type { AsyncRes } from "@/lib/types"; import db from "../lib/db"; -import cookie from "cookie"; -import { cookies } from "../lib/server/cookiebridge"; -import { unstable_redirect, unstable_rerenderRoute } from "waku/router/server"; +import { useCookies } from "../lib/server/cookiebridge"; export type FormState = { name?: string; @@ -11,21 +9,30 @@ export type FormState = { error?: string; success?: boolean; }; -async function call(formData: FormData, register: boolean) { +async function call( + formData: FormData, + register: boolean, +): AsyncRes { const nam = formData.get("username"); const creds = formData.get("password"); const password = await Bun.password.hash(creds!.toString()); const name = nam!.toString(); - const res = register - ? db.addUser(name, password) - : await db.loginUser(name, creds!.toString()); - return res; + try { + const res = register + ? db.addUser(name, password) + : await db.loginUser(name, creds!.toString()); + return res; + } catch (e) { + console.error(e); + return { error: `${e}` }; + } } export async function postRegister( prevState: FormState, formData: FormData, ): Promise { + // "use server"; const res = await call(formData, true); console.log("reg res", res); if ("error" in res) return { error: "Something went wrong" }; @@ -37,15 +44,15 @@ export async function postRegister( export async function postLogin( prevState: FormState, formData: FormData, -): Promise { - return prevState; - // const res = await call(formData, false); - // if ("error" in res) return { error: res.error }; - // else { - // setCookie(res.ok as number); - // return prevState; - // // return { success: true }; - // } +): Promise { + console.log(formData); + const res = await call(formData, false); + console.log({ res }); + if ("error" in res) return { error: res.error }; + else { + setCookie(res.ok as number); + return { success: true }; + } } async function setCookie(userId: number) { const COOKIE_EXPIRY = Date.now() + 1000 * 60 * 60 * 24 * 30; @@ -54,13 +61,13 @@ async function setCookie(userId: number) { const { randomBytes } = await import("node:crypto"); const cokistring = randomBytes(32).toBase64(); const res = db.setCookie(cokistring, userId, COOKIE_EXPIRY); - const { setCookie } = cookies(); - setCookie("sorlang", cokistring, COOKIE_OPTS); + const { setCookie } = useCookies(); + setCookie(cokistring); // unstable_redirect("/"); } -export async function postLogout(prev: number) { - const { delCookie } = cookies(); - const rest = delCookie("sorlang"); - return prev + 9; -} +// export async function postLogout(prev: number) { +// const { delCookie } = cookies(); +// const rest = delCookie("sorlang"); +// return prev + 9; +// } 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 ( +//
+// +// +// Profile +// {state} +// +// +//

Username: {user.name}

+//

User ID: {user.id}

+//
+// +// +// +//
+//
+// ); +// } +// "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 = ({ + 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 ( +
+
+ {/* Front of the card */} +
+ + {data.expression.ipa.map((ip, i) => ( + + {ip.ipa} + + ))} + +

+ {data.expression.spelling} +

+
+ {" "} + {/* Placeholder for spacing, mimics bottom controls */} + + Flip + +
+
+ + {/* Back of the card */} +
+ + {data.expression.senses.map((ss, i) => ( +
+ {ss.senses.map((sss, i) => ( +
+ {sss.glosses.map((ssss, i) => ( +

{ssss}

+ ))} +
+ ))} +
+ ))} +
+

+ {data.note} +

+
+ + Flip + +
+
+
+
+ ); +}; + +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(0); + const [currentIndex, setCurrentIndex] = useState(0); + const [isFlipped, setIsFlipped] = useState(false); + const [animationDirection, setAnimationDirection] = useState< + "enter-left" | "enter-right" | "exit-left" | "exit-right" | "none" + >("none"); + const flashcards = data.cards; + const [isAnimating, setIsAnimating] = useState(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 ( +
+

No flashcards available.

+
+ ); + } + + const currentCard = flashcards[currentIndex]; + if (!currentCard) return

wtf

; + + return ( +
+
+ {/* This div is for positioning the card and managing overflow during animations */} +
+ {" "} + {/* Ensure this matches card height */} + +
+
+ +
+ +
+

+ Card {currentIndex + 1} of {flashcards.length} +

+ +
+ +
+ +
+ Use Arrow Keys (← →) to navigate, Space/Enter to flip. +
+
+ ); +} + +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( + // isReg ? postRegister : postLogin, + // { error: "" }, + // "/login", + // ); const [state, formAction, isPending] = useActionState( - isReg ? postRegister : postLogin, + postLogin, { error: "" }, "/login", ); - // const nav = useRouter(); - // useEffect(() => { - // if (state.success) nav.replace("/"); - // }, [state]); + console.log({ state }); return (
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(""); + const [pastedImageUrl, setPastedImageUrl] = useState(null); + const [pastedImageFile, setPastedImageFile] = useState(null); // Store the file for extraction + const [isAnalyzing, setIsAnalyzing] = useState(false); + const [isExtracting, setIsExtracting] = useState(false); + + const textareaRef = useRef(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 ( +
+ + + + Sorlang + + + +