Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mikas happy thoughts project #107

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
@import url("https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap");

* {
box-sizing: border-box;
margin: 0;
padding: 0;
}

body {
font-family: "Roboto Mono", monospace;
width: 100vw;
margin: 0 auto;
overflow-x: hidden;
}

.thought-container {
border: 1px solid black;
padding: 20px;
margin: 20px auto;
box-shadow: 7px 8px 0px rgba(0, 0, 0, 1);
max-width: 450px;
width: 90%;
}

.input-form {
background-color: #cdc3c082;
display: flex;
flex-direction: column;
}

form {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 100%;
}

input[type="text"] {
width: 100%;
padding: 20px;
margin: 20px 0;
font-size: 16px;
}

ul,
li {
list-style: none;
color: #828282;
display: flex;
justify-content: space-between;
}

button {
border: none;
background-color: #cdc3c082;
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 10px;
font-size: 16px;
cursor: pointer;
}

.submit {
border-radius: 20px;
width: 100%;
max-width: 300px;
padding: 10px 20px;
margin: 10px 0;
}

/* button:hover {
background-color: #cdc3c0;
} */

.liked {
background-color: #da2c3d71;
color: rgb(0, 0, 0, 0.8);
font-weight: 550;
}

.heart-container {
display: flex;
align-items: center;
}

.thought-footer {
display: flex;
justify-content: space-between;
align-items: center;
}

.thought-message {
margin-bottom: 20px;
font-size: 16px;
line-height: 1.4;
word-wrap: break-word;
}

.char-counter {
margin-bottom: 10px;
}

.error {
color: red;
}



/* media queries for different screen sizes */
@media (min-width: 768px) {
.thought-container {
margin: 30px auto;
}

.submit {
width: auto;
}

.thought-message {
font-size: 18px;
}
}

@media (min-width: 1024px) {
.thought-container {
margin: 50px auto;
}

.thought-message {
font-size: 20px;
}
}

/* touch-friendly sizing for mobile */
@media (max-width: 480px) {
button {
width: 44px;
height: 44px;
}

.thought-footer {
flex-wrap: wrap;
gap: 10px;
}
}
64 changes: 63 additions & 1 deletion src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,65 @@
import { useEffect, useState } from "react";
import "./App.css";
import { Thought } from "./components/Thought";
import { InputForm } from "./components/InputForm";
import { fetchData, URL } from "./utils/api";

export const App = () => {
return <div>Find me in src/app.jsx!</div>;
const [thoughts, setThoughts] = useState([]);
const [likedThoughts, setLikedThoughts] = useState([]);
const [message, setMessage] = useState("");
const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
fetchData().then((data) => setThoughts(data));
}, []);

const handleHeartClick = async (id) => {
try {
const res = await fetch(`${URL}/${id}/like`, {
method: "POST",
});

if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}

const updatedThought = await res.json();

// Update thoughts with new heart count from server
setThoughts((prevThoughts) =>
prevThoughts.map((thought) =>
thought._id === id
? { ...thought, hearts: updatedThought.hearts }
: thought
)
);

// Is not already liked, dd to likedThoughts array
setLikedThoughts((prev) =>
prev.includes(id)
? prev.filter((thoughtId) => thoughtId !== id)
: [...prev, id]
);
} catch (error) {
console.error("Error liking thought:", error);
}
};

return (
thoughts && (
<>
<InputForm
setMessage={setMessage}
message={message}
setThoughts={setThoughts}
/>
<Thought
thoughts={thoughts}
handleHeartClick={handleHeartClick}
likedThoughts={likedThoughts}
/>
</>
)
);
};
11 changes: 11 additions & 0 deletions src/components/HeartButton.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const HeartButton = ({ thoughtId, hearts, handleHeartClick, isLiked }) => (
<div className="heart-container">
<button
onClick={() => handleHeartClick(thoughtId)}
className={isLiked ? "liked" : ""}
>
❤️
</button>
<li>x {hearts}</li>
</div>
);
54 changes: 54 additions & 0 deletions src/components/InputForm.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { URL } from "../utils/api";

export const InputForm = ({ setMessage, message, setThoughts }) => {
const handleSubmit = async (event) => {
event.preventDefault();

try {
const res = await fetch(URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message: message }),
});

if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}

const data = await res.json();
setThoughts((prevThoughts) => [data, ...prevThoughts]);
setMessage("");
} catch (error) {
console.error("Error submitting thought:", error);
}
Comment on lines +7 to +25
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice with try/catch!

};

const MAX_CHARS = 140;

return (
<div className="thought-container input-form">
What's making you happy right now?
<form onSubmit={handleSubmit}>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
required
/>
Comment on lines +34 to +39
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't forget labels when working with form elements! And perhaps this should be a textarea since it's a multiline input?

<div
className={`char-counter ${message.length > MAX_CHARS ? "error" : ""}`}
>
{MAX_CHARS - message.length} characters remaining
</div>
<button
disabled={message.length < 5 || message.length > MAX_CHARS}
className={`submit ${message.length < 5 || message.length > MAX_CHARS ? "disabled" : "liked"}`}
>
❤️ Send Happy Thought ❤️
</button>
</form>
</div>
);
};
3 changes: 3 additions & 0 deletions src/components/MessageContent.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const MessageContent = ({ message }) => (
<div className="thought-message">{message}</div>
);
20 changes: 20 additions & 0 deletions src/components/MessageFooter.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { HeartButton } from "./HeartButton";
import { formatTimeAgo } from "../utils/api";

export const MessageFooter = ({
thoughtId,
hearts,
createdAt,
handleHeartClick,
isLiked,
}) => (
<div className="thought-footer">
<HeartButton
thoughtId={thoughtId}
hearts={hearts}
handleHeartClick={handleHeartClick}
isLiked={isLiked}
/>
<li>{formatTimeAgo(createdAt)}</li>
</div>
);
17 changes: 17 additions & 0 deletions src/components/Thought.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MessageContent } from "./MessageContent";
import { MessageFooter } from "./MessageFooter";

export const Thought = ({ thoughts, handleHeartClick, likedThoughts }) => {
return thoughts.map((thought) => (
<div key={thought._id} className="thought-container">
<MessageContent message={thought.message} />
<MessageFooter
thoughtId={thought._id}
hearts={thought.hearts}
createdAt={thought.createdAt}
handleHeartClick={handleHeartClick}
isLiked={likedThoughts.includes(thought._id)}
/>
</div>
));
};
30 changes: 30 additions & 0 deletions src/utils/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export const URL = "http://localhost:9000/happy-thoughts";

export const fetchData = async () => {
const response = await fetch(URL);
const data = await response.json();
return data;
};

export const formatTimeAgo = (timestamp) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! However, does this really belong in an api.js file? 👀

const now = new Date();
const messageDate = new Date(timestamp);
const diffInSeconds = Math.floor((now - messageDate) / 1000);

if (diffInSeconds < 60) {
return `${diffInSeconds} seconds ago`;
}

const diffInMinutes = Math.floor(diffInSeconds / 60);
if (diffInMinutes < 60) {
return `${diffInMinutes} ${diffInMinutes === 1 ? "minute" : "minutes"} ago`;
}

const diffInHours = Math.floor(diffInMinutes / 60);
if (diffInHours < 24) {
return `${diffInHours} ${diffInHours === 1 ? "hour" : "hours"} ago`;
}

const diffInDays = Math.floor(diffInHours / 24);
return `${diffInDays} ${diffInDays === 1 ? "day" : "days"} ago`;
};