From ba82c13fe12ce35ce0a421d7fd6dfa0acebd57e2 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Sun, 17 Apr 2022 22:31:41 -0500 Subject: [PATCH] Color and I18n support --- frontend/package-lock.json | 13 ++ frontend/package.json | 1 + frontend/src/App.css | 86 +-------- frontend/src/App.jsx | 9 +- frontend/src/Routes.jsx | 3 +- frontend/src/global/components/Footer.jsx | 8 +- .../FormControl/InlineLabelInput.jsx | 40 ++++ .../components/FormControl/StandardInput.jsx | 36 ++++ .../src/global/components/Modal/Alert.jsx | 3 +- frontend/src/global/components/Nav/Navbar.jsx | 113 ++++++++++-- .../src/global/components/Nav/NavbarItem.jsx | 16 -- frontend/src/global/i18n.js | 87 +++++++++ frontend/src/pages/Home/components/Card.jsx | 52 ++++++ frontend/src/pages/Home/index.jsx | 57 ++++-- .../pages/Manage/components/FileUpload.jsx | 4 +- frontend/src/pages/Manage/index.jsx | 172 +++++++++++------- frontend/src/pages/User/Login.jsx | 95 ++++++---- frontend/src/pages/User/Register.jsx | 138 +++++++------- frontend/src/redux/decode.js | 4 +- 19 files changed, 632 insertions(+), 305 deletions(-) create mode 100644 frontend/src/global/components/FormControl/InlineLabelInput.jsx create mode 100644 frontend/src/global/components/FormControl/StandardInput.jsx delete mode 100644 frontend/src/global/components/Nav/NavbarItem.jsx create mode 100644 frontend/src/global/i18n.js create mode 100644 frontend/src/pages/Home/components/Card.jsx diff --git a/frontend/package-lock.json b/frontend/package-lock.json index c572f70..a0720e5 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -8510,6 +8510,11 @@ "json5": "^2.1.2" } }, + "localized-strings": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/localized-strings/-/localized-strings-0.2.4.tgz", + "integrity": "sha512-TKDhqFPkIIN/if2FSvVVZTaM/GP9TzfgdQ2uY65mr32xgFu5nqkKXprXbzy5rfx32DF5LDvS/y1UqYF/mAscYA==" + }, "locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -10266,6 +10271,14 @@ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" }, + "react-localization": { + "version": "1.0.19", + "resolved": "https://registry.npmjs.org/react-localization/-/react-localization-1.0.19.tgz", + "integrity": "sha512-f4E6T8xRis19K8qMOnnhjGV2quy1YH2lrSsnAiytvgt7uOSp6WgDhrZH6XZEaEFqupTOCFSf8uagIoIAkjl4JA==", + "requires": { + "localized-strings": "^0.2.0" + } + }, "react-phone-input-2": { "version": "2.15.0", "resolved": "https://registry.npmjs.org/react-phone-input-2/-/react-phone-input-2-2.15.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index c12e555..671936c 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -12,6 +12,7 @@ "react-currency-input-field": "^3.6.4", "react-dom": "^18.0.0", "react-icons": "^4.3.1", + "react-localization": "^1.0.19", "react-phone-input-2": "^2.15.0", "react-redux": "^7.2.8", "react-router-dom": "^6.3.0", diff --git a/frontend/src/App.css b/frontend/src/App.css index 8001667..4578b16 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -22,88 +22,13 @@ color: var(--chakra-colors-purple-500) !important; } -.nav-inactive { - display: -webkit-inline-box; - display: -webkit-inline-flex; - display: -ms-inline-flexbox; - display: inline-flex; - -webkit-appearance: none; - -moz-appearance: none; - -ms-appearance: none; - appearance: none; - -webkit-align-items: center; - -webkit-box-align: center; - -ms-flex-align: center; - align-items: center; - -webkit-box-pack: center; - -ms-flex-pack: center; - -webkit-justify-content: center; - justify-content: center; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - position: relative; - white-space: nowrap; - vertical-align: middle; - outline: 2px solid transparent; - outline-offset: 2px; - width: auto; - line-height: 1.2; - border-radius: var(--chakra-radii-md); - font-weight: var(--chakra-fontWeights-semibold); - transition-property: var(--chakra-transition-property-common); - transition-duration: var(--chakra-transition-duration-normal); - height: var(--chakra-sizes-10); - min-width: var(--chakra-sizes-10); - font-size: var(--chakra-fontSizes-md); - -webkit-padding-start: var(--chakra-space-4); - padding-inline-start: var(--chakra-space-4); - -webkit-padding-end: var(--chakra-space-4); - padding-inline-end: var(--chakra-space-4); - background: var(--chakra-colors-gray-100); +body.chakra-ui-light .chakra-input.currency { + background: var(--chakra-colors-gray-50); + color: var(--chakra-colors-black); } -.nav-active { - display: -webkit-inline-box; - display: -webkit-inline-flex; - display: -ms-inline-flexbox; - display: inline-flex; - -webkit-appearance: none; - -moz-appearance: none; - -ms-appearance: none; - appearance: none; - -webkit-align-items: center; - -webkit-box-align: center; - -ms-flex-align: center; - align-items: center; - -webkit-box-pack: center; - -ms-flex-pack: center; - -webkit-justify-content: center; - justify-content: center; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - position: relative; - white-space: nowrap; - vertical-align: middle; - outline: 2px solid transparent; - outline-offset: 2px; - width: auto; - line-height: 1.2; - border-radius: var(--chakra-radii-md); - font-weight: var(--chakra-fontWeights-semibold); - transition-property: var(--chakra-transition-property-common); - transition-duration: var(--chakra-transition-duration-normal); - height: var(--chakra-sizes-10); - min-width: var(--chakra-sizes-10); - font-size: var(--chakra-fontSizes-md); - -webkit-padding-start: var(--chakra-space-4); - padding-inline-start: var(--chakra-space-4); - -webkit-padding-end: var(--chakra-space-4); - padding-inline-end: var(--chakra-space-4); - background: var(--chakra-colors-blue-500); +body.chakra-ui-dark .chakra-input.currency { + background: var(--chakra-colors-gray-700); color: var(--chakra-colors-white); } @@ -132,7 +57,6 @@ border-bottom-color: currentcolor; border-left-color: currentcolor; border-color: inherit; - background: var(--chakra-colors-gray-50); border-top-left-radius: 0; border-bottom-left-radius: 0; } diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 33f7b58..4ff0319 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,9 +1,16 @@ import React from 'react'; -import { ChakraProvider, theme } from '@chakra-ui/react'; +import { ChakraProvider, extendTheme } from '@chakra-ui/react'; import { Provider } from 'react-redux'; import Routes from './Routes'; import store from './redux/store'; +const theme = extendTheme({ + config: { + initialColorMode: window.localStorage.getItem('color-mode') || 'light', + useSystemColorMode: false, + }, +}); + export default () => ( diff --git a/frontend/src/Routes.jsx b/frontend/src/Routes.jsx index 10c83b7..a956969 100644 --- a/frontend/src/Routes.jsx +++ b/frontend/src/Routes.jsx @@ -1,4 +1,5 @@ import React from 'react'; +import { MdAdminPanelSettings } from 'react-icons/md'; import { FaShoppingBag } from 'react-icons/fa'; import { BrowserRouter, Routes as RouterRoutes, Route } from 'react-router-dom'; import { connect } from 'react-redux'; @@ -23,7 +24,7 @@ export const Pages = [ { name: 'Manage', path: '/manage', - icon: null, + icon: (), element: (), adminOnly: true, hidden: false, diff --git a/frontend/src/global/components/Footer.jsx b/frontend/src/global/components/Footer.jsx index 2e69c16..263e8fe 100644 --- a/frontend/src/global/components/Footer.jsx +++ b/frontend/src/global/components/Footer.jsx @@ -1,16 +1,14 @@ import React from 'react'; import { Box, Flex, Text } from '@chakra-ui/react'; +import { General as i18n } from '../i18n'; export default () => ( - Made with 💙 by - {' '} + {`${i18n.footer.part1} `} oitsjustjose - {' '} - using - {' '} + {` ${i18n.footer.part2} `} Chakra-UI diff --git a/frontend/src/global/components/FormControl/InlineLabelInput.jsx b/frontend/src/global/components/FormControl/InlineLabelInput.jsx new file mode 100644 index 0000000..e1e19da --- /dev/null +++ b/frontend/src/global/components/FormControl/InlineLabelInput.jsx @@ -0,0 +1,40 @@ +import React from 'react'; +import { + FormControl, Input, InputGroup, InputLeftAddon, Text, useColorModeValue, +} from '@chakra-ui/react'; +import IconTextDuo from '../IconTextDuo'; + +export default ({ + type, value, propKeyPressEvt, propSubmitEvt, + propChangeEvt, required, error, labelText, labelIcon, + labelBgColor, labelFgColor, +}) => { + const id = Math.random().toString(36); + return ( + + + + + + + + + {error} + + ); +}; diff --git a/frontend/src/global/components/FormControl/StandardInput.jsx b/frontend/src/global/components/FormControl/StandardInput.jsx new file mode 100644 index 0000000..d6e2df2 --- /dev/null +++ b/frontend/src/global/components/FormControl/StandardInput.jsx @@ -0,0 +1,36 @@ +import React from 'react'; +import { + FormControl, Input, Text, useColorModeValue, +} from '@chakra-ui/react'; +import IconTextDuo from '../IconTextDuo'; + +export default ({ + type, value, propKeyPressEvt, propSubmitEvt, + propChangeEvt, required, error, labelText, labelIcon, +}) => { + const id = Math.random().toString(36); + return ( + + + + + {error} + + ); +}; diff --git a/frontend/src/global/components/Modal/Alert.jsx b/frontend/src/global/components/Modal/Alert.jsx index ef412a3..8917c29 100644 --- a/frontend/src/global/components/Modal/Alert.jsx +++ b/frontend/src/global/components/Modal/Alert.jsx @@ -5,6 +5,7 @@ import { } from '@chakra-ui/react'; import { connect } from 'react-redux'; import store from '../../../redux/store'; +import { General as i18n } from '../../i18n'; const AlertModal = ({ open, header, content, @@ -20,7 +21,7 @@ const AlertModal = ({ diff --git a/frontend/src/global/components/Nav/Navbar.jsx b/frontend/src/global/components/Nav/Navbar.jsx index da9b3e8..02f1f82 100644 --- a/frontend/src/global/components/Nav/Navbar.jsx +++ b/frontend/src/global/components/Nav/Navbar.jsx @@ -1,32 +1,50 @@ import React from 'react'; import { - Avatar, Box, + Avatar, + Box, + Button, Flex, HStack, - IconButton, Stack, useColorModeValue, useDisclosure, + IconButton, + Stack, + useColorModeValue, + useDisclosure, + useColorMode, } from '@chakra-ui/react'; -import { AiOutlineClose } from 'react-icons/ai'; -import { FaHamburger } from 'react-icons/fa'; -import { connect } from 'react-redux'; +import { AiOutlineClose, AiOutlineMenu } from 'react-icons/ai'; import { MdLogin, MdLogout } from 'react-icons/md'; -import Item from './NavbarItem'; +import { BsSunFill, BsMoonFill } from 'react-icons/bs'; +import { connect } from 'react-redux'; +import { useNavigate, useLocation } from 'react-router-dom'; import { Pages } from '../../../Routes'; +import IconTextDuo from '../IconTextDuo'; +import { General as i18n } from '../../i18n'; const NavBar = ({ user }) => { const { isOpen, onOpen, onClose } = useDisclosure(); + const { colorMode, setColorMode } = useColorMode(); + + const navigate = useNavigate(); + const location = useLocation(); return ( - + + {/* Mobile Menu Toggle Icon */} : } - aria-label="Open Menu" + icon={isOpen ? : } + aria-label={i18n.openMenu} display={{ md: 'none' }} onClick={isOpen ? onClose : onOpen} + colorScheme="gray" + textAlign="center" /> + - + + + { .filter((x) => !x.hidden) .filter((x) => !x.adminOnly || (x.adminOnly && user?.admin)) .map(({ icon, name, path }) => ( - + )) } - {!user && ()} name="Log In" to="/login" />)} - {user && ()} name="Log Out" to="/logout" />) } + + {!user && ( + + )} + + {user && ( + + )} + + : } + aria-label={i18n.changeColorMode} + onClick={() => { + const newMode = colorMode === 'light' ? 'dark' : 'light'; + setColorMode(newMode); + window.localStorage.setItem('color-mode', newMode); + }} + colorScheme="gray" + textAlign="center" + /> @@ -55,11 +108,34 @@ const NavBar = ({ user }) => { .filter((x) => !x.hidden) .filter((x) => !x.adminOnly || (x.adminOnly && user?.admin)) .map(({ icon, name, path }) => ( - + )) } - {!user && ()} name="Log In" to="/login" />)} - {user && ()} name="Log Out" to="/logout" />) } + + {!user && ( + + )} + + {user && ( + + )} ) : null} @@ -67,8 +143,5 @@ const NavBar = ({ user }) => { ); }; -const mapStateToProps = ({ user }) => ({ - user, -}); - +const mapStateToProps = ({ user }) => ({ user }); export default connect(mapStateToProps)(NavBar); diff --git a/frontend/src/global/components/Nav/NavbarItem.jsx b/frontend/src/global/components/Nav/NavbarItem.jsx deleted file mode 100644 index b07ee27..0000000 --- a/frontend/src/global/components/Nav/NavbarItem.jsx +++ /dev/null @@ -1,16 +0,0 @@ -import React from 'react'; -import { NavLink } from 'react-router-dom'; - -export default ({ - to, name, icon, -}) => ( - `chakra-button ${isActive ? 'nav-active' : 'nav-inactive'}`} - > - {icon && icon} - {!!icon && !!name && (
)} - {!!name && name} - - -); diff --git a/frontend/src/global/i18n.js b/frontend/src/global/i18n.js new file mode 100644 index 0000000..2f6cc81 --- /dev/null +++ b/frontend/src/global/i18n.js @@ -0,0 +1,87 @@ +import LocalizedStrings from 'react-localization'; + +export const General = new LocalizedStrings({ + en: { + close: 'Close', + save: 'Save', + openMenu: 'Open Menu', + login: 'Log In', + logout: 'Log Out', + changeColorMode: 'Toggle Light/Dark Theme', + footer: { + part1: 'Made with 💙 by', + part2: 'using', + }, + }, +}); + +export const Home = new LocalizedStrings({ + en: { + downloadFailedAlert: { + header: 'Failed to Download Products', + }, + }, +}); + +export const Manage = new LocalizedStrings({ + en: { + create: { + title: 'Create Product', + fileUpload: (count) => `${count || 'No'} ${count === 1 ? 'File' : 'Files'} Selected`, + itemCreatedSuccess: (id) => ({ + header: 'Item Added!', + content: `Item created with ID ${id}`, + }), + labels: { + name: 'Name', + price: 'Price', + qty: 'Quantity', + required: 'This Field is Required', + save: 'Save Product', + }, + }, + }, +}); + +export const Login = new LocalizedStrings({ + en: { + logoutAlert: { + header: 'You Have Been Logged Out', + content: 'You\'ve been logged out automatically as it has been more than 1 day since you last logged in. Please log in again.', + }, + labels: { + register: 'Need an account? Click here!', + email: 'Email Address', + password: 'Password', + required: 'This Field is Required', + }, + buttons: { + submit: 'Log In', + }, + }, +}); + +export const Register = new LocalizedStrings({ + en: { + createAccountSuccess: { + header: 'Account Created!', + content: 'You\'ll receive an account confirmation email shortly! Sit tight until you have verified your account.', + }, + createAccountFailure: ({ error }) => ({ + header: 'Unable to Create Account', + content: error, + }), + labels: { + login: 'Already have an account? Sign in here!', + first: 'First Name', + last: 'Last Name', + email: 'Email Address', + password: 'Password', + conf: 'Verify Password', + match: 'Passwords must match', + required: 'This Field is Required', + privacy: 'None of this information will be shared', + register: 'Register', + }, + }, +}); diff --git a/frontend/src/pages/Home/components/Card.jsx b/frontend/src/pages/Home/components/Card.jsx new file mode 100644 index 0000000..fe3ea9e --- /dev/null +++ b/frontend/src/pages/Home/components/Card.jsx @@ -0,0 +1,52 @@ +import React from 'react'; +import { + Box, + useColorModeValue, + Heading, + Text, + Stack, + Image, +} from '@chakra-ui/react'; + +export default ({ product }) => { + const images = product.images.filter((x) => !!x) || ['https://dv2ls.com/f/PpMcVb8gN']; + return ( + + + + + + + {product.name} + + + {product.quantity === 0 ? 'Sold Out' : `$${product.price}`} + + + + ); +}; diff --git a/frontend/src/pages/Home/index.jsx b/frontend/src/pages/Home/index.jsx index d63f576..66e50a2 100644 --- a/frontend/src/pages/Home/index.jsx +++ b/frontend/src/pages/Home/index.jsx @@ -1,22 +1,47 @@ -/* eslint-disable max-len */ -import React from 'react'; -import { Heading, Text } from '@chakra-ui/react'; +/* eslint-disable no-underscore-dangle */ +import React, { useState, useEffect } from 'react'; +import { Heading, Grid, GridItem } from '@chakra-ui/react'; import { connect } from 'react-redux'; +import store from '../../redux/store'; +import Card from './components/Card'; +import { Home as i18n } from '../../global/i18n'; -const Home = ({ user }) => ( -
- - Hello - {' '} - {user?.first} - ! - +const Home = ({ user }) => { + const [products, setProducts] = useState([]); - - Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum itaque hic pariatur ad voluptates possimus amet nostrum officia, nesciunt voluptatem. Eligendi reprehenderit explicabo, illo dolores, nemo minus facere voluptatibus eius fugit odit similique eum ullam. Assumenda reprehenderit hic nesciunt amet soluta? Aliquid accusamus architecto itaque ex, quibusdam suscipit libero voluptate eos pariatur, laudantium nulla inventore placeat. Sunt ex ut repudiandae architecto aspernatur quas, explicabo ipsa? Eligendi provident aperiam rem officiis quam dignissimos neque culpa a beatae iusto recusandae quaerat facilis, quidem, veritatis iste consectetur, est pariatur maxime repudiandae ipsa fugiat reiciendis rerum repellat voluptatum. Nihil laborum quisquam, omnis maiores, excepturi asperiores repellat repudiandae error voluptatem corporis tenetur! Non totam asperiores nam commodi suscipit. At animi unde aperiam deleniti ratione provident, fugit quam sunt error quis ad vitae reprehenderit! Mollitia soluta excepturi aspernatur iste reprehenderit, unde quidem necessitatibus animi. Veritatis, voluptatibus ullam autem, perspiciatis sequi debitis sunt, reiciendis placeat quasi perferendis quia exercitationem corporis. Minima consequatur a recusandae veniam explicabo, nihil praesentium doloribus, sapiente nulla totam aliquid corrupti quod. Obcaecati facilis vitae quia soluta consequuntur atque sed veniam ducimus exercitationem illo, numquam officia. Numquam, quae! Pariatur error alias ipsum ad, est harum animi nesciunt. Voluptatibus, cum illum modi rerum mollitia, consequuntur repudiandae voluptatum repellendus, dolorum eum harum neque exercitationem velit repellat. Repudiandae hic similique deleniti et. Nihil qui architecto quasi assumenda explicabo quas eius, odit aspernatur repellendus a veniam? Nesciunt, minima amet illum eligendi voluptate et maiores magnam, possimus corrupti, est voluptatem odit architecto culpa. Culpa sed omnis nobis in deleniti, corrupti minima repellendus non repudiandae qui dolorum numquam? A eos cumque doloremque, consequuntur maiores numquam adipisci obcaecati minima labore odio consectetur, magni ea in veritatis magnam, iusto quidem maxime! Accusantium possimus quia nisi corrupti amet! Neque autem quaerat harum eveniet libero et nemo illo porro quis itaque corporis fugiat facilis, nesciunt possimus tempore. Porro odit, voluptatum sapiente eveniet deleniti ex illum a! Ipsam earum, incidunt expedita provident nulla distinctio quaerat aliquam culpa repellendus vitae ipsum quae pariatur tempore placeat saepe sint quisquam inventore quasi ratione eum error esse maiores? Eveniet reprehenderit cupiditate veniam, dolorum dignissimos earum molestiae, asperiores fugiat magnam fugit accusamus, eum neque architecto error deserunt ipsum excepturi. Vel debitis laborum, fuga mollitia nesciunt necessitatibus architecto commodi quas exercitationem, alias odit consectetur eaque quaerat at dicta. Numquam quae sunt aliquid, dicta maiores doloremque, quos inventore esse facere excepturi porro, dolorem at eveniet assumenda eos minus iure voluptate ab incidunt odio illo tenetur asperiores deserunt. Eum eligendi dolorem ex labore earum molestias aspernatur, nostrum veniam tempora odio at nesciunt officia provident sit excepturi, deleniti pariatur ipsam harum quia? Soluta quam quas sit accusantium commodi! Dolor aperiam voluptatibus quos aspernatur a. Magni, quas dolor. Maxime molestias adipisci iste cumque quibusdam. Accusantium optio voluptate maxime facilis aspernatur odio blanditiis maiores, eius ad architecto reprehenderit quos iure facere, commodi quisquam labore, ullam itaque excepturi dolores ipsa eveniet incidunt deleniti ratione ut. Eveniet magnam provident, cupiditate, nisi ab porro temporibus mollitia, architecto dicta qui totam! Repellat, aliquid commodi. Unde vel esse accusamus velit omnis possimus, ducimus perspiciatis nobis necessitatibus corporis doloremque rem. Iste necessitatibus asperiores, rem excepturi illum ad repellat eveniet autem animi reiciendis veniam facere consectetur vel quis debitis, dolorem, placeat eius non! Quia doloremque nam a pariatur? - -
-); + useEffect(() => { + (async () => { + const resp = await fetch('/api/v1/products'); + const data = await resp.json(); + if (resp.ok) { + setProducts(data); + } else { + store.dispatch({ type: 'SET_ALERT', data: { header: i18n.downloadFailedAlert.header, content: JSON.stringify(data.error) } }); + } + })(); + + return () => {}; + }, [products, setProducts]); + + return ( +
+ + Hello + {' '} + {user?.first} + ! + + + + {products.map((x) => ( + + + + ))} + +
+ ); +}; const mapStateToProps = ({ user }) => ({ user }); export default connect(mapStateToProps)(Home); diff --git a/frontend/src/pages/Manage/components/FileUpload.jsx b/frontend/src/pages/Manage/components/FileUpload.jsx index b7f2b03..a880d3e 100644 --- a/frontend/src/pages/Manage/components/FileUpload.jsx +++ b/frontend/src/pages/Manage/components/FileUpload.jsx @@ -4,6 +4,7 @@ import { Input, InputGroup, InputLeftElement, Icon, } from '@chakra-ui/react'; import { FiFile } from 'react-icons/fi'; +import { Manage as i18n } from '../../../global/i18n'; export const FileUpload = ({ name, @@ -39,7 +40,8 @@ export const FileUpload = ({ placeholder={placeholder || 'Your file ...'} onClick={() => inputRef.current.click()} readOnly - value={`${files.length || 'No'} ${files.length === 1 ? 'File' : 'Files'} Selected`} + background="blue.300" + value={i18n.create.fileUpload(files.length)} /> ); diff --git a/frontend/src/pages/Manage/index.jsx b/frontend/src/pages/Manage/index.jsx index 7c8dd16..ddadf45 100644 --- a/frontend/src/pages/Manage/index.jsx +++ b/frontend/src/pages/Manage/index.jsx @@ -1,13 +1,13 @@ import React, { useEffect, useState } from 'react'; import { - Button, - FormControl, Heading, Input, InputGroup, InputLeftAddon, + Box, Button, FormControl, Heading, InputGroup, InputLeftAddon, Text, } from '@chakra-ui/react'; import CurrencyInput from 'react-currency-input-field'; -import { AiOutlineNumber } from 'react-icons/ai'; +import { AiOutlineFileText, AiOutlineNumber } from 'react-icons/ai'; import { BsCurrencyDollar } from 'react-icons/bs'; -import { MdTextFields } from 'react-icons/md'; +import InlineLabelInput from '../../global/components/FormControl/InlineLabelInput'; import IconTextDuo from '../../global/components/IconTextDuo'; +import { Manage as i18n } from '../../global/i18n'; import store from '../../redux/store'; import { FileUpload } from './components/FileUpload'; @@ -23,7 +23,7 @@ const uploadImage = async (file) => { const { output, error } = await resp.json(); if (error) { // eslint-disable-next-line no-console - error(error); + console.error(error); return null; } return `/api/v1/fileupload/${output}`; @@ -33,13 +33,18 @@ export default () => { const [loading, setLoading] = useState(false); const [state, setState] = useState({ name: '', - quantity: 0, - price: 0.0, + quantity: null, + price: null, images: [], }); const save = async () => { setLoading(true); + if (!state.name.length || !state.quantity || !state.price) { + store.dispatch({ type: 'SET_ALERT', data: { header: 'Missing Info', content: 'Not all required fields have been filled. Please provide this info to proceed.' } }); + setLoading(false); + return; + } try { // Step 1: Upload image files const imageUrls = await Promise.all(state.images.map(uploadImage)); @@ -74,7 +79,7 @@ export default () => { useEffect(() => { const params = new URLSearchParams(window.location.search); if (params.has('_id')) { - store.dispatch({ type: 'SET_ALERT', data: { header: 'Item Added!', content: `Item created with ID ${params.get('_id')}` } }); + store.dispatch({ type: 'SET_ALERT', data: { ...i18n.create.itemCreatedSuccess(params.get('_id')) } }); window.history.replaceState(null, null, window.location.pathname); } return () => {}; @@ -82,78 +87,113 @@ export default () => { return (
- Create Product + + {i18n.create.title} + - e.key === 'Enter' && save()} - onSubmit={save} - backgroundColor="gray.100" + - - )} text="Name" /> - setState({ ...state, name: e.target.value })} - /> - + setState({ ...state, name: e.target.value })} + propKeyPressEvt={(e) => e.key === 'Enter' && save()} + value={state.name} + labelText={i18n.create.labels.name} + labelIcon={()} + labelBgColor="#fa6663" + labelFgColor="black" + error={!state.name.length ? i18n.create.labels.required : null} + /> - - )} text="Qty" /> - {/* Use currency input to nicely handle whole numerical values */} - setState({ - ...state, quantity: JSON.parse(value), - })} - /> - + e.key === 'Enter' && save()} + isRequired + padding=".5rem" + borderRadius="8px" + margin="auto" + > + + + )} text="Qty" /> + + {/* Use currency input to nicely handle whole numerical values */} + setState({ + ...state, quantity: JSON.parse(value), + })} + /> + + {!state.quantity ? i18n.create.labels.required : null} + - - )} text="Price" /> - setState({ - ...state, price: JSON.parse(value), - })} - /> - - - - setState({ ...state, images: Array.from(evt.target.files) })} - style={{ cursor: 'pointer !important' }} - /> - + e.key === 'Enter' && save()} + isRequired + padding=".5rem" + borderRadius="8px" + margin="auto" + > + + )} text="Price" /> + setState({ + ...state, price: JSON.parse(value), + })} + /> + + {!state.price ? i18n.create.labels.required : null} + + e.key === 'Enter' && save()} + isRequired + padding=".5rem" + borderRadius="8px" + margin="auto" + > + + setState({ + ...state, + images: Array.from(evt.target.files), + })} + /> + + {state.images.length === 0 ? i18n.create.labels.required : null} + - +
); }; diff --git a/frontend/src/pages/User/Login.jsx b/frontend/src/pages/User/Login.jsx index 1895d17..64abde5 100644 --- a/frontend/src/pages/User/Login.jsx +++ b/frontend/src/pages/User/Login.jsx @@ -1,11 +1,13 @@ -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { - Button, FormControl, FormLabel, Input, Heading, Text, + Button, Heading, Text, Box, } from '@chakra-ui/react'; import { MdAlternateEmail, MdPassword, MdLogin } from 'react-icons/md'; import { useNavigate } from 'react-router-dom'; -import IconTextDuo from '../../global/components/IconTextDuo'; import store from '../../redux/store'; +import StandardInput from '../../global/components/FormControl/StandardInput'; +import IconTextDuo from '../../global/components/IconTextDuo'; +import { Login as i18n } from '../../global/i18n'; export default () => { const [state, setState] = useState({ email: '', password: '' }); @@ -13,6 +15,7 @@ export default () => { const navigate = useNavigate(); const login = async () => { + if (state.email.length === 0 || state.password.length === 0) return; setLoading(true); const resp = await fetch('/api/v1/user/auth/login', { @@ -38,58 +41,86 @@ export default () => { setLoading(false); }; + useEffect(() => { + const params = new URLSearchParams(window.location.search); + if (params.has('invalidOrExpired')) { + store.dispatch({ + type: 'SET_ALERT', + data: { + header: i18n.logoutAlert.header, + content: i18n.logoutAlert.content, + }, + }); + + // Remove the query to prevent it being annoying + params.delete('invalidOrExpired'); + navigate({ + pathname: window.location.pathname, + search: params.toString(), + }, { replace: true }); + } + return () => {}; + }, []); + return (
User Login - - Need an account? Click - {' '} - here! + navigate('/register', { replace: true })} + _hover={{ fontWeight: 600, color: 'var(--chakra-colors-purple-500) !important' }} + > + {i18n.labels.register} - e.key === 'Enter' && login()} - onSubmit={login} - backgroundColor="gray.100" + - - )} text="Email" /> - - setState({ ...state, email: e.target.value })} + propKeyPressEvt={(e) => e.key === 'Enter' && login()} value={state.email} - background="gray.50" - onChange={(e) => setState({ ...state, email: e.target.value })} + labelText={i18n.labels.email} + labelIcon={()} + error={!state.email.length ? i18n.labels.required : null} /> - - )} text="Password" /> - - setState({ ...state, password: e.target.value })} + propKeyPressEvt={(e) => e.key === 'Enter' && login()} value={state.password} - background="gray.50" - onChange={(e) => setState({ ...state, password: e.target.value })} + labelText={i18n.labels.password} + labelIcon={()} + error={!state.password.length ? i18n.labels.required : null} /> - +
); }; diff --git a/frontend/src/pages/User/Register.jsx b/frontend/src/pages/User/Register.jsx index 541bf7e..4f7e95b 100644 --- a/frontend/src/pages/User/Register.jsx +++ b/frontend/src/pages/User/Register.jsx @@ -1,12 +1,14 @@ import React, { useState } from 'react'; import { - Button, FormControl, FormLabel, Input, Heading, Text, FormHelperText, + Button, Heading, Text, Box, } from '@chakra-ui/react'; import { MdAlternateEmail, MdPassword, MdSend } from 'react-icons/md'; import { BiRename } from 'react-icons/bi'; import { useNavigate } from 'react-router-dom'; import store from '../../redux/store'; import IconTextDuo from '../../global/components/IconTextDuo'; +import { Register as i18n } from '../../global/i18n'; +import StandardInput from '../../global/components/FormControl/StandardInput'; export default () => { const [loading, setLoading] = useState(false); @@ -25,105 +27,115 @@ export default () => { }); const data = await resp.json(); - const message = { - header: resp.ok ? 'Account Created!' : 'Unable to Create Account', - content: resp.ok ? 'You will receive an account confirmation email shortly! Sit tight until you have verified your account.' : data.error, - }; - + const message = resp.ok ? i18n.createAccountSuccess : i18n.createAccountFailure(data); store.dispatch({ type: 'SET_ALERT', data: message }); resp.ok && navigate('/login', { replace: true }); setLoading(false); }; + return (
Account Setup - - Already have an account? Sign in - {' '} - here! + navigate('/login', { replace: true })} + _hover={{ fontWeight: 600, color: 'var(--chakra-colors-purple-500) !important' }} + > + {i18n.labels.login} - e.key === 'Enter' && register()} - onSubmit={register} - backgroundColor="gray.100" + - None of this information will be shared - - - )} text="First Name " /> - - e.key === 'Enter' && register()} + propChangeEvt={(e) => setState({ ...state, first: e.target.value })} value={state.first} - background="gray.50" - onChange={(e) => setState({ ...state, first: e.target.value })} + labelText={i18n.labels.first} + labelIcon={()} + error={!state.first.length ? i18n.labels.required : null} /> - - )} text="Last Name" /> - - e.key === 'Enter' && register()} + propChangeEvt={(e) => setState({ ...state, last: e.target.value })} value={state.last} - background="gray.50" - onChange={(e) => setState({ ...state, last: e.target.value })} + labelText={i18n.labels.last} + labelIcon={()} + error={!state.last.length ? i18n.labels.required : null} /> - - )} text="Email" /> - - e.key === 'Enter' && register()} + propChangeEvt={(e) => setState({ ...state, email: e.target.value })} value={state.email} - background="gray.50" - onChange={(e) => setState({ ...state, email: e.target.value })} + labelText={i18n.labels.email} + labelIcon={()} + error={!state.email.length ? i18n.labels.required : null} /> - - )} text="Password" /> - - setState({ ...state, password: e.target.value })} - /> - - - )} text="Verify Password" /> - - e.key === 'Enter' && register()} + propChangeEvt={(e) => setState({ ...state, password: e.target.value })} + value={state.password} + labelText={i18n.labels.password} + labelIcon={()} + error={(!state.password.length && i18n.labels.required) + || (state.password !== state.conf && i18n.labels.match) + || null} + /> + + e.key === 'Enter' && register()} + propChangeEvt={(e) => setState({ ...state, conf: e.target.value })} value={state.conf} - background="gray.50" - onChange={(e) => setState({ ...state, conf: e.target.value })} + labelText={i18n.labels.conf} + labelIcon={()} + error={(!state.conf.length && i18n.labels.required) + || (state.password !== state.conf && i18n.labels.match) + || null} /> - +
); }; diff --git a/frontend/src/redux/decode.js b/frontend/src/redux/decode.js index 903e0b3..85586a8 100644 --- a/frontend/src/redux/decode.js +++ b/frontend/src/redux/decode.js @@ -13,10 +13,10 @@ const decodeAndDispatch = async (token) => { if (resp.status === 410 && window.localStorage.getItem('auth-token')) { window.localStorage.removeItem('auth-token'); } - store.dispatch({ type: 'SET_ALERT', data: { header: 'Login Is Invalid', content: resp.error } }); + window.location.href = '/login?invalidOrExpired=true'; } } catch (ex) { - store.dispatch({ type: 'SET_ALERT', data: { header: 'Login Is Invalid', content: ex } }); + window.location.href = '/login?invalidOrExpired=true'; } };