diff --git a/.gitignore b/.gitignore index 7639805208..2401ea928a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -starter/node_modules \ No newline at end of file +starter/node_modules +starter/package-lock.json \ No newline at end of file diff --git a/README.md b/README.md index cc96416d7f..aea448b09e 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,64 @@ # MyReads Project - -This is the starter template for the final assessment project for Udacity's React Fundamentals course. The goal of this template is to save you time by providing a static example of the CSS and HTML markup that may be used, but without any of the React code that is needed to complete the project. If you choose to start with this template, your job will be to add interactivity to the app by refactoring the static code in this template. - -Of course, you are free to start this project from scratch if you wish! Just be sure to use [Create React App](https://reactjs.org/docs/create-a-new-react-app.html) to bootstrap the project. - -## TL;DR - +My project is a React application called "MyReads" that allows users to manage their book collection by organizing them into different shelves: "Currently Reading", "Want to Read", and "Read". The application uses a backend server provided by Udacity to fetch book data and update the book shelves. + +# Features +- Users can sign up and login +- List of books which user has added to the bookshelf +- Users can search for books using the backend server's search functionality. +- Users can add books to their collection and organize them into different shelves. +- Users can update the shelf of a book in their collection. +- Users can remove books from their collection. +- Users can see the detail information of book + +## Getting Started To get started developing right away: - +- navigate to the project directory: `cd starter` - install all project dependencies with `npm install` - start the development server with `npm start` -## What You're Getting +# Usage +1. After run command `npm start`, you should be able to see the application running in your browser at `http://localhost:3000`. +2. Click "Create a new account" to create a user to login +3. Login with your account you have created +4. Click the "Search" button to search for books using the backend server's search functionality. +5. Enter a book title or author in the search input field. +6. Select a book from the search results to add it to your bookshelf. +7. Click the "drop-down list" button to add the selected book to your bookshelf. +8. Click the "Currently Reading", "Want to Read", or "Read" buttons to organize the books in your bookshelf. +9. Click the "None" option to remove a book from your bookshelf. +10. Click the "I" icon at the book cover if you want to see the detail information of book. +11. Drag and drop the book to other bookshelf if you want to move books between shelves +11. Click the "Logout" button if you want to log out of the app. + +## Folder Structure ```bash -├── CONTRIBUTING.md ├── README.md - This file. -├── SEARCH_TERMS.md # The whitelisted short collection of available search terms for you to use with your app. -├── package.json # npm package manager file. It's unlikely that you'll need to modify this. -├── public -│ ├── favicon.ico # React Icon, You may change if you wish. -│ └── index.html # DO NOT MODIFY -└── src - ├── App.css # Styles for your app. Feel free to customize this as you desire. - ├── App.js # This is the root of your app. Contains static HTML right now. - ├── App.test.js # Used for testing. Provided with Create React App. Testing is encouraged, but not required. - ├── BooksAPI.js # A JavaScript API for the provided Udacity backend. Instructions for the methods are below. - ├── icons # Helpful images for your app. Use at your discretion. - │ ├── add.svg - │ ├── arrow-back.svg - │ └── arrow-drop-down.svg - ├── index.css # Global styles. You probably won't need to change anything here. - └── index.js # You should not need to modify this file. It is used for DOM rendering only. +├── starter ── + ├── package.json # npm package manager file. It's unlikely that you'll need to modify this. + ├── public + │ ├── favicon.ico # React Icon, You may change if you wish. + │ └── index.html # DO NOT MODIFY + └── src + ├── App.css # Styles for your app. Feel free to customize this as you desire. + ├── App.js # This is the root of your app. Contains static HTML right now. + ├── Book.js # component represents a single book and displays its information, including the cover image, title, authors, and shelf status + ├── BookDetail.js # component represents details about the book + ├── BookGrid.js # component represents a grid of books + ├── BookShelf.js # component represents a bookshelf and displays a collection of books + ├── Header.js # component show username and Logout function + ├── Login.js # handle login function + ├── Main.js # contain book collection + ├── SearchBook.js # component allows users to search for books using the backend server's search method. + ├── Signup.js # register user + ├── BooksAPI.js # A JavaScript API for the provided Udacity backend. Instructions for the methods are below. + ├── icons # Helpful images for your app. Use at your discretion. + │ ├── add.svg + │ ├── arrow-back.svg + │ └── arrow-drop-down.svg + │ └── information.svg + ├── index.css # Global styles. You probably won't need to change anything here. + └── index.js # You should not need to modify this file. It is used for DOM rendering only. ``` Remember that good React design practice is to create new JS files for each component and use import/require statements to include them where they are needed. @@ -40,18 +67,30 @@ Remember that good React design practice is to create new JS files for each comp To simplify your development process, we've provided a backend server for you to develop against. The provided file [`BooksAPI.js`](src/BooksAPI.js) contains the methods you will need to perform necessary operations on the backend: +- [`get`](#get) - [`getAll`](#getall) - [`update`](#update) - [`search`](#search) -### `getAll` +### `get` Method Signature: ```js -getAll(); +get(bookId); ``` +- bookId: `` id of book +- Returns a Promise which resolves to a JSON object containing a book. + + +### `getAll` +Method Signature: + +```js +getAll(token); +``` +- token: `` token for specific user - Returns a Promise which resolves to a JSON object containing a collection of book objects. - This collection represents the books currently in the bookshelves in your app. @@ -60,11 +99,12 @@ getAll(); Method Signature: ```js -update(book, shelf); +update(book, shelf,token); ``` - book: `` containing at minimum an `id` attribute - shelf: `` contains one of ["wantToRead", "currentlyReading", "read"] +- token: `` token for specific user - Returns a Promise which resolves to a JSON object containing the response data of the POST request ### `search` @@ -80,15 +120,6 @@ search(query); - These books do not know which shelf they are on. They are raw results only. You'll need to make sure that books have the correct state while on the search page. ## Important - The backend API uses a fixed set of cached search results and is limited to a particular set of search terms, which can be found in [SEARCH_TERMS.md](SEARCH_TERMS.md). That list of terms are the _only_ terms that will work with the backend, so don't be surprised if your searches for Basket Weaving or Bubble Wrap don't come back with any results. +https://github.com/udacity/reactnd-project-myreads-starter/blob/master/SEARCH_TERMS.md -## Create React App - -This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). You can find more information on how to perform common tasks [here](https://github.com/facebook/create-react-app/blob/main/packages/cra-template/template/README.md). - -## Contributing - -This repository is the starter code for _all_ Udacity students. Therefore, we most likely will not accept pull requests. - -For details, check out [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/starter/README.md b/starter/README.md index cc96416d7f..aea448b09e 100644 --- a/starter/README.md +++ b/starter/README.md @@ -1,37 +1,64 @@ # MyReads Project - -This is the starter template for the final assessment project for Udacity's React Fundamentals course. The goal of this template is to save you time by providing a static example of the CSS and HTML markup that may be used, but without any of the React code that is needed to complete the project. If you choose to start with this template, your job will be to add interactivity to the app by refactoring the static code in this template. - -Of course, you are free to start this project from scratch if you wish! Just be sure to use [Create React App](https://reactjs.org/docs/create-a-new-react-app.html) to bootstrap the project. - -## TL;DR - +My project is a React application called "MyReads" that allows users to manage their book collection by organizing them into different shelves: "Currently Reading", "Want to Read", and "Read". The application uses a backend server provided by Udacity to fetch book data and update the book shelves. + +# Features +- Users can sign up and login +- List of books which user has added to the bookshelf +- Users can search for books using the backend server's search functionality. +- Users can add books to their collection and organize them into different shelves. +- Users can update the shelf of a book in their collection. +- Users can remove books from their collection. +- Users can see the detail information of book + +## Getting Started To get started developing right away: - +- navigate to the project directory: `cd starter` - install all project dependencies with `npm install` - start the development server with `npm start` -## What You're Getting +# Usage +1. After run command `npm start`, you should be able to see the application running in your browser at `http://localhost:3000`. +2. Click "Create a new account" to create a user to login +3. Login with your account you have created +4. Click the "Search" button to search for books using the backend server's search functionality. +5. Enter a book title or author in the search input field. +6. Select a book from the search results to add it to your bookshelf. +7. Click the "drop-down list" button to add the selected book to your bookshelf. +8. Click the "Currently Reading", "Want to Read", or "Read" buttons to organize the books in your bookshelf. +9. Click the "None" option to remove a book from your bookshelf. +10. Click the "I" icon at the book cover if you want to see the detail information of book. +11. Drag and drop the book to other bookshelf if you want to move books between shelves +11. Click the "Logout" button if you want to log out of the app. + +## Folder Structure ```bash -├── CONTRIBUTING.md ├── README.md - This file. -├── SEARCH_TERMS.md # The whitelisted short collection of available search terms for you to use with your app. -├── package.json # npm package manager file. It's unlikely that you'll need to modify this. -├── public -│ ├── favicon.ico # React Icon, You may change if you wish. -│ └── index.html # DO NOT MODIFY -└── src - ├── App.css # Styles for your app. Feel free to customize this as you desire. - ├── App.js # This is the root of your app. Contains static HTML right now. - ├── App.test.js # Used for testing. Provided with Create React App. Testing is encouraged, but not required. - ├── BooksAPI.js # A JavaScript API for the provided Udacity backend. Instructions for the methods are below. - ├── icons # Helpful images for your app. Use at your discretion. - │ ├── add.svg - │ ├── arrow-back.svg - │ └── arrow-drop-down.svg - ├── index.css # Global styles. You probably won't need to change anything here. - └── index.js # You should not need to modify this file. It is used for DOM rendering only. +├── starter ── + ├── package.json # npm package manager file. It's unlikely that you'll need to modify this. + ├── public + │ ├── favicon.ico # React Icon, You may change if you wish. + │ └── index.html # DO NOT MODIFY + └── src + ├── App.css # Styles for your app. Feel free to customize this as you desire. + ├── App.js # This is the root of your app. Contains static HTML right now. + ├── Book.js # component represents a single book and displays its information, including the cover image, title, authors, and shelf status + ├── BookDetail.js # component represents details about the book + ├── BookGrid.js # component represents a grid of books + ├── BookShelf.js # component represents a bookshelf and displays a collection of books + ├── Header.js # component show username and Logout function + ├── Login.js # handle login function + ├── Main.js # contain book collection + ├── SearchBook.js # component allows users to search for books using the backend server's search method. + ├── Signup.js # register user + ├── BooksAPI.js # A JavaScript API for the provided Udacity backend. Instructions for the methods are below. + ├── icons # Helpful images for your app. Use at your discretion. + │ ├── add.svg + │ ├── arrow-back.svg + │ └── arrow-drop-down.svg + │ └── information.svg + ├── index.css # Global styles. You probably won't need to change anything here. + └── index.js # You should not need to modify this file. It is used for DOM rendering only. ``` Remember that good React design practice is to create new JS files for each component and use import/require statements to include them where they are needed. @@ -40,18 +67,30 @@ Remember that good React design practice is to create new JS files for each comp To simplify your development process, we've provided a backend server for you to develop against. The provided file [`BooksAPI.js`](src/BooksAPI.js) contains the methods you will need to perform necessary operations on the backend: +- [`get`](#get) - [`getAll`](#getall) - [`update`](#update) - [`search`](#search) -### `getAll` +### `get` Method Signature: ```js -getAll(); +get(bookId); ``` +- bookId: `` id of book +- Returns a Promise which resolves to a JSON object containing a book. + + +### `getAll` +Method Signature: + +```js +getAll(token); +``` +- token: `` token for specific user - Returns a Promise which resolves to a JSON object containing a collection of book objects. - This collection represents the books currently in the bookshelves in your app. @@ -60,11 +99,12 @@ getAll(); Method Signature: ```js -update(book, shelf); +update(book, shelf,token); ``` - book: `` containing at minimum an `id` attribute - shelf: `` contains one of ["wantToRead", "currentlyReading", "read"] +- token: `` token for specific user - Returns a Promise which resolves to a JSON object containing the response data of the POST request ### `search` @@ -80,15 +120,6 @@ search(query); - These books do not know which shelf they are on. They are raw results only. You'll need to make sure that books have the correct state while on the search page. ## Important - The backend API uses a fixed set of cached search results and is limited to a particular set of search terms, which can be found in [SEARCH_TERMS.md](SEARCH_TERMS.md). That list of terms are the _only_ terms that will work with the backend, so don't be surprised if your searches for Basket Weaving or Bubble Wrap don't come back with any results. +https://github.com/udacity/reactnd-project-myreads-starter/blob/master/SEARCH_TERMS.md -## Create React App - -This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). You can find more information on how to perform common tasks [here](https://github.com/facebook/create-react-app/blob/main/packages/cra-template/template/README.md). - -## Contributing - -This repository is the starter code for _all_ Udacity students. Therefore, we most likely will not accept pull requests. - -For details, check out [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/starter/package.json b/starter/package.json index 639ffdb7ab..ce5ffcebea 100644 --- a/starter/package.json +++ b/starter/package.json @@ -7,8 +7,11 @@ "@testing-library/react": "^11.1.0", "@testing-library/user-event": "^12.1.10", "react": "^17.0.2", + "react-beautiful-dnd": "^13.1.1", "react-dom": "^17.0.2", + "react-router-dom": "^6.23.0", "react-scripts": "4.0.3", + "sqlite3": "^5.1.7", "web-vitals": "^1.0.1" }, "scripts": { diff --git a/starter/src/App.css b/starter/src/App.css index 55870579c1..6590fce779 100644 --- a/starter/src/App.css +++ b/starter/src/App.css @@ -69,7 +69,7 @@ body, .search-books-bar { position: fixed; - width: 100%; + width: 90%; top: 0; left: 0; z-index: 5; @@ -112,8 +112,8 @@ body, list-style-type: none; padding: 0; margin: 0; - display: flex; + gap: 70px; justify-content: center; flex-wrap: wrap; } @@ -175,3 +175,154 @@ body, text-align: center; font-size: 0.8em; } + +/* book detail */ +.book-detail { + display: flex; + flex-direction: column; + align-items: center; + max-width: 600px; + margin: 20px auto; + padding: 20px; + border: 1px solid #ccc; + border-radius: 5px; +} + +.book-detail img { + width: 200px; + height: 300px; + object-fit: cover; + margin-bottom: 20px; +} + +.book-detail h2 { + font-size: 24px; + margin-bottom: 10px; +} + +.book-detail p { + font-size: 16px; + margin-bottom: 10px; +} + +.book-detail button { + /* position: absolute; + top: 0; + left: 0; */ + padding: 5px 10px; + margin: 25px; + background-color: #cfcfb2; + border: 1px solid #ccc; + cursor: pointer; +} + + +/* Auth */ +.auth-container { + /* Add your styles here */ + /* For example: */ + width: 400px; + margin: 0 auto; + padding: 20px; + border: 1px solid #ccc; + border-radius: 5px; +} + +.auth-container h2 { + text-align: center; +} + +.auth-container .error { + color: red; + margin-bottom: 10px; +} + +.auth-container form { + display: flex; + flex-direction: column; +} + +.auth-container form div { + margin-bottom: 10px; +} + +.auth-container form label { + display: block; + margin-bottom: 5px; +} + +.auth-container form input { + padding: 5px; + border-radius: 3px; + border: 1px solid #ccc; +} + +.auth-container form button { + padding: 10px 20px; + background-color: #700b0b; + color: white; + border: none; + border-radius: 3px; + cursor: pointer; +} + +.auth-container a { + display: inline-block; + padding: 10px 20px; + background-color: #4CAF50; + color: white; + border: none; + border-radius: 3px; + text-decoration: none; + cursor: pointer; + transition: background-color 0.3s ease; +} + +.auth-container a:hover { + background-color: #3e8e41; +} + +/* header */ +.app-header { + background-color: #282c34; + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + color: white; + padding: 0.5rem; +} + +.user-info { + display: flex; + align-items: center; +} + +.user-info span { + margin-right: 1rem; +} + +.user-info button { + padding: 10px 20px; + background-color: #700b0b; + color: white; + border: none; + border-radius: 3px; + cursor: pointer; +} + +.book-info { + position: absolute; + left: 0; + bottom: 160px; + width: 34px; + height: 34px; + border-radius: 50%; + background: #2440bd; + background-image: url("./icons/information.svg"); + background-repeat: no-repeat; + background-position: center; + background-size: 20px; + box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23); + cursor: pointer; +} diff --git a/starter/src/App.js b/starter/src/App.js index 7fea1a00b8..735355827d 100644 --- a/starter/src/App.js +++ b/starter/src/App.js @@ -1,282 +1,38 @@ import "./App.css"; -import { useState } from "react"; +import { Routes, Route, useNavigate } from "react-router-dom"; +import Main from "./Main"; +import SearchBooks from "./SearchBooks"; +import BookDetail from "./BookDetail"; +import Login from "./Login"; +import { useEffect } from "react"; +import SignUp from "./SignUp"; +import Header from "./Header"; function App() { - const [showSearchPage, setShowSearchpage] = useState(false); + const navigate = useNavigate(); + const isLoggedIn = sessionStorage.getItem("isLoggedIn") === "true"; + + useEffect(() => { + if (!isLoggedIn) { + navigate("/login"); + } + }, [isLoggedIn]); // eslint-disable-line react-hooks/exhaustive-deps + + const handleLogOut = () => { + sessionStorage.removeItem("isLoggedIn"); + navigate("/login"); + }; return (
- {showSearchPage ? ( - - ) : ( -
-
-

MyReads

-
-
-
-
-

Currently Reading

-
-
    -
  1. -
    -
    -
    -
    - -
    -
    -
    To Kill a Mockingbird
    -
    Harper Lee
    -
    -
  2. -
  3. -
    -
    -
    -
    - -
    -
    -
    Ender's Game
    -
    Orson Scott Card
    -
    -
  4. -
-
-
-
-

Want to Read

-
-
    -
  1. -
    -
    -
    -
    - -
    -
    -
    1776
    -
    David McCullough
    -
    -
  2. -
  3. -
    -
    -
    -
    - -
    -
    -
    - Harry Potter and the Sorcerer's Stone -
    -
    J.K. Rowling
    -
    -
  4. -
-
-
-
-

Read

-
-
    -
  1. -
    -
    -
    -
    - -
    -
    -
    The Hobbit
    -
    J.R.R. Tolkien
    -
    -
  2. -
  3. -
    -
    -
    -
    - -
    -
    -
    - Oh, the Places You'll Go! -
    -
    Seuss
    -
    -
  4. -
  5. -
    -
    -
    -
    - -
    -
    -
    - The Adventures of Tom Sawyer -
    -
    Mark Twain
    -
    -
  6. -
-
-
-
-
- -
- )} +
+ + } /> : + } /> + } /> + } /> + } /> +
); } diff --git a/starter/src/Book.js b/starter/src/Book.js new file mode 100644 index 0000000000..2ebace181a --- /dev/null +++ b/starter/src/Book.js @@ -0,0 +1,41 @@ +import { useNavigate } from "react-router-dom"; + +const Book = ({ book, isSearch, onHandleOnchange }) => { + let navigate = useNavigate(); + const moveToBookDetail = (e, book) => { + e.stopPropagation(); + navigate(`/book/${book.id}`, { state: { book } }) + }; + + return (
+
+
+
moveToBookDetail(e, book)} /> +
+ +
+
+
{book.title}
+
{book.authors}
+
); +}; + +export default Book; \ No newline at end of file diff --git a/starter/src/BookDetail.js b/starter/src/BookDetail.js new file mode 100644 index 0000000000..4d0da6d145 --- /dev/null +++ b/starter/src/BookDetail.js @@ -0,0 +1,22 @@ +import { useLocation, useNavigate } from 'react-router-dom'; + +const BookDetail = () => { + + const navigate = useNavigate(); + const location = useLocation(); + const { book } = location.state || {}; + const goBack = () => { + navigate(-1); + }; + + return (
+ + Book Cover +

{book.title}

+

{book.authors.join(' , ')}

+

Published Date: {book.publishedDate}

+

Description: {book.description}

+
); +}; + +export default BookDetail; \ No newline at end of file diff --git a/starter/src/BookGrid.js b/starter/src/BookGrid.js new file mode 100644 index 0000000000..7e21c4baa3 --- /dev/null +++ b/starter/src/BookGrid.js @@ -0,0 +1,34 @@ +import * as BooksAPI from "./BooksAPI"; +import { Draggable } from 'react-beautiful-dnd'; +import Book from "./Book"; + +const BookGrid = ({ books, isSearch, countChanged, onShelfChanged }) => { + const handleOnchange = (book, value) => { + const currentUsername = sessionStorage.getItem('currentUsername'); + const token = localStorage.getItem(`token-${currentUsername}`); + BooksAPI.update(book, value, token).then(() => { + if (countChanged !== undefined) { + onShelfChanged(countChanged + 1); + } + }).catch((error) => { + console.error("Error updating book shelf:", error); + }); + }; + + return (
    + {books.map((book, index) => + !isSearch ? + + {(provided) => ( +
  1. + +
  2. + )} +
    + : + + )} +
); +}; + +export default BookGrid; \ No newline at end of file diff --git a/starter/src/BookShelf.js b/starter/src/BookShelf.js new file mode 100644 index 0000000000..1895bd4cb3 --- /dev/null +++ b/starter/src/BookShelf.js @@ -0,0 +1,11 @@ + +import BookGrid from "./BookGrid"; + +const BookShelf = ({ books, onShelfChanged, countChanged }) => { + + return (
+ +
) +}; + +export default BookShelf; \ No newline at end of file diff --git a/starter/src/BooksAPI.js b/starter/src/BooksAPI.js index bc4694a84f..5b4168797f 100644 --- a/starter/src/BooksAPI.js +++ b/starter/src/BooksAPI.js @@ -3,28 +3,36 @@ const api = "https://reactnd-books-api.udacity.com"; let token = localStorage.token; if (!token) token = localStorage.token = Math.random().toString(36).substr(-8); - const headers = { Accept: "application/json", Authorization: token, }; +const jsonType = "application/json"; + export const get = (bookId) => fetch(`${api}/books/${bookId}`, { headers }) .then((res) => res.json()) .then((data) => data.book); -export const getAll = () => - fetch(`${api}/books`, { headers }) - .then((res) => res.json()) - .then((data) => data.books); +export const getAll = (specificUserToken) => { + return fetch(`${api}/books`, { + headers: { + Accept: jsonType, + Authorization: specificUserToken, + }, + }) + .then((res) => res.json()) + .then((data) => data.books); +}; -export const update = (book, shelf) => +export const update = (book, shelf,specificUserToken) => fetch(`${api}/books/${book.id}`, { method: "PUT", headers: { - ...headers, - "Content-Type": "application/json", + Accept: jsonType, + Authorization: specificUserToken, + "Content-Type": jsonType, }, body: JSON.stringify({ shelf }), }).then((res) => res.json()); @@ -34,7 +42,7 @@ export const search = (query, maxResults) => method: "POST", headers: { ...headers, - "Content-Type": "application/json", + "Content-Type": jsonType, }, body: JSON.stringify({ query, maxResults }), }) diff --git a/starter/src/Header.js b/starter/src/Header.js new file mode 100644 index 0000000000..5bbd5f0662 --- /dev/null +++ b/starter/src/Header.js @@ -0,0 +1,19 @@ +import React from "react"; + +function Header({ isLoggedIn, handleLogOut }) { + const currentUsername = sessionStorage.getItem('currentUsername'); + + return ( +
+

My Book App

+ {isLoggedIn && ( +
+ {currentUsername} + +
+ )} +
+ ); +} + +export default Header; \ No newline at end of file diff --git a/starter/src/Login.js b/starter/src/Login.js new file mode 100644 index 0000000000..d078d0ba74 --- /dev/null +++ b/starter/src/Login.js @@ -0,0 +1,64 @@ +import React, { useState } from "react"; +import { useNavigate, Link } from "react-router-dom"; + +function Login() { + const navigate = useNavigate(); + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(""); + + const handleSubmit = (e) => { + e.preventDefault(); + const userStorageValue = localStorage.getItem(username); + if (!username || !password) { + setError("Please enter username and password"); + }else if (!userStorageValue){ + setError("username not exist"); + } + else if (userStorageValue !== password) { + setError("password was incorrect"); + } else { + setError(""); + sessionStorage.setItem("isLoggedIn", "true"); + sessionStorage.setItem("currentUsername", username); + if(!localStorage.getItem(`token-${username}`)){ + localStorage.setItem(`token-${username}`, Math.random().toString(36).substr(-8)); + } + + navigate("/"); + } + }; + + return ( +
+

Login

+ {error &&
{error}
} +
+
+ + setUsername(e.target.value)} + /> +
+
+ + setPassword(e.target.value)} + /> +
+
+ +
+
+ Create a new account +
+ ); +} + +export default Login; \ No newline at end of file diff --git a/starter/src/Main.js b/starter/src/Main.js new file mode 100644 index 0000000000..bbbd85408f --- /dev/null +++ b/starter/src/Main.js @@ -0,0 +1,127 @@ +import BookShelf from "./BookShelf"; +import { Link } from "react-router-dom"; +import { useState, useEffect } from "react"; +import * as BooksAPI from "./BooksAPI"; +import { DragDropContext, Droppable } from 'react-beautiful-dnd'; + +const Main = () => { + const [books, setBooks] = useState([]); + + const [countBookShelfChanged, setCountBookShelfChanged] = useState(0); + + const currentUsername = sessionStorage.getItem('currentUsername'); + const token = localStorage.getItem(`token-${currentUsername}`); + useEffect(() => { + const getBooks = async () => { + const books = await BooksAPI.getAll(token); + setBooks(books); + }; + getBooks(); + }, [countBookShelfChanged]); // eslint-disable-line react-hooks/exhaustive-deps + + const changeCountBookShelf = (value) => { + setCountBookShelfChanged(value); + }; + + const handleOnDragEnd = (result) => { + const { source, destination } = result; + + if (!destination) return; + + if (source.droppableId === destination.droppableId && source.index === destination.index) { + return; + } + + const items = Array.from(books); + + const indexReorderedItem = items.findIndex(e => e.id === result.draggableId); + + const [reorderedItem] = items.splice(indexReorderedItem, 1); + reorderedItem.shelf = destination.droppableId; + + + const indexMain = getIndexMain(items, destination.droppableId, destination.index); + + items.splice(indexMain, 0, reorderedItem); + setBooks(items); + + BooksAPI.update(reorderedItem, reorderedItem.shelf, token); + }; + + const getIndexMain = (items, destinationDroppableId, destinationIndex) => { + let indexMain; + switch (destinationDroppableId) { + case 'currentlyReading': + indexMain = getIndexForShelf(items, destinationDroppableId, destinationIndex); + break; + case 'wantToRead': + indexMain = getIndexForShelf(items, destinationDroppableId, destinationIndex); + break; + case 'read': + indexMain = getIndexForShelf(items, destinationDroppableId, destinationIndex); + break; + default: + break; + } + return indexMain; + }; + + const getIndexForShelf = (items, shelf, destinationIndex) => { + const index = items.findIndex(e => e.shelf === shelf) + destinationIndex; + return index; + }; + + const currentlyReadingBooks = books.filter(book => book.shelf === 'currentlyReading'); + const wantToReadBooks = books.filter(book => book.shelf === 'wantToRead'); + const readBooks = books.filter(book => book.shelf === 'read'); + + return (
+
+

MyReads

+
+
+ + + {(provided) => ( +
+
+

Currently Reading

+ +
+ {provided.placeholder} +
+ )} +
+ + + {(provided) => ( +
+
+

Want to Read

+ +
+ {provided.placeholder} +
+ )} +
+ + + {(provided) => ( +
+
+

Read

+ +
+ {provided.placeholder} +
+ )} +
+
+
+
+ Add a book +
+
); +}; + +export default Main; \ No newline at end of file diff --git a/starter/src/SearchBooks.js b/starter/src/SearchBooks.js new file mode 100644 index 0000000000..161c388467 --- /dev/null +++ b/starter/src/SearchBooks.js @@ -0,0 +1,72 @@ +import { Link, useLocation } from "react-router-dom"; +import { useState, useEffect } from "react"; +import BookGrid from "./BookGrid"; +import * as BooksAPI from "./BooksAPI"; + +const SearchBooks = () => { + const location = useLocation(); + const booksOfMain = location.state || []; + const [input, setInput] = useState(sessionStorage.getItem('searchInput') || ''); + const [books, setBooks] = useState([]); + + useEffect(() => { + sessionStorage.setItem('searchInput', input); + if (input) { + const inputTrimmed = input.trim(); + BooksAPI.search(inputTrimmed).then(res => { + if (res.error) { + setBooks([]); + } else { + const filteredBooks = checkDuplicatedBook(res); + setBooks(filteredBooks); + } + }).catch((error) => { + console.error("Error searching book :", error); + }); + } else { + setBooks([]); + } + }, [input]); // eslint-disable-line react-hooks/exhaustive-deps + + const handleInputChange = (e) => { + setInput(e.target.value); + }; + + const checkDuplicatedBook = (books) => { + + const filteredBooks = books.map((book) => { + const duplicatedBook = booksOfMain.find((b) => b.id === book.id); + if (duplicatedBook) { + book.shelf = duplicatedBook.shelf; + } + return book; + }); + + return filteredBooks; + }; + + return (
+
+ + Close + +
+ +
+
+
+ {books.length !== 0 && } +
+
); +}; + +export default SearchBooks; \ No newline at end of file diff --git a/starter/src/SignUp.js b/starter/src/SignUp.js new file mode 100644 index 0000000000..7a9dedfc15 --- /dev/null +++ b/starter/src/SignUp.js @@ -0,0 +1,69 @@ +import React, { useState } from "react"; +import { useNavigate } from "react-router-dom"; + +function SignUp() { + const navigate = useNavigate(); + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [error, setError] = useState(""); + + const handleSubmit = (e) => { + e.preventDefault(); + if (!username || !password || !confirmPassword) { + setError("Please don't let any empty fields"); + } else if (password !== confirmPassword) { + setError("Passwords don't match with confirmPassword"); + } else { + const existingUsernames = Object.keys(localStorage); + if (existingUsernames.includes(username)) { + setError("Username already exists"); + } else { + localStorage.setItem(username, password); + setError(""); + navigate("/login"); + } + } + }; + + return ( +
+

Sign Up

+ {error &&
{error}
} +
+
+ + setUsername(e.target.value)} + /> +
+
+ + setPassword(e.target.value)} + /> +
+
+ + setConfirmPassword(e.target.value)} + /> +
+
+ +
+
+
+ ); +} + +export default SignUp; \ No newline at end of file diff --git a/starter/src/icons/information.svg b/starter/src/icons/information.svg new file mode 100644 index 0000000000..ab53acaf60 --- /dev/null +++ b/starter/src/icons/information.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/starter/src/index.js b/starter/src/index.js index 846ed2ced3..d8e4f8dae8 100644 --- a/starter/src/index.js +++ b/starter/src/index.js @@ -2,10 +2,11 @@ import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; +import { BrowserRouter } from "react-router-dom"; ReactDOM.render( - + - , + , document.getElementById("root") );