feat: Add Toast functionality

This commit is contained in:
sigmasternchen 2024-09-20 20:17:55 +02:00
parent 7d049af52d
commit 8b046d6b59
3 changed files with 59 additions and 10 deletions

View file

@ -93,4 +93,24 @@ body {
.key.Right {
background-color: #090;
border: none;
}
.toast {
position: fixed;
top: 0;
left: 50%;
transform: translate(-50%, -100%);
min-height: 50px;
background-color: lightgrey;
width: 400px;
border-radius: 0 0 5px 5px;
text-align: center;
font-size: 20px;
padding-top: 10px;
padding-bottom: 10px;
transition: transform 0.3s;
}
.toast.show {
transform: translate(-50%, 0);
}

View file

@ -1,17 +1,21 @@
import React from "react";
import React, {useState} from "react";
import {Field} from "./Field";
import {calculateDifference} from "../logic/game-logic";
import {id, objectMap, zip} from "../utils";
import {Keyboard} from "./Keyboard";
import {CellState, sortCellStates} from "../model/CellState";
import {Toast} from "./Toast";
export const App = () => {
const [pastGuesses, setPastGuesses] = useState([]);
const [currentGuess, setCurrentGuess] = useState("");
const [message, setMessage] = useState("");
const length = 5;
const correct = "guess";
const [pastGuesses, setPastGuesses] = React.useState([]);
const [currentGuess, setCurrentGuess] = React.useState("");
const fieldDataForPastGuesses = pastGuesses
.map(guess => guess.toUpperCase())
@ -41,17 +45,21 @@ export const App = () => {
);
const inputHandler = key => {
if (currentGuess.length > 0 && key === "BACK") {
setCurrentGuess(currentGuess.substring(0, currentGuess.length - 1));
} else if (currentGuess.length >= length) {
if (key === "ENTER") {
if (key === "ENTER") {
if (currentGuess.length === length) {
setPastGuesses(pastGuesses.concat([currentGuess]));
setCurrentGuess("");
} else {
// do nothing
setMessage("Not enough letters.");
}
} else if (key === "BACK") {
if (currentGuess.length > 0) {
setCurrentGuess(currentGuess.substring(0, currentGuess.length - 1));
}
} else {
if (currentGuess.length < length) {
setCurrentGuess(currentGuess + key);
}
} else if (key.length === 1) {
setCurrentGuess(currentGuess + key);
}
};
@ -65,11 +73,13 @@ export const App = () => {
])
return <div>
<Field
size={[5, 6]}
fieldData={fieldData}
/>
<Keyboard used={usedWithState} onKey={inputHandler}/>
<Toast message={message} />
</div>
};

19
src/components/Toast.jsx Normal file
View file

@ -0,0 +1,19 @@
import React, {useEffect, useState} from 'react';
export const Toast = ({message}) => {
const [oldMessage, setOldMessage] = useState("");
const [show, setShow] = useState(false);
useEffect(() => {
if (message && message !== oldMessage) {
setOldMessage(message);
setShow(true);
setTimeout(() => setShow(false), 2000);
}
});
return <div className={"toast " + (show ? "show" : "")}>
{message}
</div>
}