Skip to content

Commit

Permalink
Merge pull request #154 from nepalcodes/tajpuiya-flahscards
Browse files Browse the repository at this point in the history
immplemented change language to flahscards and dictionary
  • Loading branch information
binamkayastha authored Jul 28, 2024
2 parents 34aa605 + 708359d commit 33ad9ed
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 151 deletions.
55 changes: 47 additions & 8 deletions nepalingo-web/src/components/Flashcard.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import Card from "@/components/Card";
import Button from "@/components/Button";
import useDictionary from "@/hooks/useDictionary";
import { generate } from "random-words";
import ReactGA from "react-ga4";
import { useLanguage } from "@/hooks/Langauge";

const Flashcard: React.FC = () => {
ReactGA.event({
Expand All @@ -13,12 +13,26 @@ const Flashcard: React.FC = () => {
nonInteraction: true, // optional, true/false
transport: "xhr", // optional, beacon/xhr/image
});
const [word, setWord] = useState("salt");
const { selectedLanguage } = useLanguage();
const [word, setWord] = useState("Today");
const [isFlipped, setIsFlipped] = useState(false);
const [index, setIndex] = useState(0);

useEffect(() => {
// Make sure flashcard is updated when language is changed
handleNextWord();
}, [selectedLanguage]);

function getNextIndex(wordArray: Array<string>) {
const newIndex = (index + 1) % wordArray.length;
return newIndex;
}

const { data, isLoading, error } = useDictionary({
language: "newari",
language: selectedLanguage || "",
word,
});

if (error) {
console.error(error);
}
Expand All @@ -27,21 +41,44 @@ const Flashcard: React.FC = () => {
setIsFlipped(!isFlipped);
};

const handleNextWord = () => {
setWord(generate() as string);
const handleNextWord = async () => {
let wordArray: Array<string> = [];
if (selectedLanguage === "Newari") {
wordArray = ["salt", "hello", "go"];
} else if (selectedLanguage === "Tajpuriya") {
const wordText = await fetch("./dictionaries/TajpuriyaDictionary.csv")
.then((r) => r.text())
.catch((error) => {
console.error("Error fetching words:", error);
});

if (wordText) {
wordArray = wordText.split("\n").map((line: string) =>
line
.split(",")[0]
.trim()
.replace(/(^"|"$)/g, ""),
);
}
}

const newIndex = getNextIndex(wordArray);
setIndex(newIndex);
setWord(wordArray[newIndex]);
setIsFlipped(false);
};

if (isLoading) return <div>Loading</div>;
if (error?.response?.length) handleNextWord();
const meaning = data && data.meanings[0];

const meaning = data ? data.meanings[0] : null;

return (
<div className="max-w-md mx-auto p-4 flex justify-center border-2">
<div className="mx-auto max-w-[calc(100% - 20px)]">
{error ? (
<div>Error: {error.message}</div>
) : (
) : selectedLanguage ? (
<Card
Word={word}
TranslatedWord={meaning?.meaningOriginal || ""}
Expand All @@ -51,6 +88,8 @@ const Flashcard: React.FC = () => {
PronounciationUrl={meaning?.audio?.uri}
isFlipped={isFlipped}
/>
) : (
<div>No data available</div>
)}

<div className="flex justify-between mt-4">
Expand Down
2 changes: 1 addition & 1 deletion nepalingo-web/src/hooks/Langauge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export type LanguageKey = keyof typeof Languages;

export const Languages = {
Newari: "newari",
Tajpuriya: "coming soon",
Tajpuriya: "tajpuriya",
Maithili: "coming soon",
} as const;

Expand Down
58 changes: 0 additions & 58 deletions nepalingo-web/src/hooks/getTajpuriya.tsx

This file was deleted.

43 changes: 24 additions & 19 deletions nepalingo-web/src/hooks/useDictionary.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import useNewari from "@/hooks/useNewari";
import useSWR from "swr";

import { Language } from "./Langauge";
import { getNewariWord } from "@/lib/getNewariWord";
import { getTajpuriyaWord } from "@/lib/getTajpuriyaWord";

export type DictionaryProps = {
language: Language;
language: string;
word: string;
};

Expand All @@ -29,26 +30,30 @@ export type DictionaryResponse = {
meanings: Array<Meaning>;
};

///Use case
//const {data, isLoading, error} = useDictionary('newari', "Hello")
async function getFetcherByLanguage(
language: string,
word?: string,
): Promise<DictionaryResponse> {
if (!word) {
word = "hello";
}

const useDictionary = ({ language, ...otherProps }: DictionaryProps) => {
switch (language) {
case "newari":
return useNewari(otherProps);
// case 'tajpuriya':
// return ({
// error: { message: "Sorry the language does not exist" },
// data: null,
// isLoading: false,
// })
case "Newari":
return await getNewariWord(word);
case "Tajpuriya":
return await getTajpuriyaWord(word);
default:
return {
error: { message: "Sorry the language does not exist" },
data: undefined,
isLoading: false,
};
throw new Error(`Language ${language} not supported`);
}
}

const useDictionary = ({ language, word }: DictionaryProps) => {
const cacheKey = word ? `/${language}/${word}` : null;
const { data, error, isLoading } = useSWR(cacheKey, () =>
getFetcherByLanguage(language, word),
);
return { data, error, isLoading };
};

export default useDictionary;
38 changes: 0 additions & 38 deletions nepalingo-web/src/hooks/useTajpuriya.tsx

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
import useSWR from "swr";
import { DictionaryProps, DictionaryResponse } from "@/hooks/useDictionary";
import { DictionaryResponse } from "@/hooks/useDictionary";

const fetcher = (url: string) =>
fetch(import.meta.env.VITE_NEPALBHASA_API_URL + url, {}).then((r) =>
r.json(),
);
export async function getNewariWord(word: string): Promise<DictionaryResponse> {
const api_endpoint = `/dict/en/search/${word}`;
const data = await fetch(
import.meta.env.VITE_NEPALBHASA_API_URL + api_endpoint,
{},
).then((r) => r.json());

const useNewari = (props: Omit<DictionaryProps, "language">) => {
const { data, error, isLoading } = useSWR(
props.word ? `/dict/en/search/${props.word}` : null,
fetcher,
);
console.log(data);

const customError = data?.errors.length
? { status: true, response: data.errors, message: data.errors[0] }
: error;
if (data?.errors.length) {
console.error(data.errors);
throw new Error(data.errors[0]);
}

const response: DictionaryResponse = {
language: "newari",
word: props.word,
word: word,
//Mapping the meanings from the api to create a custom response based on DictionaryResponse
meanings:
data?.meanings.length == 0
Expand Down Expand Up @@ -58,8 +53,5 @@ const useNewari = (props: Omit<DictionaryProps, "language">) => {
}),
),
};

return { data: response, error: customError, isLoading };
};

export default useNewari;
return response;
}
37 changes: 37 additions & 0 deletions nepalingo-web/src/lib/getTajpuriyaWord.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { DictionaryResponse } from "@/hooks/useDictionary";

export async function getTajpuriyaWord(
word: string,
): Promise<DictionaryResponse> {
const wordText = await fetch("./dictionaries/TajpuriyaDictionary.csv")
.then((r) => r.text())
.catch((error) => {
console.error("Error fetching words:", error);
});

if (!wordText) {
throw new Error("Error fetching tajpuriya CSV");
}
const dictArray = wordText.split("\n");

for (const line of dictArray) {
const [englishWord, tajpuriyaWord] = line
.split(",")
.map((word) => word.trim().replace(/(^"|"$)/g, ""));

if (englishWord.toLowerCase() == word.toLowerCase()) {
return {
language: "tajpuriya",
word: word,
meanings: [
{
language: "tajpuriya",
meaningOriginal: tajpuriyaWord,
meaningEn: englishWord,
},
],
};
}
}
throw new Error(`Word "${word}" not found in tajpuriya dictionary`);
}
8 changes: 3 additions & 5 deletions nepalingo-web/src/pages/DictionaryPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import CustomTextInput from "@/components/CustomTextInput";
import Button from "@/components/Button";
import useDictionary from "@/hooks/useDictionary";
import SearchResponseCard from "@/components/SearchResponseCard";
import { useLanguage } from "@/hooks/Langauge";

const DictionaryPage: React.FC = () => {
const [searchTerm, setSearchTerm] = useState<string>("");
const { selectedLanguage } = useLanguage();
const { data, isLoading, error } = useDictionary({
language: "newari",
language: selectedLanguage || "",
word: searchTerm,
});
console.log(data?.meanings);

const handleSearchClick = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
Expand Down Expand Up @@ -42,9 +43,6 @@ const DictionaryPage: React.FC = () => {
</Button>
</form>

{!isLoading && !data && error && (
<p className="mt-2 text-red-600">{error.message}</p>
)}
<div className="p-0 mt-5 gap-4 flex flex-col ">
{isLoading && <p className="mt-2 text-gray-600 ">Loading...</p>}
{data && data.meanings?.length > 0
Expand Down

0 comments on commit 33ad9ed

Please sign in to comment.