repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
khoadaxne15/LastProject
src/views/admin/index.ts
<reponame>khoadaxne15/LastProject export * from "./add_product"; export * from "./components"; export * from "./dashboard"; export * from "./edit_product"; export * from "./products";
khoadaxne15/LastProject
src/components/product/ProductItem.tsx
import { CheckOutlined } from "@ant-design/icons"; import React from "react"; import Skeleton, { SkeletonTheme } from "react-loading-skeleton"; import { useHistory } from "react-router-dom"; import { displayMoney } from "../../helpers"; import { Product } from "../../redux"; import { ImageLoader } from "../common"; export const ProductItem: React.FC<ProductItemProps> = ({ product, isItemOnBasket, addToBasket }) => { const history = useHistory(); const onClickItem = () => { if (!product) { return; } if (product.id) { history.push(`/product/${product.id}`); } }; const itemOnBasket = isItemOnBasket ? isItemOnBasket(product.id) : false; const handleAddToBasket = () => { if (addToBasket) { addToBasket({ ...product, selectedSize: product.sizes[0] }); } }; return ( <SkeletonTheme color="#e1e1e1" highlightColor="#f2f2f2"> <div className={`product-card ${!product.id ? "product-loading" : ""}`} style={{ border: product && itemOnBasket ? "1px solid #a6a5a5" : "", boxShadow: product && itemOnBasket ? "0 10px 15px rgba(0, 0, 0, .07)" : "none", }}> {itemOnBasket && <CheckOutlined className="fa fa-check product-card-check" />} <div className="product-card-content" onClick={onClickItem} role="presentation"> <div className="product-card-img-wrapper"> {product.image ? ( <ImageLoader alt={product.name} className="product-card-img" src={product.image} /> ) : ( <Skeleton width="100%" height="90%" /> )} </div> <div className="product-details"> <h5 className="product-card-name text-overflow-ellipsis margin-auto"> {product.name || <Skeleton width={80} />} </h5> <p className="product-card-brand">{product.brand || <Skeleton width={60} />}</p> <h4 className="product-card-price"> {product.price ? displayMoney(product.price) : <Skeleton width={40} />} </h4> </div> </div> {product.id && ( <button className={`product-card-button button-small button button-block ${ itemOnBasket ? "button-border button-border-gray" : "" }`} onClick={handleAddToBasket} type="button"> {itemOnBasket ? "Remove from basket" : "Add to basket"} </button> )} </div> </SkeletonTheme> ); }; ProductItem.defaultProps = { isItemOnBasket: undefined, addToBasket: undefined, }; type ProductItemProps = { product: Product; isItemOnBasket?: (id: string) => boolean; addToBasket?: (product: Product) => void; };
khoadaxne15/LastProject
src/routers/PublicRoute.tsx
<filename>src/routers/PublicRoute.tsx<gh_stars>0 import React from "react"; import { connect } from "react-redux"; import { Redirect, Route } from "react-router-dom"; import { ADMIN_DASHBOARD, SIGNIN, SIGNUP } from "../constants"; import { AppState } from "../redux"; const _PublicRoute: React.FC<PublicRouteProps> = ({ isAuth, role, component: Component, path, ...rest }) => ( <Route {...rest} render={(props) => { // @ts-ignore const { from } = props.location.state || { from: { pathname: "/" } }; if (isAuth && role === "ADMIN") { return <Redirect to={ADMIN_DASHBOARD} />; } if (isAuth && role === "USER" && (path === SIGNIN || path === SIGNUP)) { return <Redirect to={from} />; } return ( <main className="content"> <Component {...props} /> </main> ); }} /> ); _PublicRoute.defaultProps = { isAuth: false, role: "USER", path: "/", exact: false, }; type PublicRouteProps = { isAuth?: boolean; role?: string; component: any; path?: string; exact?: boolean; }; const mapStateToProps = (params: AppState) => ({ isAuth: !!params.auth, role: params.auth?.role || "", }); export const PublicRoute = connect(mapStateToProps)(_PublicRoute);
khoadaxne15/LastProject
src/redux/reducers/checkoutReducer.ts
<gh_stars>0 import { AnyAction } from "typescript-fsa"; import { Payment, setPaymentDetails, setShippingDetails, Shipping } from "../actions"; export interface CheckoutState { shipping: Shipping; payment: Payment; } const initState: CheckoutState = { shipping: { fullname: "", email: "", address: "", mobile: undefined, }, payment: { type: "paypal", name: "", cardnumber: "", expiry: "", ccv: "", }, }; export function checkoutReducer(state: CheckoutState | undefined, action: AnyAction): CheckoutState { if (state === undefined) { return initState; } if (setShippingDetails.match(action)) { return { ...state, shipping: action.payload, }; } if (setPaymentDetails.match(action)) { return { ...state, payment: action.payload, }; } return state; }
khoadaxne15/LastProject
src/views/checkout/hoc/withCheckout.tsx
<reponame>khoadaxne15/LastProject import React from "react"; import { useSelector } from "react-redux"; import { Redirect, withRouter } from "react-router-dom"; import { SIGNIN } from "../../../constants"; import { calculateTotal } from "../../../helpers"; import { AppState, BasketState, CheckoutState, ProfileState } from "../../../redux"; export const withCheckout = (Component: any) => withRouter((props) => { const state = useSelector< AppState, { isAuth: boolean; basket: BasketState; shipping: CheckoutState["shipping"]; payment: CheckoutState["payment"]; profile: ProfileState; } >((store) => ({ isAuth: !!store.auth?.id && !!store.auth?.role, basket: store.basket, shipping: store.checkout.shipping, payment: store.checkout.payment, profile: store.profile, })); const shippingFee = state.shipping.isInternational ? 50 : 0; const subtotal = calculateTotal(state.basket.map((product) => product.price * product.quantity)); if (!state.isAuth) { return <Redirect to={SIGNIN} />; } if (state.basket.length === 0) { return <Redirect to="/" />; } if (state.isAuth && state.basket.length !== 0) { return ( <Component {...props} basket={state.basket} payment={state.payment} profile={state.profile} shipping={state.shipping} subtotal={Number(subtotal + shippingFee)} /> ); } return null; });
khoadaxne15/LastProject
src/hooks/useFileHandler.ts
<reponame>khoadaxne15/LastProject import { useState } from "react"; import { v4 as uuidv4 } from "uuid"; import { AddImageFile } from "../redux"; function arrayBufferToString(buffer: string | ArrayBuffer | null | undefined): string { if (!buffer) { return ""; } if (typeof buffer === "string") { return buffer; } return new Uint16Array(buffer).toString(); } export function useFileHandler<T extends string>(initState: Record<T, AddImageFile[]>) { const [imageFile, setImageFile] = useState(initState); const [isFileLoading, setFileLoading] = useState(false); const removeImage = (params: { id: string; name: T }) => { const items = imageFile[params.name].filter((item) => item.id !== params.id); setImageFile({ ...imageFile, [params.name]: items, }); }; const onFileChange = ( event: { target: { value: string; files: FileList | null } }, params: { name: T; type: "single" | "multiple" } ) => { const { files, value } = event.target; if (!files || !files[0]) { return; } const img: File = files[0]; const size = img.size / 1024 / 1024; setFileLoading(true); if (!/(\.jpg|\.jpeg|\.png)$/i.exec(value)) { alert("File type must be JPEG or PNG"); setFileLoading(false); return; } if (size > 0.5) { alert("File size exceeded 500kb, consider optimizing your image"); setFileLoading(false); return; } if (params.type === "multiple") { Array.from(files).forEach((file) => { const reader = new FileReader(); reader.addEventListener("load", (e) => { setImageFile((oldFiles) => ({ ...oldFiles, [params.name]: [ ...oldFiles[params.name], { file, url: arrayBufferToString(e.target?.result ?? ""), id: uuidv4() }, ], })); }); reader.readAsDataURL(file); }); setFileLoading(false); return; } // type is single const reader = new FileReader(); reader.addEventListener("load", (e) => { setImageFile((oldImageFiles) => ({ ...oldImageFiles, [params.name]: [ ...oldImageFiles[params.name], { file: img, url: arrayBufferToString(e.target?.result), id: uuidv4() }, ], })); setFileLoading(false); }); reader.readAsDataURL(img); }; return { imageFile, setImageFile, isFileLoading, onFileChange, removeImage, }; }
khoadaxne15/LastProject
src/redux/reducers/basketReducer.ts
<filename>src/redux/reducers/basketReducer.ts<gh_stars>0 import { AnyAction } from "typescript-fsa"; import { addQtyItem, addToBasket, clearBasket, minusQtyItem, removeFromBasket, setBasketItems } from "../actions"; import { Product } from "./productReducer"; export interface Item extends Product {} export type BasketState = Item[]; export function basketReducer(state: BasketState | undefined, action: AnyAction): BasketState { if (state === undefined) { return []; } if (setBasketItems.match(action)) { return action.payload; } if (addToBasket.match(action)) { return state.some((product) => product.id === action.payload.id) ? state : [action.payload, ...state]; } if (removeFromBasket.match(action)) { return state.filter((product) => product.id !== action.payload); } if (clearBasket.match(action)) { return []; } if (addQtyItem.match(action)) { return state.map((product) => { if (product.id === action.payload) { return { ...product, quantity: product.quantity + 1, }; } return product; }); } if (minusQtyItem.match(action)) { return state.map((product) => { if (product.id === action.payload) { return { ...product, quantity: product.quantity - 1, }; } return product; }); } return state; }
khoadaxne15/LastProject
src/views/account/components/UserOrdersTab.tsx
import React from "react"; export const UserOrdersTab = () => ( <div className="loader" style={{ minHeight: "80vh" }}> <h3>My Orders</h3> <strong> <span className="text-subtle">You don&apos;t have any orders</span> </strong> </div> );
khoadaxne15/LastProject
src/views/checkout/components/index.ts
<gh_stars>0 export { StepTracker } from "./StepTracker";
khoadaxne15/LastProject
src/views/account/edit_account/ConfirmModal.tsx
import { CheckOutlined, CloseOutlined } from "@ant-design/icons"; import { useFormikContext } from "formik"; import React, { useState } from "react"; import { Modal } from "../../../components"; export const ConfirmModal: React.FC<ConfirmModalProps> = ({ onConfirmUpdate, modal }) => { const [password, setPassword] = useState(""); const { values } = useFormikContext(); return ( <Modal isOpen={modal.isOpenModal} onRequestClose={() => modal.onCloseModal("edit_account")}> <div className="text-center padding-l"> <h4>Confirm Update</h4> <p> To continue updating profile including your &nbsp; <strong>email</strong> , <br /> please confirm by entering your password </p> <input className="input-form d-block" onChange={(e) => setPassword(e.target.value)} placeholder="Enter your password" required type="password" value={password} /> </div> <br /> <div className="d-flex-center"> <button className="button" onClick={() => { onConfirmUpdate(values, password); modal.onCloseModal("edit_account"); }} type="button"> <CheckOutlined /> &nbsp; Confirm </button> </div> <button className="modal-close-button button button-border button-border-gray button-small" onClick={() => modal.onCloseModal("edit_account")} type="button"> <CloseOutlined /> </button> </Modal> ); }; type ConfirmModalProps = { onConfirmUpdate: (values: any, password: string) => void; modal: { onCloseModal: (from: string) => void; isOpenModal: boolean; }; };
khoadaxne15/LastProject
src/components/common/ImageLoader.tsx
<filename>src/components/common/ImageLoader.tsx<gh_stars>0 import { LoadingOutlined } from "@ant-design/icons"; import React, { useState } from "react"; export const ImageLoader: React.FC<ImageLoaderProps> = ({ src, alt, className }) => { const [loaded, setLoaded] = useState(false); const onLoad = () => { setLoaded(true); }; return ( <> {!loaded && ( <LoadingOutlined style={{ position: "absolute", top: 0, bottom: 0, right: 0, left: 0, margin: "auto", }} /> )} <img alt={alt || ""} className={`${className || ""} ${loaded ? "is-img-loaded" : "is-img-loading"}`} onLoad={onLoad} // @ts-ignore src={src} /> </> ); }; ImageLoader.defaultProps = { className: "image-loader", }; type ImageLoaderProps = { src: File | string; alt: string; className?: string; };
khoadaxne15/LastProject
src/components/basket/BasketItemControl.tsx
<reponame>khoadaxne15/LastProject import { MinusOutlined, PlusOutlined } from "@ant-design/icons"; import * as React from "react"; import { useDispatch } from "react-redux"; import { addQtyItem, minusQtyItem, Product } from "../../redux"; interface BasketItemControlProps { product: Product; } export const BasketItemControl: React.FC<BasketItemControlProps> = ({ product }) => { const dispatch = useDispatch(); const onAddQty = () => { if (product.quantity < product.maxQuantity) { dispatch(addQtyItem(product.id)); } }; const onMinusQty = () => { if (product.maxQuantity >= product.quantity && product.quantity !== 0) { dispatch(minusQtyItem(product.id)); } }; return ( <div className="basket-item-control"> <button className="button button-border button-border-gray button-small basket-control basket-control-add" disabled={product.maxQuantity === product.quantity} onClick={onAddQty} type="button"> <PlusOutlined style={{ fontSize: "9px" }} /> </button> <button className="button button-border button-border-gray button-small basket-control basket-control-minus" disabled={product.quantity === 1} onClick={onMinusQty} type="button"> <MinusOutlined style={{ fontSize: "9px" }} /> </button> </div> ); };
khoadaxne15/LastProject
src/views/auth/forgot_password/index.tsx
import { CheckOutlined, LoadingOutlined } from "@ant-design/icons"; import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useDidMount, useDocumentTitle, useScrollTop } from "../../../hooks"; import { AppState, MiscState, resetPassword } from "../../../redux"; export const ForgotPassword: React.FC = () => { const { authStatus, isAuthenticating } = useSelector< AppState, { isAuthenticating: boolean; authStatus: MiscState["authStatus"] } >((state) => ({ isAuthenticating: state.app.isAuthenticating, authStatus: state.app.authStatus, })); const dispatch = useDispatch(); const didMount = useDidMount(); const [forgotPWStatus, setForgotPWStatus] = useState<MiscState["authStatus"]>(null); const [isSendingForgotPWRequest, setIsSending] = useState(false); const [field, setField] = useState<{ email?: string; error?: string }>({}); useScrollTop(); useDocumentTitle("Forgot Password | TK"); useEffect(() => { if (didMount) { setForgotPWStatus(authStatus); setIsSending(isAuthenticating); } }, [authStatus, didMount, isAuthenticating]); const onEmailChange = (value: string, error: string) => { setField({ email: value, error }); }; const onSubmitEmail = () => { if (!!field.email && !field.error) { dispatch(resetPassword(field.email)); } }; return ( <div className="forgot_password"> {forgotPWStatus?.message && ( <h5 className={`text-center ${authStatus?.success ? "toast-success" : "toast-error"}`}> {authStatus?.message} </h5> )} <h3>Forgot Your Password?</h3> <p>Enter your email address and we will send you a password reset email.</p> <br /> <input field="email" required className="input-form" label="* Email" maxLength={40} // @ts-ignore onChange={onEmailChange} placeholder="Enter your email" readOnly={isSendingForgotPWRequest || authStatus?.success} type="email" style={{ width: "100%" }} /> <br /> <br /> <button className="button w-100-mobile" disabled={isSendingForgotPWRequest || authStatus?.success} onClick={onSubmitEmail} type="button"> {isSendingForgotPWRequest ? <LoadingOutlined /> : <CheckOutlined />} &nbsp; {isSendingForgotPWRequest ? "Sending Password Reset Email" : "Send Password Reset Email"} </button> </div> ); };
khoadaxne15/LastProject
src/redux/actions/authActions.ts
import firebase from "firebase"; import actionCreatorFactory from "typescript-fsa"; const factory = actionCreatorFactory("AUTH"); export const signIn = factory.async<SignInPayload, SignInSuccessPayload>("SIGN_IN"); export interface SignInPayload { email: string; password: string; } export interface SignInSuccessPayload { id: string; role: string; provider: string | undefined; } export const signInWithGoogle = factory<SignInWithGooglePayload>("SIGN_IN_WITH_GOOGLE"); export interface SignInWithGooglePayload {} export const signInWithFacebook = factory<SignInWithGooglePayload>("SIGN_IN_WITH_FACEBOOK"); export interface SignInWithFacebookPayload {} export const signInWithGithub = factory<SignInWithGooglePayload>("SIGN_IN_WITH_GITHUB"); export interface SignInWithGithubPayload {} export const signUp = factory<SignUpPayload>("SIGN_UP"); export interface SignUpPayload { email: string; password: <PASSWORD>; fullname: string; } export const setAuthPersistence = factory<SetAuthPersistencePayload>("SET_AUTH_PERSISTENCE"); export interface SetAuthPersistencePayload {} export const signOut = factory.async<SignOutParamPayload, SignOutSuccessPayload>("SIGN_OUT"); export interface SignOutSuccessPayload {} export interface SignOutParamPayload {} export const onAuthStateChanged = factory.async< OnAuthStateChangedParam, OnAuthStateChangedResult, OnAuthStateChangedError >("AUTH_STATE_CHANGED"); export type OnAuthStateChangedParam = void; export type OnAuthStateChangedResult = firebase.User; export type OnAuthStateChangedError = string; export const resetPassword = factory<ResetPasswordPayload>("RESET_PASSWORD"); export type ResetPasswordPayload = string;
khoadaxne15/LastProject
src/redux/selectors/selector.ts
import { Filter, Product } from "../reducers"; export const selectFilter = (products: Product[], filter: Filter): Product[] => { if (!products || products.length === 0) { return []; } const keyword = filter.keyword?.toLowerCase(); return products .filter((product) => { const isInRange = filter.maxPrice ? product.price >= filter.minPrice && product.price <= filter.maxPrice : true; const matchKeyword = product.keywords ? product.keywords.includes(keyword ?? "") : true; // const matchName = product.name ? product.name.toLowerCase().includes(keyword) : true; const matchDescription = product.description ? product.description.toLowerCase().includes(keyword ?? "") : true; const matchBrand = product.brand ? product.brand.toLowerCase().includes(filter.brand.toLowerCase()) : true; console.log(product.brand, product.brand.toLowerCase(), filter.brand); return (matchKeyword || matchDescription) && matchBrand && isInRange; }) .sort((a, b) => { if (filter.sortBy === "name-desc") { return a.name < b.name ? 1 : -1; } else if (filter.sortBy === "name-asc") { return a.name > b.name ? 1 : -1; } else if (filter.sortBy === "price-desc") { return a.price < b.price ? 1 : -1; } return a.price > b.price ? 1 : -1; }); }; // Select product with highest price export const selectMax = (products: Product[]): number => { if (!products || products.length === 0) { return 0; } let high = products[0]; for (let i = 0; i < products.length; i++) { if (products[i].price > high.price) { high = products[i]; } } return Math.floor(high.price); }; // Select product with lowest price export const selectMin = (products: Product[]): number => { if (!products || products.length === 0) { return 0; } let low = products[0]; for (let i = 0; i < products.length; i++) { if (products[i].price < low.price) { low = products[i]; } } return Math.floor(low.price); };
khoadaxne15/LastProject
src/hooks/useBasket.ts
<filename>src/hooks/useBasket.ts<gh_stars>0 import { useDispatch, useSelector } from "react-redux"; import { displayActionMessage } from "../helpers"; import { AppState, BasketState, Product, addToBasket as dispatchAddToBasket, removeFromBasket } from "../redux"; export const useBasket = () => { const basket = useSelector<AppState, BasketState>((state) => state.basket); const dispatch = useDispatch(); const isItemOnBasket = (id: string) => !!basket.find((item) => item.id === id); const addToBasket = (product: Product) => { if (isItemOnBasket(product.id)) { dispatch(removeFromBasket(product.id)); displayActionMessage("Item removed from basket", "info"); } else { dispatch(dispatchAddToBasket({ ...product, quantity: 1 })); displayActionMessage("Item added to basket", "success"); } }; return { basket, isItemOnBasket, addToBasket }; };
khoadaxne15/LastProject
src/components/formik/CustomColorInput.tsx
import React from "react"; export const CustomColorInput: React.FC<InputColorProps> = (props) => { const { name, form, push, remove } = props; const [selectedColor, setSelectedColor] = React.useState(""); const handleColorChange = (e: any) => { const val = e.target.value; setSelectedColor(val); }; const handleAddSelectedColor = () => { if (!form.values[name].includes(selectedColor)) { push(selectedColor); setSelectedColor(""); } }; return ( <div className="d-flex"> <div className="input-group product-form-field"> <div className="d-flex"> {form.touched[name] && form.errors[name] ? ( <span className="label-input label-error">{form.errors[name]}</span> ) : ( <label className="label-input" htmlFor={name}> Available Colors </label> )} {selectedColor && ( <> <div className="color-item" style={{ background: selectedColor }} /> <h4 className="text-link" onClick={handleAddSelectedColor} style={{ textDecoration: "underline" }} role="presentation"> <i className="fa fa-check" /> Add Selected Color </h4> </> )} </div> <input name={name} type="color" onChange={handleColorChange} id={name} /> </div> <div className="product-form-field"> <span className="d-block padding-s">Selected Color(s)</span> <div className="color-chooser"> {form.values[name]?.map((color, index) => ( <div key={color} onClick={() => remove(index)} className="color-item color-item-deletable" title={`Remove ${color}`} style={{ backgroundColor: color }} role="presentation" /> ))} </div> </div> </div> ); }; type InputColorProps = { name: string; form: { values: Record<string, string[]>; touched: Record<string, any>; errors: Record<string, any>; }; push: (path: string) => void; remove: (index: number) => void; };
khoadaxne15/LastProject
src/hooks/useFeaturedProducts.ts
<gh_stars>0 import { useCallback, useEffect, useState } from "react"; import { Product } from "../redux"; import firebase from "../services/firebase"; import { useDidMount } from "./useDidMount"; export const useFeaturedProducts = (itemsCount: number) => { const [featuredProducts, setFeaturedProducts] = useState<Product[]>([]); const [isLoading, setLoading] = useState(false); const [error, setError] = useState(""); const didMount = useDidMount(true); const fetchFeaturedProducts = useCallback(async () => { try { setLoading(true); setError(""); const docs = await firebase.getFeaturedProducts(itemsCount); if (docs.empty) { if (didMount) { setError("No featured products found."); setLoading(false); } } else { const items: Product[] = []; docs.forEach((snap) => { const data = snap.data(); items.push({ ...data, id: snap.ref.id }); }); if (didMount) { setFeaturedProducts(items); setLoading(false); } } } catch (e) { if (didMount) { setError("Failed to fetch featured products"); setLoading(false); } } }, [didMount, itemsCount]); useEffect(() => { if (featuredProducts.length === 0 && didMount) { fetchFeaturedProducts(); } }, [didMount, featuredProducts.length, fetchFeaturedProducts]); return { featuredProducts, fetchFeaturedProducts, isLoading, error, }; };
khoadaxne15/LastProject
src/components/product/index.ts
export { ProductAppliedFilters } from "./ProductAppliedFilters"; export { ProductFeatured } from "./ProductFeatured"; export { ProductGrid } from "./ProductGrid"; export { ProductItem } from "./ProductItem"; export { ProductList } from "./ProductList"; export { ProductSearch } from "./ProductSearch"; export { ProductShowcase } from "./ProductShowcaseGrid";
khoadaxne15/LastProject
src/redux/reducers/filterReducer.ts
<reponame>khoadaxne15/LastProject<filename>src/redux/reducers/filterReducer.ts import { AnyAction } from "typescript-fsa"; import { applyFilter, clearRecentSearch, removeSelectedRecent, resetFilter, setBrandFilter, setMaxPriceFilter, setMinPriceFilter, setTextFilter, } from "../actions"; export interface Filter { recent?: string[]; keyword?: string; brand: string; minPrice: number; maxPrice: number; sortBy: string; } export type FilterState = Filter; const initState: FilterState = { recent: [], keyword: "", brand: "", minPrice: 0, maxPrice: 0, sortBy: "", }; export function filterReducer(state: FilterState | undefined, action: AnyAction): FilterState { if (state === undefined) { return initState; } if (setTextFilter.match(action)) { return { ...state, recent: !!state.recent?.find((n) => n === action.payload) || action.payload === "" ? state.recent : [action.payload, ...(state.recent ?? [])], keyword: action.payload, }; } if (setBrandFilter.match(action)) { return { ...state, brand: action.payload, }; } if (setMaxPriceFilter.match(action)) { return { ...state, maxPrice: action.payload, }; } if (setMinPriceFilter.match(action)) { return { ...state, minPrice: action.payload, }; } if (resetFilter.match(action)) { return initState; } if (clearRecentSearch.match(action)) { return { ...state, recent: [], }; } if (removeSelectedRecent.match(action)) { return { ...state, recent: state.recent?.filter((item) => item !== action.payload), }; } if (applyFilter.match(action)) { return { ...state, ...action.payload, }; } return state; }
khoadaxne15/LastProject
src/redux/actions/basketActions.ts
import actionCreatorFactory from "typescript-fsa"; import { Item } from "../reducers"; const factory = actionCreatorFactory("BASKET"); export const setBasketItems = factory<SetBasketItemsPayload>("SET_BASKET_ITEMS"); export type SetBasketItemsPayload = Item[]; export const addToBasket = factory<AddToBasketPayload>("ADD_TO_BASKET"); export type AddToBasketPayload = Item; export const removeFromBasket = factory<RemoveFromBasketPayload>("REMOVE_FROM_BASKET"); export type RemoveFromBasketPayload = string; export const clearBasket = factory<ClearBasketPayload>("CLEAR_BASKET"); export interface ClearBasketPayload {} export const addQtyItem = factory<AddQtyItemPayload>("ADD_QTY_ITEM"); export type AddQtyItemPayload = string; export const minusQtyItem = factory<MinusQtyItemPayload>("MINUS_QTY_ITEM"); export type MinusQtyItemPayload = string;
khoadaxne15/LastProject
src/views/checkout/step1/index.tsx
<filename>src/views/checkout/step1/index.tsx import { ArrowRightOutlined, ShopOutlined } from "@ant-design/icons"; import React from "react"; import { useHistory } from "react-router-dom"; import { BasketItem } from "../../../components/basket"; import { CHECKOUT_STEP_2 } from "../../../constants"; import { displayMoney } from "../../../helpers"; import { useDocumentTitle, useScrollTop } from "../../../hooks"; import { Product } from "../../../redux"; import { StepTracker } from "../components"; import { withCheckout } from "../hoc/withCheckout"; const OrderSummary: React.FC<OrderSummaryProps> = ({ basket, subtotal }) => { useDocumentTitle("Check Out Step 1 | TK"); useScrollTop(); const history = useHistory(); const onClickPrevious = () => history.push("/"); const onClickNext = () => history.push(CHECKOUT_STEP_2); return ( <div className="checkout"> <StepTracker current={1} /> <div className="checkout-step-1"> <h3 className="text-center">Order Summary</h3> <span className="d-block text-center">Review items in your basket.</span> <br /> <div className="checkout-items"> {basket.map((product) => ( <BasketItem basket={basket} key={product.id} product={product} /> ))} </div> <br /> <div className="basket-total text-right"> <p className="basket-total-title">Subtotal:</p> <h2 className="basket-total-amount">{displayMoney(subtotal)}</h2> </div> <br /> <div className="checkout-shipping-action"> <button className="button button-muted" onClick={onClickPrevious} type="button"> <ShopOutlined /> &nbsp; Continue Shopping </button> <button className="button" onClick={onClickNext} type="submit"> Next Step &nbsp; <ArrowRightOutlined /> </button> </div> </div> </div> ); }; type OrderSummaryProps = { basket: Product[]; subtotal: number; }; export const CheckOutStep1 = withCheckout(OrderSummary);
khoadaxne15/LastProject
src/views/index.ts
export * from "./account/edit_account"; export * from "./account/user_account"; export * from "./admin/add_product"; export * from "./admin/dashboard"; export * from "./admin/edit_product"; export * from "./admin/products"; export * from "./auth/forgot_password"; export * from "./auth/signin"; export * from "./auth/signup"; export * from "./checkout/step1"; export * from "./checkout/step2"; export * from "./checkout/step3"; export * from "./error/PageNotFound"; export * from "./featured"; export * from "./home"; export * from "./recommended"; export * from "./search"; export * from "./shop"; export * from "./view_product"; export * from "./checkout";
khoadaxne15/LastProject
src/components/common/PriceRange/TooltipRail.tsx
<reponame>khoadaxne15/LastProject import React, { useState } from "react"; const railStyle: React.CSSProperties = { position: "absolute", width: "100%", transform: "translate(0%, -50%)", height: 20, cursor: "pointer", zIndex: 300, // border: '1px solid grey', }; const railCenterStyle: React.CSSProperties = { position: "absolute", width: "100%", transform: "translate(0%, -50%)", height: 14, borderRadius: 7, cursor: "pointer", pointerEvents: "none", backgroundColor: "#d0d0d0", }; export const TooltipRail: React.FC<TooltipRailProps> = (props) => { const [value, setValue] = useState(null); const [percent, setPercent] = useState<number | null>(0); const onMouseEnter = () => { document.addEventListener("mousemove", onMouseMove); }; const onMouseLeave = () => { setValue(null); setPercent(null); document.removeEventListener("mousemove", onMouseMove); }; const onMouseMove = (e: MouseEvent) => { const { activeHandleID, getEventData } = props; if (activeHandleID) { setValue(null); setPercent(null); } else { const eventData = getEventData?.(e); if (eventData) { setValue(eventData.value); setPercent(eventData.percent); } } }; const { activeHandleID, getRailProps } = props; return ( <> {!activeHandleID && value ? ( <div style={{ left: `${percent}%`, position: "absolute", marginLeft: "-11px", marginTop: "-35px", }}> <div className="tooltip"> <span className="tooltiptext"> Value: {value} </span> </div> </div> ) : null} <div style={railStyle} {...getRailProps({ onMouseEnter, onMouseLeave, })} /> <div style={railCenterStyle} /> </> ); }; TooltipRail.defaultProps = { getEventData: undefined, activeHandleID: undefined, disabled: false, }; type TooltipRailProps = { getEventData?: (e: MouseEvent) => { value: any; percent: number | null }; activeHandleID?: string; getRailProps: (params: { onMouseEnter: () => void; onMouseLeave: () => void }) => React.ReactNode; disabled?: boolean; };
khoadaxne15/LastProject
src/components/product/ProductList.tsx
<filename>src/components/product/ProductList.tsx import React, { useCallback, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import { setLoading, getProducts, Product, SearchedProduct } from "../../redux"; import { Boundary, MessageDisplay } from "../common"; export const ProductList: React.FC<ProductListProps> = (props) => { const { products, filteredProducts, isLoading, requestStatus, children } = props; const [isFetching, setFetching] = useState(false); const dispatch = useDispatch(); const fetchProducts = useCallback(() => { setFetching(true); dispatch(getProducts.started(products.lastRefKey)); }, [products.lastRefKey]); // eslint-disable-line react-hooks/exhaustive-deps // @ts-ignore useEffect(() => { if (products.items.length === 0 || !products.lastRefKey) { fetchProducts(); } window.scrollTo(0, 0); return () => dispatch(setLoading(false)); }, [fetchProducts, products.items.length, products.lastRefKey]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { setFetching(false); }, [products.lastRefKey]); if (filteredProducts.length === 0 && !isLoading) { return <MessageDisplay message={requestStatus?.message || "No products found."} />; } if (filteredProducts.length === 0 && requestStatus) { return ( <MessageDisplay message={requestStatus?.message || "Something went wrong :("} action={fetchProducts} buttonLabel="Try Again" /> ); } return ( <Boundary> {children} {/* Show 'Show More' button if products length is less than total products */} {products.items.length < products.total && ( <div className="d-flex-center padding-l"> <button className="button button-small" disabled={isFetching} onClick={fetchProducts} type="button"> {isFetching ? "Fetching Items..." : "Show More Items"} </button> </div> )} </Boundary> ); }; ProductList.defaultProps = { requestStatus: undefined, }; type ProductListProps = { products: SearchedProduct; filteredProducts: Product[]; isLoading: boolean; requestStatus?: { message: string }; children: React.ReactNode[] | React.ReactNode; };
khoadaxne15/LastProject
src/redux/reducers/profileReducer.ts
<reponame>khoadaxne15/LastProject import { AnyAction } from "typescript-fsa"; import { clearProfile, setProfile, updateProfile } from "../actions"; export interface Mobile { country?: string; countryCode?: string; dialCode?: string; value?: string; } export interface Profile { fullname?: string; email?: string | null; address?: string; mobile?: Mobile; avatar?: string; banner?: string; dateJoined?: string; role?: string; } export interface File { bannerFile: string; avatarFile: string; } export type ProfileState = Profile; export function profileReducer(state: ProfileState | undefined, action: AnyAction): ProfileState { if (state === undefined) { return {}; } if (setProfile.match(action)) { return action.payload; } if (updateProfile.done.match(action)) { return { ...state, ...action.payload.result.updates }; } if (clearProfile.match(action)) { return {}; } return state; }
khoadaxne15/LastProject
src/redux/actions/productActions.ts
<filename>src/redux/actions/productActions.ts<gh_stars>0 import actionCreatorFactory from "typescript-fsa"; import { ProductFormSchema } from "../../views/admin"; import { Product, SearchedProduct } from "../reducers"; const factory = actionCreatorFactory("PRODUCT"); export const getProducts = factory.async<GetProductsPayload, GetProductsSuccessPayload>("GET_PRODUCTS"); export type GetProductsPayload = string | null; export type GetProductsSuccessPayload = SearchedProduct; export const cancelGetProducts = factory<CancelGetProductsPayload>("CANCEL_GET_PRODUCTS"); export interface CancelGetProductsPayload {} export const addProduct = factory.async<AddProductPayload, AddProductSuccessPayload>("ADD_PRODUCT"); export interface AddProductPayload extends Product { imageCollection: AddImageFile[]; image: File; } export type AddProductSuccessPayload = Product; export type ImageCollection = ImageFile[]; export type ImageFile = { id: string; file?: File; url?: string }; export type AddImageFile = { id: string; file: File; url?: string }; export const searchProduct = factory.async<SearchProductPayload, SearchProductSuccessPayload>("SEARCH_PRODUCT"); export interface SearchProductPayload { searchKey: string; } export type SearchProductSuccessPayload = SearchedProduct; export const clearSearchState = factory<ClearSearchStatePayload>("CLEAR_SEARCH_STATE"); export type ClearSearchStatePayload = void; export const removeProduct = factory.async<RemoveProductPayload, RemoveProductSuccessPayload>("REMOVE_PRODUCT"); export type RemoveProductPayload = string; export type RemoveProductSuccessPayload = string | undefined; export const editProduct = factory.async<EditProductPayload, EditProductSuccessPayload>("EDIT_PRODUCT"); export interface EditProductPayload { id: string; updates: ProductFormSchema & { imageCollection?: ImageCollection; image?: string; }; } export interface EditProductSuccessPayload { id: string; updates: ProductFormSchema; }
khoadaxne15/LastProject
src/routers/AppRouter.tsx
import { createBrowserHistory } from "history"; import React from "react"; import { Route, Router, Switch } from "react-router-dom"; import { Footer, Navigation, Basket } from "../components"; import * as ROUTES from "../constants/routes"; import { CheckOutStep1, CheckOutStep2, CheckOutStep3, EditAccount, AddProduct, Dashboard, EditProduct, FeaturedProducts, ForgotPassword, Home, PageNotFound, Products, RecommendedProducts, Search, Shop, SignIn, SignUp, UserAccount, ViewProduct, } from "../views"; import { AdminRoute } from "./AdminRoute"; import { ClientRoute } from "./ClientRoute"; import { PublicRoute } from "./PublicRoute"; // Revert back to history v4.10.0 because // v5.0 breaks navigation export const history = createBrowserHistory(); export const AppRouter: React.FC = () => ( <Router history={history}> <> <Navigation /> <Basket /> <Switch> <Route component={Search} exact path={ROUTES.SEARCH} /> <Route component={Home} exact path={ROUTES.HOME} /> <Route component={Shop} exact path={ROUTES.SHOP} /> <Route component={FeaturedProducts} exact path={ROUTES.FEATURED_PRODUCTS} /> <Route component={RecommendedProducts} exact path={ROUTES.RECOMMENDED_PRODUCTS} /> <PublicRoute component={SignUp} path={ROUTES.SIGNUP} /> <PublicRoute component={SignIn} exact path={ROUTES.SIGNIN} /> <PublicRoute component={ForgotPassword} path={ROUTES.FORGOT_PASSWORD} /> <Route component={ViewProduct} path={ROUTES.VIEW_PRODUCT} /> <ClientRoute component={UserAccount} exact path={ROUTES.ACCOUNT} /> <ClientRoute component={EditAccount} exact path={ROUTES.ACCOUNT_EDIT} /> <ClientRoute component={CheckOutStep1} path={ROUTES.CHECKOUT_STEP_1} /> <ClientRoute component={CheckOutStep2} path={ROUTES.CHECKOUT_STEP_2} /> <ClientRoute component={CheckOutStep3} path={ROUTES.CHECKOUT_STEP_3} /> <AdminRoute component={Dashboard} exact path={ROUTES.ADMIN_DASHBOARD} /> <AdminRoute component={Products} path={ROUTES.ADMIN_PRODUCTS} /> <AdminRoute component={AddProduct} path={ROUTES.ADD_PRODUCT} /> <AdminRoute component={EditProduct} path={`${ROUTES.EDIT_PRODUCT}/:id`} /> <PublicRoute component={PageNotFound} /> </Switch> <Footer /> </> </Router> );
khoadaxne15/LastProject
src/redux/actions/checkoutActions.ts
<reponame>khoadaxne15/LastProject import actionCreatorFactory from "typescript-fsa"; import { Mobile } from "../reducers"; const factory = actionCreatorFactory("CHECKOUT"); export const setShippingDetails = factory<SetCheckoutShippingPayload>("SET_CHECKOUT_SHIPPING_DETAILS"); export type SetCheckoutShippingPayload = Shipping; export interface Shipping { fullname: string; email: string; address: string; mobile?: Mobile; isInternational?: boolean; isDone?: boolean; } export const setPaymentDetails = factory<SetCheckoutPaymentPayload>("SET_CHECKOUT_PAYMENT_DETAILS"); export type SetCheckoutPaymentPayload = Payment; export interface Payment { type: string; name: string; cardnumber?: string; expiry: string; ccv?: string; } export const resetCheckout = factory<ResetCheckoutPayload>("RESET_CHECKOUT"); export interface ResetCheckoutPayload {}
khoadaxne15/LastProject
src/hooks/useRecommendedProducts.ts
<gh_stars>0 import { useCallback, useEffect, useState } from "react"; import { Product } from "../redux"; import firebase from "../services/firebase"; import { useDidMount } from "./useDidMount"; export const useRecommendedProducts = (itemsCount: number) => { const [recommendedProducts, setRecommendedProducts] = useState<Product[]>([]); const [isLoading, setLoading] = useState(false); const [error, setError] = useState(""); const didMount = useDidMount(true); const fetchRecommendedProducts = useCallback(async () => { try { setLoading(true); setError(""); const docs = await firebase.getRecommendedProducts(itemsCount); if (docs.empty) { if (didMount) { setError("No recommended products found."); setLoading(false); } } else { const items: Product[] = []; docs.forEach((snap) => { const data = snap.data(); items.push({ ...data, id: snap.ref.id }); }); if (didMount) { setRecommendedProducts(items); setLoading(false); } } } catch (e) { if (didMount) { setError("Failed to fetch recommended products"); setLoading(false); } } }, [didMount, itemsCount]); useEffect(() => { if (recommendedProducts.length === 0 && didMount) { fetchRecommendedProducts(); } }, [didMount, fetchRecommendedProducts, recommendedProducts.length]); return { recommendedProducts, fetchRecommendedProducts, isLoading, error, }; };
khoadaxne15/LastProject
src/redux/reducers/miscReducer.ts
<reponame>khoadaxne15/LastProject import { AnyAction } from "typescript-fsa"; import { AuthStatus, setAuthenticating, setAuthStatus, setLoading, setRequestStatus } from "../actions"; export interface MiscState { loading: boolean; isAuthenticating: boolean; authStatus: AuthStatus; requestStatus: { message: string } | undefined; theme: string; } const initState: MiscState = { loading: false, isAuthenticating: false, authStatus: null, requestStatus: undefined, theme: "light", }; export function miscReducer(state: MiscState | undefined, action: AnyAction): MiscState { if (state === undefined) { return initState; } if (setLoading.match(action)) { return { ...state, loading: action.payload, }; } if (setAuthenticating.match(action)) { return { ...state, isAuthenticating: action.payload, }; } if (setRequestStatus.match(action)) { return { ...state, requestStatus: action.payload, }; } if (setAuthStatus.match(action)) { return { ...state, authStatus: action.payload, }; } return state; }
khoadaxne15/LastProject
src/components/product/ProductAppliedFilters.tsx
<gh_stars>0 import { CloseCircleOutlined } from "@ant-design/icons"; import React from "react"; import { shallowEqual, useDispatch, useSelector } from "react-redux"; import { applyFilter, AppState, FilterState } from "../../redux"; export const ProductAppliedFilters: React.FC<ProductAppliedFiltersProps> = ({ filteredProductsCount }) => { const filter = useSelector<AppState, FilterState>((state) => state.filter, shallowEqual); const fields: (keyof FilterState)[] = ["brand", "minPrice", "maxPrice", "sortBy", "keyword"]; const isFiltered = fields.some((key) => !!filter[key]); const dispatch = useDispatch(); console.log({ filter, isFiltered }); const onRemoveKeywordFilter = () => { dispatch(applyFilter({ keyword: "" })); }; const onRemovePriceRangeFilter = () => { dispatch(applyFilter({ minPrice: 0, maxPrice: 0 })); }; const onRemoveBrandFilter = () => { dispatch(applyFilter({ brand: "" })); }; const onRemoveSortFilter = () => { dispatch(applyFilter({ sortBy: "" })); }; return !isFiltered ? null : ( <> <div className="product-list-header"> <div className="product-list-header-title"> <h5> {filteredProductsCount > 0 && `Found ${filteredProductsCount} ${filteredProductsCount > 1 ? "products" : "product"}`} </h5> </div> </div> <div className="product-applied-filters"> {filter.keyword && ( <div className="pill-wrapper"> <span className="d-block">Keyword</span> <div className="pill padding-right-l"> <h5 className="pill-content margin-0">{filter.keyword}</h5> <div className="pill-remove" onClick={onRemoveKeywordFilter} role="presentation"> <h5 className="margin-0 text-subtle"> <CloseCircleOutlined /> </h5> </div> </div> </div> )} {filter.brand && ( <div className="pill-wrapper"> <span className="d-block">Brand</span> <div className="pill padding-right-l"> <h5 className="pill-content margin-0">{filter.brand}</h5> <div className="pill-remove" onClick={onRemoveBrandFilter} role="presentation"> <h5 className="margin-0 text-subtle"> <CloseCircleOutlined /> </h5> </div> </div> </div> )} {(!!filter.minPrice || !!filter.maxPrice) && ( <div className="pill-wrapper"> <span className="d-block">Price Range</span> <div className="pill padding-right-l"> <h5 className="pill-content margin-0"> ${filter.minPrice}- ${filter.maxPrice} </h5> <div className="pill-remove" onClick={onRemovePriceRangeFilter} role="presentation"> <h5 className="margin-0 text-subtle"> <CloseCircleOutlined /> </h5> </div> </div> </div> )} {filter.sortBy && ( <div className="pill-wrapper"> <span className="d-block">Sort By</span> <div className="pill padding-right-l"> <h5 className="pill-content margin-0"> {filter.sortBy === "price-desc" ? "Price High - Low" : filter.sortBy === "price-asc" ? "Price Low - High" : filter.sortBy === "name-desc" ? "Name Z - A" : "Name A - Z"} </h5> <div className="pill-remove" onClick={onRemoveSortFilter} role="presentation"> <h5 className="margin-0 text-subtle"> <CloseCircleOutlined /> </h5> </div> </div> </div> )} </div> </> ); }; ProductAppliedFilters.defaultProps = { filteredProductsCount: 0, }; type ProductAppliedFiltersProps = { filteredProductsCount: number; };
khoadaxne15/LastProject
src/hooks/useModal.ts
import { useMemo, useState } from "react"; export const useModal = () => { const [isOpenModal, setModalOpen] = useState(false); const onOpenModal = () => { console.log("onOpenModal"); setModalOpen(() => true); }; const onCloseModal = (from: string) => { console.log("onCloseModal", from); setModalOpen(() => false); }; return useMemo( () => ({ isOpenModal, onOpenModal, onCloseModal, }), [isOpenModal] ); };
khoadaxne15/LastProject
src/services/firebase.ts
<reponame>khoadaxne15/LastProject<filename>src/services/firebase.ts import app from "firebase/app"; import "firebase/auth"; import "firebase/firestore"; import "firebase/storage"; import firebase from "firebase/app"; import { BasketState, Profile, Product, EditProductPayload } from "../redux"; import firebaseConfig from "./config"; import DocumentSnapshot = firebase.firestore.DocumentSnapshot; class Firebase { private storage: ReturnType<typeof app.storage>; private db: ReturnType<typeof app.firestore>; public auth: ReturnType<typeof app.auth>; constructor() { if (!app.apps.length) { app.initializeApp(firebaseConfig); } this.storage = app.storage(); this.db = app.firestore(); this.auth = app.auth(); } // AUTH ACTIONS ------------ createAccount = (email: string, password: string) => { return this.auth.createUserWithEmailAndPassword(email, password); }; signIn = (email: string, password: string) => this.auth.signInWithEmailAndPassword(email, password); signInWithGoogle = () => this.auth.signInWithPopup(new app.auth.GoogleAuthProvider()); signInWithFacebook = () => this.auth.signInWithPopup(new app.auth.FacebookAuthProvider()); signInWithGithub = () => this.auth.signInWithPopup(new app.auth.GithubAuthProvider()); signOut = () => this.auth.signOut(); passwordReset = (email: string) => this.auth.sendPasswordResetEmail(email); addUser = (id: string, user: Profile) => this.db.collection("users").doc(id).set(user); getUser = (id: string) => this.db.collection("users").doc(id).get(); passwordUpdate = (password: string) => this.auth.currentUser?.updatePassword(password); changePassword = (currentPassword: string, newPassword: string) => new Promise((resolve, reject) => { this.reauthenticate(currentPassword) .then(() => { const user = this.auth.currentUser; user ?.updatePassword(newPassword) .then(() => resolve("Password updated successfully!")) .catch((error) => reject(error)); }) .catch((error) => reject(error)); }); reauthenticate = (currentPassword: string) => { const user = this.auth.currentUser; if (!user?.email) { throw new Error("reauthenticate"); } const cred = app.auth.EmailAuthProvider.credential(user.email, currentPassword); return user.reauthenticateWithCredential(cred); }; updateEmail = (currentPassword: string, newEmail: string) => new Promise((resolve, reject) => { this.reauthenticate(currentPassword) .then(() => { const user = this.auth.currentUser; user ?.updateEmail(newEmail) .then(() => resolve("Email Successfully updated")) .catch((error) => reject(error)); }) .catch((error) => reject(error)); }); updateProfile = (id: string, updates: Partial<Profile>) => this.db.collection("users").doc(id).update(updates); onAuthStateChanged = () => new Promise((resolve, reject) => { this.auth.onAuthStateChanged((user) => { if (user) { resolve(user); } else { reject(new Error("Auth State Changed failed")); } }); }); saveBasketItems = (items: BasketState, userId: string) => this.db.collection("users").doc(userId).update({ basket: items }); setAuthPersistence = () => this.auth.setPersistence(app.auth.Auth.Persistence.LOCAL); // PRODUCT ACTIONS -------------- getSingleProduct = (id: string) => this.db.collection("products").doc(id).get() as Promise<DocumentSnapshot<Product>>; getProducts = (lastRefKey: string | null) => { let didTimeout = false; return new Promise((resolve, reject) => { (async () => { if (lastRefKey) { console.log({ lastRefKey }); try { const query = this.db .collection("products") .orderBy(app.firestore.FieldPath.documentId()) .startAfter(lastRefKey) .limit(12); const snapshot = (await query.get()) as app.firestore.QuerySnapshot<Product>; const products: Product[] = []; snapshot.forEach((doc) => products.push({ ...doc.data(), id: doc.id })); console.log({ snapshot, products }); const lastKey = snapshot.docs[snapshot.docs.length - 1]; resolve({ items: products, lastKey }); } catch (e: any) { reject(e?.message || ":( Failed to fetch products."); } } else { const timeout = setTimeout(() => { didTimeout = true; reject(new Error("Request timeout, please try again")); }, 15000); try { const totalQuery = await this.db.collection("products").get(); const total = totalQuery.docs.length; const query = this.db.collection("products").orderBy(app.firestore.FieldPath.documentId()).limit(12); const snapshot = (await query.get()) as app.firestore.QuerySnapshot<Product>; clearTimeout(timeout); if (!didTimeout) { const products: Product[] = []; snapshot.forEach((doc) => products.push({ ...doc.data(), id: doc.id })); const lastKey = snapshot.docs[snapshot.docs.length - 1]; resolve({ items: products, lastKey, total }); } } catch (e: any) { if (didTimeout) { return; } reject(e?.message || ":( Failed to fetch products."); } } })(); }); }; searchProducts = (searchKey: string) => { let didTimeout = false; return new Promise((resolve, reject) => { (async () => { const productsRef = this.db.collection("products"); const timeout = setTimeout(() => { didTimeout = true; reject(new Error("Request timeout, please try again")); }, 15000); try { const searchedNameRef = productsRef .orderBy("name_lower") .where("name_lower", ">=", searchKey) .where("name_lower", "<=", `${searchKey}\uf8ff`) .limit(12) as app.firestore.Query<Product>; const searchedKeywordsRef = productsRef .orderBy("dateAdded", "desc") .where("keywords", "array-contains-any", searchKey.split(" ")) .limit(12) as app.firestore.Query<Product>; // const totalResult = await totalQueryRef.get(); const nameSnaps = await searchedNameRef.get(); const keywordsSnaps = await searchedKeywordsRef.get(); // const total = totalResult.docs.length; clearTimeout(timeout); if (!didTimeout) { const searchedNameProducts: Product[] = []; const searchedKeywordsProducts: Product[] = []; let lastKey = null; if (!nameSnaps.empty) { nameSnaps.forEach((doc) => { searchedNameProducts.push({ ...doc.data(), id: doc.id }); }); lastKey = nameSnaps.docs[nameSnaps.docs.length - 1]; } if (!keywordsSnaps.empty) { keywordsSnaps.forEach((doc) => { searchedKeywordsProducts.push({ ...doc.data(), id: doc.id }); }); } // MERGE PRODUCTS const mergedProducts = [...searchedNameProducts, ...searchedKeywordsProducts]; const hash: Record<string, Product> = {}; mergedProducts.forEach((product) => { hash[product.id] = product; }); resolve({ products: Object.values(hash), lastKey }); } } catch (e) { if (didTimeout) { return; } reject(e); } })(); }); }; getFeaturedProducts = (itemsCount = 12) => this.db.collection("products").where("isFeatured", "==", true).limit(itemsCount).get() as Promise< app.firestore.QuerySnapshot<Product> >; getRecommendedProducts = (itemsCount = 12) => this.db.collection("products").where("isRecommended", "==", true).limit(itemsCount).get() as Promise< app.firestore.QuerySnapshot<Product> >; addProduct = (id: string, product: Product) => this.db.collection("products").doc(id).set(product); generateKey = () => this.db.collection("products").doc().id; storeImage = async (id: string, folder: string, imageFile: File) => { const snapshot = await this.storage .ref(folder) .child(id) .put(new Blob([imageFile], { type: "text/plain" })); const downloadURL = await snapshot.ref.getDownloadURL(); return downloadURL; }; deleteImage = (id: string) => this.storage.ref("products").child(id).delete(); editProduct = (id: string, updates: EditProductPayload["updates"]) => this.db.collection("products").doc(id).update(updates); removeProduct = (id: string) => this.db.collection("products").doc(id).delete(); } export const firebaseInstance = new Firebase(); export default firebaseInstance;
khoadaxne15/LastProject
src/redux/sagas/rootSaga.ts
<reponame>khoadaxne15/LastProject<filename>src/redux/sagas/rootSaga.ts import { SagaIterator } from "redux-saga"; import { takeLatest } from "redux-saga/effects"; import { AnyAction } from "typescript-fsa"; import { onAuthStateChanged, resetPassword, setAuthPersistence, signIn, signInWithFacebook, signInWithGithub, signInWithGoogle, signOut, signUp, searchProduct, removeProduct, addProduct, editProduct, getProducts, updateEmail, updateProfile, } from "../actions"; import { authSaga } from "./authSaga"; import { productSaga } from "./productSaga"; import { profileSaga } from "./profileSaga"; export function* rootSaga(): SagaIterator { yield takeLatest((action: AnyAction) => { return [ signIn.started, signUp, signOut.started, signInWithFacebook, signInWithGoogle, signInWithGithub, onAuthStateChanged.started, onAuthStateChanged.failed, onAuthStateChanged.done, setAuthPersistence, resetPassword, ].some((a) => a.match(action)); }, authSaga); yield takeLatest( (action: AnyAction) => [addProduct.started, searchProduct.started, removeProduct.started, editProduct.started, getProducts.started].some( (a) => a.match(action) ), productSaga ); yield takeLatest( (action: AnyAction) => [updateEmail, updateProfile.started].some((a) => a.match(action)), profileSaga ); }
khoadaxne15/LastProject
src/components/formik/CustomInput.tsx
<filename>src/components/formik/CustomInput.tsx import React from "react"; export const CustomInput: React.FC<CustomInputProps> = ({ field, form: { touched, errors }, label, inputRef, ...props }) => { return ( <div className="input-group"> {touched[field.name] && errors[field.name] ? ( <span className="label-input label-error">{errors[field.name]}</span> ) : ( <label className="label-input" htmlFor={field.name}> {label} </label> )} <input type="text" id={field.name} className={`input-form ${touched[field.name] && errors[field.name] && "input-error"}`} ref={inputRef} {...field} {...props} /> </div> ); }; CustomInput.defaultProps = { inputRef: undefined, }; type CustomInputProps = { label: string; field: { name: string }; form: { touched: Record<string, string[]>; errors: Record<string, string[]> }; inputRef: React.MutableRefObject<HTMLInputElement | null>; };
khoadaxne15/LastProject
src/components/formik/index.ts
<gh_stars>0 export { CustomColorInput } from "./CustomColorInput"; export { CustomCreatableSelect } from "./CustomCreatableSelect"; export { CustomInput } from "./CustomInput"; export { CustomMobileInput } from "./CustomMobileInput"; export { CustomTextarea } from "./CustomTextarea";
khoadaxne15/LastProject
src/hooks/useProduct.ts
import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { Product, AppState } from "../redux"; import firebase from "../services/firebase"; import { useDidMount } from "./useDidMount"; export const useProduct = (id: string) => { // get and check if product exists in store const storeProduct = useSelector<AppState, Product | undefined>((state) => state.products.items.find((item) => item.id === id) ); const [product, setProduct] = useState(storeProduct); const [isLoading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const didMount = useDidMount(true); useEffect(() => { (async () => { try { if (!product || product.id !== id) { setLoading(true); const doc: { exists: boolean; ref: { id: string }; data: () => any } = await firebase.getSingleProduct(id); if (doc.exists) { const data: Product = { ...doc.data(), id: doc.ref.id }; if (didMount) { setProduct(data); setLoading(false); } } else { setError("Product not found."); } } } catch (err: any) { if (didMount) { setLoading(false); setError(err?.message || "Something went wrong."); } } })(); }, [didMount, id, product]); return { product, isLoading, error }; };
khoadaxne15/LastProject
src/services/generate.ts
import * as fs from "fs"; import * as Path from "path"; import * as axios from "axios"; import DotEnv from "dotenv"; import Faker from "faker"; import app from "firebase/app"; import "firebase/auth"; import "firebase/firestore"; import "firebase/storage"; import { v4 as uuidv4 } from "uuid"; import { Product } from "../redux"; DotEnv.config({ path: Path.join(__dirname, "..", "..", ".env.dev") }); import firebaseConfig from "./config"; class Firebase { private storage: ReturnType<typeof app.storage>; private db: ReturnType<typeof app.firestore>; public auth: ReturnType<typeof app.auth>; constructor() { console.log(firebaseConfig); if (!app.apps.length) { app.initializeApp(firebaseConfig); } this.storage = app.storage(); this.db = app.firestore(); this.auth = app.auth(); } generateKey = () => this.db.collection("products").doc().id; storeImage = async (id: string, folder: string, imageFile: ArrayBuffer) => { const snapshot = await this.storage.ref(folder).child(id).put(imageFile); return await snapshot.ref.getDownloadURL(); }; // AUTH ACTIONS ------------ addProduct = async () => { console.log("@@@@") await this.auth.signInWithEmailAndPassword("<EMAIL>", "<PASSWORD>"); for (let i = 0; i < 10; i++) { console.log(i); const key = this.generateKey(); const imageFile = fs.readFileSync( Path.join(__dirname, "..", "..", "generate", Math.floor(Math.random() * 10) + ".png") ); const downloadURL = await this.storeImage(key, "products", imageFile); const image = { id: key, url: downloadURL }; const maxQuantity = Math.floor(Math.random() * 1000); const description = Faker.commerce.productDescription(); const product: Product = { id: uuidv4(), imageUrl: "", quantity: Math.floor(Math.random() * maxQuantity), availableColors: Faker.random.arrayElements( [ "LightCoral", "Crimson", "HotPink", "PaleVioletRed", "Coral", "LightSalmon", "Gold", "MediumPurple", "Purple", "YellowGreen", "Teal", "Cyan", "LightBlue", ], 7 ), brand: Faker.company.companyName(), description, maxQuantity, name: Faker.commerce.productName(), price: Math.floor(Math.random() * 1000), sizes: Faker.random.arrayElements([3, 4, 5, 6, 7, 8, 9, 10], 4), isFeatured: Math.random() < 0.7, isRecommended: Math.random() < 0.7, keywords: Faker.random.arrayElements(description.split(" "), 3), image: downloadURL, imageCollection: [image], }; await this.db.collection("products").doc(key).set(product); } }; } // @ts-ignore const firebaseInstance = new Firebase(); firebaseInstance .addProduct() .then(() => { console.log("Successfully added product"); process.exit(0); }) .catch((e) => console.log(e)); // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unused-vars const download_image = (url: string, image_path: string) => axios .default({ url, responseType: "stream", }) .then( (response) => new Promise((resolve, reject) => { (response as any).data .pipe(fs.createWriteStream(image_path)) .on("finish", () => resolve({})) .on("error", (e: any) => reject(e)); }) ); // (async () => { // for (let i = 0; i < 10; i++) { // console.log(i); // await download_image(Faker.image.fashion(480, 480), Path.join(__dirname, "..", "..", "generate", i + ".png")); // } // })();
khoadaxne15/LastProject
src/components/formik/CustomMobileInput.tsx
import { useField } from "formik"; import React from "react"; import PhoneInput from "react-phone-input-2"; export const CustomMobileInput: React.FC<CustomMobileInputProps> = (props) => { // @ts-ignore const [field, meta, helpers] = useField(props); const { label, placeholder, defaultValue } = props; const { touched, error } = meta; const { setValue } = helpers; const handleChange = (value: string, data: { dialCode: number; countryCode: number; name: string }) => { const mob = { dialCode: data.dialCode, countryCode: data.countryCode, country: data.name, value, }; setValue(mob); }; return ( <div className="input-group"> {touched && error ? ( // @ts-ignore <span className="label-input label-error">{error?.value || error?.dialCode}</span> ) : ( <label className="label-input" htmlFor={field.name}> {label} </label> )} <PhoneInput // @ts-ignore name={field.name} country="ph" inputClass="input-form d-block" style={{ border: touched && error ? "1px solid red" : "1px solid #cacaca", }} inputExtraProps={{ required: true }} onChange={handleChange} placeholder={placeholder} value={defaultValue.value} /> </div> ); }; CustomMobileInput.defaultProps = { label: "Mobile Number", placeholder: "09254461351", }; type CustomMobileInputProps = { label?: string; placeholder?: string; defaultValue: { value: string }; name?: string; disabled?: boolean; };
khoadaxne15/LastProject
src/views/error/PageNotFound.tsx
import React from "react"; import { useScrollTop } from "../../hooks"; export const PageNotFound: React.FC<PageNotFoundProps> = ({ history }) => { useScrollTop(); return ( <div className="page-not-found"> <h1>:( Page you are looking for doesn&apos;t exists.</h1> <br /> <button className="button" onClick={history.goBack} type="button"> Go back </button> </div> ); }; type PageNotFoundProps = { history: { goBack: () => void; }; };
khoadaxne15/LastProject
src/components/common/Modal.tsx
import React from "react"; import AppModal from "react-modal"; export const Modal: React.FC<ModalProps> = ({ isOpen, onRequestClose, afterOpenModal, overrideStyle, children }) => { const defaultStyle: AppModal.Styles = { content: { top: "50%", left: "50%", right: "auto", bottom: "auto", position: "fixed", padding: "50px 20px", transition: "all .5s ease", zIndex: 9999, marginRight: "-50%", transform: "translate(-50%, -50%)", boxShadow: "0 5px 10px rgba(0, 0, 0, .1)", animation: "scale .3s ease", ...overrideStyle, }, }; AppModal.setAppElement("#app"); console.log({ isOpen }); return ( <AppModal closeTimeoutMS={300} contentLabel="Product Modal" isOpen={isOpen} onAfterOpen={afterOpenModal} onRequestClose={onRequestClose} shouldCloseOnOverlayClick style={defaultStyle}> {children} </AppModal> ); }; Modal.defaultProps = { overrideStyle: {}, afterOpenModal: () => {}, }; type ModalProps = { isOpen: boolean; onRequestClose: () => void; afterOpenModal?: () => void; overrideStyle?: React.CSSProperties; children: React.ReactNode[] | React.ReactNode; };
khoadaxne15/LastProject
src/views/checkout/step3/Total.tsx
import { ArrowLeftOutlined, CheckOutlined } from "@ant-design/icons"; import { useFormikContext } from "formik"; import React from "react"; import { useDispatch } from "react-redux"; import { useHistory } from "react-router-dom"; import { CHECKOUT_STEP_2 } from "../../../constants"; import { displayMoney } from "../../../helpers"; import { Payment, setPaymentDetails } from "../../../redux"; export const Total: React.FC<TotalProps> = ({ isInternational, subtotal }) => { const { values, submitForm } = useFormikContext<Payment>(); const history = useHistory(); const dispatch = useDispatch(); const onClickBack = () => { // destructure to only select left fields omitting cardnumber and ccv const { cardnumber, ccv, ...rest } = values; dispatch(setPaymentDetails({ ...rest })); // save payment details history.push(CHECKOUT_STEP_2); }; return ( <> <div className="basket-total text-right"> <p className="basket-total-title">Total:</p> <h2 className="basket-total-amount">{displayMoney(subtotal + (isInternational ? 50 : 0))}</h2> </div> <br /> <div className="checkout-shipping-action"> <button className="button button-muted" onClick={() => onClickBack()} type="button"> <ArrowLeftOutlined /> &nbsp; Go Back </button> <button className="button" disabled={false} onClick={submitForm} type="button"> <CheckOutlined /> &nbsp; Confirm </button> </div> </> ); }; type TotalProps = { isInternational: boolean; subtotal: number; };
khoadaxne15/LastProject
src/views/admin/components/ProductsTable.tsx
<gh_stars>0 import React from "react"; import { Product } from "../../../redux"; import { ProductItem } from "."; export const ProductsTable: React.FC<ProductsTableProps> = ({ filteredProducts }) => ( <div> {filteredProducts.length > 0 && ( <div className="grid grid-product grid-count-6"> <div className="grid-col" /> <div className="grid-col"> <h5>Name</h5> </div> <div className="grid-col"> <h5>Brand</h5> </div> <div className="grid-col"> <h5>Price</h5> </div> <div className="grid-col"> <h5>Date Added</h5> </div> <div className="grid-col"> <h5>Qty</h5> </div> </div> )} {filteredProducts.length === 0 ? new Array(10) .fill({}) .map((product, index) => <ProductItem key={`product-skeleton ${index}`} product={product} />) : filteredProducts.map((product) => <ProductItem key={product.id} product={product} />)} </div> ); type ProductsTableProps = { filteredProducts: Product[]; };
khoadaxne15/LastProject
src/hooks/useDocumentTitle.ts
import { useLayoutEffect } from "react"; export const useDocumentTitle = (title: string) => { useLayoutEffect(() => { if (title) { document.title = title; } else { document.title = "TK - eCommerce React App"; } }, [title]); };
khoadaxne15/LastProject
src/views/admin/components/index.ts
<reponame>khoadaxne15/LastProject export * from "./ProductForm"; export * from "./ProductItem"; export * from "./ProductsNavbar"; export * from "./ProductsTable";
khoadaxne15/LastProject
src/components/basket/index.ts
export { Basket } from "./Basket"; export { BasketItem } from "./BasketItem"; export { BasketItemControl } from "./BasketItemControl"; export { BasketToggle } from "./BasketToggle";
khoadaxne15/LastProject
src/index.tsx
import * as React from "react"; import { render } from "react-dom"; import WebFont from "webfontloader"; import { App } from "./App"; import { Preloader } from "./components"; import "normalize.css/normalize.css"; import "react-phone-input-2/lib/style.css"; import { createAppStore, onAuthStateChanged } from "./redux"; import "../styles/style.scss"; import firebase from "./services/firebase"; WebFont.load({ google: { families: ["Tajawal"], }, }); const { store, persistor } = createAppStore(); const root = document.getElementById("app"); // Render the preloader on initial load render(<Preloader />, root); firebase.auth.onAuthStateChanged((user) => { if (user) { store.dispatch(onAuthStateChanged.done({ result: user })); } else { store.dispatch(onAuthStateChanged.failed({ error: "Failed to authenticate" })); } // then render the app after checking the auth state render(<App store={store} persistor={persistor} />, root); }); if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) { window.addEventListener("load", () => { navigator.serviceWorker .register("/sw.js") .then((registration) => { console.log("SW registered: ", registration); }) .catch((registrationError) => { console.log("SW registration failed: ", registrationError); }); }); }
khoadaxne15/LastProject
src/views/error/NoInternetPage.tsx
<filename>src/views/error/NoInternetPage.tsx import React from "react"; import { useScrollTop } from "../../hooks"; export const NoInternet = () => { useScrollTop(); return ( <div className="page-not-found"> <h1>:( No Internet Connection.</h1> <p>Please check you network connectivity and try again.</p> <br /> <button className="button" onClick={() => window.location.reload()} type="button"> Try Again </button> </div> ); };
khoadaxne15/LastProject
src/redux/reducers/userReducer.ts
<filename>src/redux/reducers/userReducer.ts import { AnyAction } from "typescript-fsa"; import { addUser, deleteUser, editUser } from "../actions"; // const initState = [ // { // firstname: 'Gago', // lastname: 'Ka', // email: '<EMAIL>', // password: '<PASSWORD>', // avatar: '', // banner: '', // dateJoined: 0 // } // ]; export interface User { id: string; firstname: string; lastname: string; email: string; password: string; avatar: string; banner: string; dateJoined: number; } export type UserState = User[]; export function userReducer(state: UserState = [], action: AnyAction): UserState { if (state === undefined) { return []; } if (addUser.match(action)) { return [...state, action.payload]; } if (editUser.match(action)) { return state.map((user) => { if (user.id === action.payload.id) { return { ...user, ...action.payload, }; } return user; }); } if (deleteUser.match(action)) { return state.filter((user) => user.id !== action.payload); } return state; }
khoadaxne15/LastProject
src/components/basket/BasketToggle.tsx
<reponame>khoadaxne15/LastProject import * as React from "react"; export const BasketToggle = (params: { children: React.FC<{ onClickToggle: () => void }> }) => { const onClickToggle = () => { if (document.body.classList.contains("is-basket-open")) { document.body.classList.remove("is-basket-open"); } else { document.body.classList.add("is-basket-open"); } }; document.addEventListener("click", (e) => { const closest = (e.target as HTMLElement)?.closest?.(".basket"); const toggle = (e.target as HTMLElement)?.closest(".basket-toggle"); const closeToggle = (e.target as HTMLElement)?.closest(".basket-item-remove"); if (!closest && document.body.classList.contains("is-basket-open") && !toggle && !closeToggle) { document.body.classList.remove("is-basket-open"); } }); return params.children({ onClickToggle }); };
khoadaxne15/LastProject
src/views/checkout/step2/ShippingForm.tsx
import { Field, useFormikContext } from "formik"; import React from "react"; import { CustomInput, CustomMobileInput } from "../../../components"; export const ShippingForm: React.FC = () => { const { values } = useFormikContext(); return ( <div className="checkout-shipping-wrapper"> <div className="checkout-shipping-form"> <div className="checkout-fieldset"> <div className="d-block checkout-field"> <Field name="fullname" type="text" label="* Full Name" placeholder="Enter your full name" component={CustomInput} style={{ textTransform: "capitalize" }} /> </div> <div className="d-block checkout-field"> <Field name="email" type="email" label="* Email Address" placeholder="Enter your email address" component={CustomInput} /> </div> </div> <div className="checkout-fieldset"> <div className="d-block checkout-field"> <Field name="address" type="text" label="* Shipping Address" placeholder="Enter full shipping address" component={CustomInput} /> </div> <div className="d-block checkout-field"> {/* @ts-ignore */} <CustomMobileInput name="mobile" defaultValue={values.mobile} /> </div> </div> <div className="checkout-fieldset"> <Field name="isInternational"> {/* @ts-ignore */} {({ field, form, meta }) => ( <div className="checkout-field"> {meta.touched && meta.error ? ( <span className="label-input label-error">{meta.error}</span> ) : ( <label className="label-input" htmlFor={field.name}> Shipping Option </label> )} <div className="checkout-checkbox-field"> <input checked={field.value} id={field.name} onChange={(e) => { form.setValues({ ...form.values, [field.name]: e.target.checked }); }} value={meta.value} type="checkbox" /> <label className="d-flex w-100" htmlFor={field.name}> <h5 className="d-flex-grow-1 margin-0"> &nbsp; International Shipping &nbsp; <span className="text-subtle">7-14 days</span> </h5> <h4 className="margin-0">$50.00</h4> </label> </div> </div> )} </Field> </div> </div> </div> ); };
khoadaxne15/LastProject
src/views/checkout/components/StepTracker.tsx
import React from "react"; export const StepTracker: React.FC<StepTrackerProps> = ({ current }) => { const className = (step: number) => (current === step ? "is-active-step" : step < current ? "is-done-step" : ""); return ( <div className="checkout-header"> <ul className="checkout-header-menu"> <li className={`checkout-header-list ${className(1)}`}> <div className="checkout-header-item"> <div className="checkout-header-icon"> <h4 className="checkout-header-step">1</h4> </div> <h6 className="checkout-header-subtitle">Order Summary</h6> </div> </li> <li className={`checkout-header-list ${className(2)}`}> <div className="checkout-header-item"> <div className="checkout-header-icon"> <h4 className="checkout-header-step">2</h4> </div> <h6 className="checkout-header-subtitle">Shipping Details</h6> </div> </li> <li className={`checkout-header-list ${className(3)}`}> <div className="checkout-header-item"> <div className="checkout-header-icon"> <h4 className="checkout-header-step">3</h4> </div> <h6 className="checkout-header-subtitle">Payment</h6> </div> </li> </ul> </div> ); }; type StepTrackerProps = { current: number; };
khoadaxne15/LastProject
src/views/account/components/UserAccountTab.tsx
<reponame>khoadaxne15/LastProject import React from "react"; import { useSelector } from "react-redux"; import { RouteComponentProps, withRouter } from "react-router-dom"; import { ImageLoader } from "../../../components"; import { ACCOUNT_EDIT } from "../../../constants"; import { displayDate } from "../../../helpers"; import { AppState, ProfileState } from "../../../redux"; const _UserProfile: React.FC<UserProfileProps> = (props) => { const profile = useSelector<AppState, ProfileState>((state) => state.profile); return ( <div className="user-profile"> <div className="user-profile-block"> <div className="user-profile-banner"> <div className="user-profile-banner-wrapper"> <ImageLoader alt="Banner" className="user-profile-banner-img" src={profile.banner || ""} /> </div> <div className="user-profile-avatar-wrapper"> <ImageLoader alt="Avatar" className="user-profile-img" src={profile.avatar || ""} /> </div> <button className="button button-small user-profile-edit" onClick={() => props.history.push(ACCOUNT_EDIT)} type="button"> Edit Account </button> </div> <div className="user-profile-details"> <h2 className="user-profile-name">{profile.fullname}</h2> <span>Email</span> <br /> <h5>{profile.email}</h5> <span>Address</span> <br /> {profile.address ? <h5>{profile.address}</h5> : <h5 className="text-subtle text-italic">Address not set</h5>} <span>Mobile</span> <br /> {profile.mobile ? ( <h5>{profile.mobile.value}</h5> ) : ( <h5 className="text-subtle text-italic">Mobile not set</h5> )} <span>Date Joined</span> <br /> {profile.dateJoined ? ( <h5>{displayDate(profile.dateJoined)}</h5> ) : ( <h5 className="text-subtle text-italic">Not available</h5> )} </div> </div> </div> ); }; type UserProfileProps = RouteComponentProps & { history: { push: (path: string) => void; }; }; export const UserAccountTab = withRouter(_UserProfile);
khoadaxne15/LastProject
src/views/admin/components/ProductItem.tsx
import React, { useRef } from "react"; import Skeleton, { SkeletonTheme } from "react-loading-skeleton"; import { useDispatch } from "react-redux"; import { RouteComponentProps, useHistory, withRouter } from "react-router-dom"; import { ImageLoader } from "../../../components/common"; import { EDIT_PRODUCT } from "../../../constants"; import { displayActionMessage, displayDate, displayMoney } from "../../../helpers"; import { Product, removeProduct } from "../../../redux"; const _ProductItem: React.FC<ProductItemProps> = ({ product }) => { const dispatch = useDispatch(); const history = useHistory(); const productRef = useRef<HTMLDivElement | null>(null); const onClickEdit = () => { history.push(`${EDIT_PRODUCT}/${product.id}`); }; const onDeleteProduct = () => { productRef.current?.classList.toggle("item-active"); }; const onConfirmDelete = () => { dispatch(removeProduct.started(product.id)); displayActionMessage("Item successfully deleted"); productRef.current?.classList.remove("item-active"); }; const onCancelDelete = () => { productRef.current?.classList.remove("item-active"); }; return ( <SkeletonTheme color="#e1e1e1" highlightColor="#f2f2f2"> <div className={`item item-products ${!product.id && "item-loading"}`} ref={productRef}> <div className="grid grid-count-6"> <div className="grid-col item-img-wrapper"> {product.image ? ( <ImageLoader alt={product.name} className="item-img" src={product.image} /> ) : ( <Skeleton width={50} height={30} /> )} </div> <div className="grid-col"> <span className="text-overflow-ellipsis">{product.name || <Skeleton width={50} />}</span> </div> <div className="grid-col"> <span>{product.brand || <Skeleton width={50} />}</span> </div> <div className="grid-col"> <span>{product.price ? displayMoney(product.price) : <Skeleton width={30} />}</span> </div> <div className="grid-col"> <span>{product.dateAdded ? displayDate(product.dateAdded) : <Skeleton width={30} />}</span> </div> <div className="grid-col"> <span>{product.maxQuantity || <Skeleton width={20} />}</span> </div> </div> {product.id && ( <div className="item-action"> <button className="button button-border button-small" onClick={onClickEdit} type="button"> Edit </button> &nbsp; <button className="button button-border button-small button-danger" onClick={onDeleteProduct} type="button"> Delete </button> <div className="item-action-confirm"> <h5>Are you sure you want to delete this?</h5> <button className="button button-small button-border" onClick={onCancelDelete} type="button"> No </button> &nbsp; <button className="button button-small button-danger" onClick={onConfirmDelete} type="button"> Yes </button> </div> </div> )} </div> </SkeletonTheme> ); }; type ProductItemProps = RouteComponentProps & { product: Product; }; export const ProductItem = withRouter(_ProductItem);
khoadaxne15/LastProject
src/components/product/ProductSearch.tsx
import React, { useEffect, useRef } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useHistory } from "react-router-dom"; import { AppState, clearRecentSearch, FilterState, removeSelectedRecent, setTextFilter } from "../../redux"; import { Filters } from "../common"; export const ProductSearch = () => { const history = useHistory(); const { productsLength, filter } = useSelector<AppState, { filter: FilterState; productsLength: number }>( (state) => ({ filter: state.filter, products: state.products.items, isLoading: state.app.loading, productsLength: state.products.items.length, }) ); const dispatch = useDispatch(); const searchInput = useRef<HTMLInputElement | null>(null); let input = ""; useEffect(() => { searchInput.current?.focus(); }, []); const onSearchChange = (e: any) => { const val = e.target.value.trim(); input = val; if (val === "" && productsLength !== 0) { dispatch(setTextFilter(val)); history.push("/"); } }; const onKeyUp = (e: any) => { if (e.keyCode === 13 && productsLength !== 0) { dispatch(setTextFilter(input)); history.push("/"); } }; const onClearRecentSearch = () => { dispatch(clearRecentSearch({})); }; return ( <div className="product-search"> <div className="product-search-header"> <h3 onClick={history.goBack} role="presentation"> <i className="fa fa-chevron-left" /> </h3> <div className="product-search-wrapper"> <input className="product-search-input" onChange={onSearchChange} onKeyUp={onKeyUp} placeholder="Search for product..." ref={searchInput} type="text" /> <div className="searchbar-icon" /> </div> </div> <div className="product-search-body"> <div className="product-search-recent"> <div className="product-search-recent-header"> <h5>Recent Searches</h5> <h5 onClick={onClearRecentSearch} style={{ color: "red" }} role="presentation"> Clear </h5> </div> {filter.recent?.map((item, index) => ( <div className="pill-wrapper" key={`${item}${index}`}> <div className="pill padding-right-l"> <h5 className="pill-content margin-0" onClick={() => { dispatch(setTextFilter(item)); history.push("/"); }} role="presentation"> {item} </h5> <div className="pill-remove" onClick={() => dispatch(removeSelectedRecent(item))} role="presentation"> <h5 className="text-subtle margin-0"> <i className="fa fa-times-circle" /> </h5> </div> </div> </div> ))} {filter.recent?.length === 0 && <h5 className="text-subtle">No recent searches</h5>} </div> <div className="product-search-filter"> <h5 className="margin-0">Choose Filters</h5> </div> <div className="product-search-filter-sub"> <Filters closeModal={() => {}} /> </div> </div> </div> ); };
khoadaxne15/LastProject
src/components/product/ProductShowcaseGrid.tsx
import React from "react"; import { Product } from "../../redux"; import { ProductFeatured } from "./ProductFeatured"; export const ProductShowcase: React.FC<ProductShowcaseProps> = ({ products, skeletonCount }) => ( <div className="product-display-grid"> {products.length === 0 ? new Array(skeletonCount) .fill({}) .map((product, index) => <ProductFeatured key={`product-skeleton ${index}`} product={product} />) : products.map((product) => <ProductFeatured key={product.id} product={product} />)} </div> ); ProductShowcase.defaultProps = { skeletonCount: 4, }; type ProductShowcaseProps = { products: Product[]; skeletonCount?: number; };
khoadaxne15/LastProject
src/helpers/utils.ts
<filename>src/helpers/utils.ts export const displayDate = (timestamp: string) => { const date = new Date(timestamp); const monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; const day = date.getDate(); const monthIndex = date.getMonth(); const year = date.getFullYear(); // return day + ' ' + monthNames[monthIndex] + ' ' + year; return `${monthNames[monthIndex]} ${day}, ${year}`; }; export const displayMoney = (n: number) => { const format = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }); // or use toLocaleString() return format.format(n); }; export const calculateTotal = (arr: number[]) => { if (!arr || arr?.length === 0) { return 0; } const total = arr.reduce((acc, val) => acc + val, 0); return Math.round(total * 100) / 100; }; export const displayActionMessage = (msg: string, status = "info") => { const div = document.createElement("div"); const span = document.createElement("span"); div.className = `toast ${ status === "info" ? "toast-info" : status === "success" ? "toast-success" : "toast-error" // eslint-disable-next-line indent }`; span.className = "toast-msg"; span.textContent = msg; div.appendChild(span); const toast = document.querySelector(".toast"); if (toast) { document.body.removeChild(toast); document.body.appendChild(div); } else { document.body.appendChild(div); } setTimeout(() => { try { document.body.removeChild(div); } catch (e) { console.log(e); } }, 3000); };
khoadaxne15/LastProject
src/components/common/PriceRange/Handle.tsx
import React, { useState } from "react"; export const Handle: React.FC<HandleProps> = (props) => { const [mouseOver, setMouseOver] = useState(false); const { domain: [min, max], handle: { id, value, percent }, isActive, disabled, getHandleProps, } = props; return ( <> {(mouseOver || isActive) && !disabled ? ( <div style={{ left: `${percent}%`, position: "absolute", marginLeft: "-11px", marginTop: "-35px", }}> <div className="tooltip"> <span className="tooltiptext"> Value: {value} </span> </div> </div> ) : null} <div style={{ left: `${percent}%`, position: "absolute", transform: "translate(-50%, -50%)", WebkitTapHighlightColor: "rgba(0,0,0,0)", zIndex: 400, width: 26, height: 42, cursor: "pointer", // border: '1px solid grey', backgroundColor: "none", }} {...getHandleProps(id, { onMouseEnter: () => setMouseOver(() => true), onMouseLeave: () => setMouseOver(() => false), })} /> <div role="slider" aria-valuemin={min} aria-valuemax={max} aria-valuenow={value} style={{ left: `${percent}%`, position: "absolute", transform: "translate(-50%, -50%)", WebkitTapHighlightColor: "rgba(0,0,0,0)", zIndex: 300, width: 24, height: 24, border: 0, borderRadius: "50%", boxShadow: "1px 1px 1px 1px rgba(0, 0, 0, 0.2)", backgroundColor: disabled ? "#666" : "#1a1a1a", }} /> </> ); }; interface HandleProps { domain: number[]; handle: { id: string; value: number; percent: number; }; getHandleProps: MouseCallbacks; isActive: boolean; disabled?: boolean; } Handle.defaultProps = { disabled: false, }; type MouseCallbacks = (id: string, callbacks: { onMouseEnter: () => void; onMouseLeave: () => void }) => void;
khoadaxne15/LastProject
src/components/common/Preloader.tsx
<gh_stars>0 import React from "react"; import logoWordmark from "../../../static/MainLogo.png"; export const Preloader = () => ( <div className="preloader"> <svg className="logo-symbol" viewBox="0 0 41.25 41.25"> <circle cx="20.62" cy="20.62" r="20.62" /> <circle className="fill-white" cx="29.97" cy="14.93" r="6.58" /> </svg> <img alt="TK logo wordmark" src={logoWordmark} /> </div> );
khoadaxne15/LastProject
src/components/common/PriceRange/SliderRail.tsx
import React from "react"; const railOuterStyle: React.CSSProperties = { position: "absolute", transform: "translate(0%, -50%)", width: "100%", height: 42, borderRadius: 7, cursor: "pointer", // border: '1px solid grey', }; const railInnerStyle: React.CSSProperties = { position: "absolute", width: "100%", height: 14, transform: "translate(0%, -50%)", borderRadius: 7, pointerEvents: "none", backgroundColor: "#d0d0d0", }; export const SliderRail: React.FC<SliderRailProps> = ({ getRailProps }) => ( <div> <div style={railOuterStyle} {...getRailProps()} /> <div style={railInnerStyle} /> </div> ); type SliderRailProps = { getRailProps: () => void; };
khoadaxne15/LastProject
src/views/account/index.ts
export * from "./components"; export * from "./edit_account"; export * from "./user_account";
khoadaxne15/LastProject
src/components/index.ts
export * from "./basket"; export * from "./common"; export * from "./formik"; export * from "./product";
khoadaxne15/LastProject
src/components/common/Navigation.tsx
import { FilterOutlined, ShoppingOutlined } from "@ant-design/icons"; import React, { useEffect, useRef } from "react"; import { useSelector } from "react-redux"; import { Link, NavLink, useLocation } from "react-router-dom"; import logo from "../../../static/MainLogo.png"; import * as ROUTE from "../../constants/routes"; import { AppState, AuthState } from "../../redux"; import { UserAvatar } from "../../views/account/components/UserAvatar"; import { BasketToggle } from "../basket"; import { Badge } from "./Badge"; import { FiltersToggle } from "./FiltersToggle"; import { MobileNavigation } from "./MobileNavigation"; import { SearchBar } from "./SearchBar"; export const Navigation = () => { const navbar = useRef<HTMLElement | null>(null); const { pathname } = useLocation(); const store = useSelector< AppState, { basketLength: number; user: AuthState; isAuthenticating: boolean; isLoading: boolean } >((state) => ({ basketLength: state.basket.length, user: state.auth, isAuthenticating: state.app.isAuthenticating, isLoading: state.app.loading, })); const scrollHandler = () => { if (navbar.current && window.screen.width > 480) { if (window.pageYOffset >= 70) { navbar.current.classList.add("is-nav-scrolled"); } else { navbar.current.classList.remove("is-nav-scrolled"); } } }; useEffect(() => { window.addEventListener("scroll", scrollHandler); return () => window.removeEventListener("scroll", scrollHandler); }, []); const onClickLink = (e: React.MouseEvent) => { if (store.isAuthenticating) { e.preventDefault(); } }; // disable the basket toggle to these pathnames const basketDisabledpathnames = [ ROUTE.CHECKOUT_STEP_1, ROUTE.CHECKOUT_STEP_2, ROUTE.CHECKOUT_STEP_3, ROUTE.SIGNIN, ROUTE.SIGNUP, ROUTE.FORGOT_PASSWORD, ]; if (store.user && store.user.role === "ADMIN") { return null; } if (window.screen.width <= 800) { return <MobileNavigation {...store} disabledPaths={basketDisabledpathnames} />; } return ( <nav className="navigation" ref={navbar}> <div className="logo"> <Link onClick={onClickLink} to="/"> <img alt="Logo" src={logo} /> </Link> </div> <ul className="navigation-menu-main"> <li> <NavLink activeClassName="navigation-menu-active" exact to={ROUTE.HOME}> Home </NavLink> </li> <li> <NavLink activeClassName="navigation-menu-active" to={ROUTE.SHOP}> Shop </NavLink> </li> <li> <NavLink activeClassName="navigation-menu-active" to={ROUTE.FEATURED_PRODUCTS}> Featured </NavLink> </li> <li> <NavLink activeClassName="navigation-menu-active" to={ROUTE.RECOMMENDED_PRODUCTS}> Recommended </NavLink> </li> </ul> {(pathname === ROUTE.SHOP || pathname === ROUTE.SEARCH) && ( <FiltersToggle> <button className="button-muted button-small" type="button"> Filters &nbsp; <FilterOutlined /> </button> </FiltersToggle> )} <SearchBar /> <ul className="navigation-menu"> <li className="navigation-menu-item"> <BasketToggle> {({ onClickToggle }) => ( <button className="button-link navigation-menu-link basket-toggle" disabled={basketDisabledpathnames.includes(pathname)} onClick={onClickToggle} type="button"> <Badge count={store.basketLength}> <ShoppingOutlined style={{ fontSize: "2.4rem" }} /> </Badge> </button> )} </BasketToggle> </li> {store.user ? ( <li className="navigation-menu-item"> <UserAvatar /> </li> ) : ( <li className="navigation-action"> {pathname !== ROUTE.SIGNUP && ( <Link className="button button-small" onClick={onClickLink} to={ROUTE.SIGNUP}> Sign Up </Link> )} {pathname !== ROUTE.SIGNIN && ( <Link className="button button-small button-muted margin-left-s" onClick={onClickLink} to={ROUTE.SIGNIN}> Sign In </Link> )} </li> )} </ul> </nav> ); };
khoadaxne15/LastProject
src/views/auth/signup/index.tsx
import { ArrowRightOutlined, LoadingOutlined } from "@ant-design/icons"; import { Field, Form, Formik } from "formik"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import * as Yup from "yup"; import { SocialLogin } from "../../../components/common"; import { CustomInput } from "../../../components/formik"; import { SIGNIN } from "../../../constants"; import { useDocumentTitle, useScrollTop } from "../../../hooks"; import { signUp, setAuthenticating, setAuthStatus, AppState, MiscState } from "../../../redux"; const SignInSchema = Yup.object().shape({ email: Yup.string().email("Email is not valid.").required("Email is required."), password: Yup.string() .required("Password is required.") .min(8, "Password length should be at least 8 characters.") .matches(/[A-Z\W]/g, "Password should contain at least 1 uppercase letter."), fullname: Yup.string().required("Full name is required.").min(4, "Name should be at least 4 characters."), }); export type SignInSchemaForm = { email: string; password: string; fullname: string; }; export const SignUp: React.FC<SignUpProps> = ({ history }) => { const { isAuthenticating, authStatus } = useSelector< AppState, { isAuthenticating: boolean; authStatus: MiscState["authStatus"] } >((state) => ({ isAuthenticating: state.app.isAuthenticating, authStatus: state.app.authStatus, })); const dispatch = useDispatch(); useScrollTop(); useDocumentTitle("Sign Up | TK"); useEffect( () => () => { dispatch(setAuthStatus(null)); dispatch(setAuthenticating(false)); }, [dispatch] ); const onClickSignIn = () => history.push(SIGNIN); const onFormSubmit = (form: SignInSchemaForm) => { dispatch( signUp({ fullname: form.fullname.trim(), email: form.email.trim().toLowerCase(), password: form.password.trim(), }) ); }; return ( <div className="auth-content"> {authStatus?.success && ( <div className="loader"> <h3 className="toast-success auth-success"> {authStatus?.message} <LoadingOutlined /> </h3> </div> )} {!authStatus?.success && ( <> {authStatus?.message && <h5 className="text-center toast-error">{authStatus?.message}</h5>} <div className={`auth ${authStatus?.message && !authStatus?.success && "input-error"}`}> <div className="auth-main"> <h3>Sign up to TK</h3> <Formik initialValues={{ fullname: "", email: "", password: "", }} validateOnChange validationSchema={SignInSchema} onSubmit={onFormSubmit}> {() => ( <Form> <div className="auth-field"> <Field disabled={isAuthenticating} name="fullname" type="text" label="* Full Name" placeholder="<NAME>" style={{ textTransform: "capitalize" }} component={CustomInput} /> </div> <div className="auth-field"> <Field disabled={isAuthenticating} name="email" type="email" label="* Email" placeholder="<EMAIL>" component={CustomInput} /> </div> <div className="auth-field"> <Field disabled={isAuthenticating} name="password" type="password" label="* Password" placeholder="<PASSWORD>" component={CustomInput} /> </div> <br /> <div className="auth-field auth-action auth-action-signup"> <button className="button auth-button" disabled={isAuthenticating} type="submit"> {isAuthenticating ? "Signing Up" : "Sign Up"} &nbsp; {isAuthenticating ? <LoadingOutlined /> : <ArrowRightOutlined />} </button> </div> </Form> )} </Formik> </div> <div className="auth-divider"> <h6>OR</h6> </div> <SocialLogin isLoading={isAuthenticating} /> </div> <div className="auth-message"> <span className="auth-info"> <strong>Already have an account?</strong> </span> <button className="button button-small button-border button-border-gray" disabled={isAuthenticating} onClick={onClickSignIn} type="button"> Sign In </button> </div> </> )} </div> ); }; type SignUpProps = { history: { push: (path: string) => void; }; };
khoadaxne15/LastProject
src/views/auth/index.ts
<reponame>khoadaxne15/LastProject export * from "./forgot_password"; export * from "./signin"; export * from "./signup";
khoadaxne15/LastProject
src/redux/actions/profileActions.ts
<reponame>khoadaxne15/LastProject import actionCreatorFactory from "typescript-fsa"; import { Profile } from "../reducers"; const factory = actionCreatorFactory("PROFILE"); export const clearProfile = factory<ClearProfilePayload>("CLEAR_PROFILE"); export interface ClearProfilePayload {} export type SetProfilePayload = Profile; export const setProfile = factory<SetProfilePayload>("SET_PROFILE"); export const updateEmail = factory<UpdateEmailPayload>("UPDATE_EMAIL"); export interface UpdateEmailPayload { password: string; newEmail: string; } export const updateProfile = factory.async<UpdateProfilePayload, UpdateProfileSuccessPayload>("UPDATE_PROFILE"); export interface UpdateProfilePayload { updates: Partial<Profile>; files: ProfileFiles; credentials: Credentials; } export interface ProfileFiles { avatarFile?: File; bannerFile?: File; } export interface Credentials { email?: string; password?: <PASSWORD>; } export interface UpdateProfileSuccessPayload { updates: Partial<Profile>; }
khoadaxne15/LastProject
src/redux/reducers/index.ts
import { ReducersMapObject } from "redux"; import { AnyAction } from "typescript-fsa"; import { authReducer, AuthState } from "./authReducer"; import { basketReducer, BasketState } from "./basketReducer"; import { checkoutReducer, CheckoutState } from "./checkoutReducer"; import { filterReducer, FilterState } from "./filterReducer"; import { miscReducer, MiscState } from "./miscReducer"; import { productReducer, ProductState } from "./productReducer"; import { profileReducer, ProfileState } from "./profileReducer"; import { userReducer, UserState } from "./userReducer"; export interface AppState { auth: AuthState; basket: BasketState; checkout: CheckoutState; filter: FilterState; products: ProductState; profile: ProfileState; users: UserState; app: MiscState; } export const rootReducer: ReducersMapObject<AppState, AnyAction> = { products: productReducer, basket: basketReducer, auth: authReducer, profile: profileReducer, filter: filterReducer, users: userReducer, checkout: checkoutReducer, app: miscReducer, }; export * from "./authReducer"; export * from "./basketReducer"; export * from "./checkoutReducer"; export * from "./filterReducer"; export * from "./miscReducer"; export * from "./productReducer"; export * from "./profileReducer"; export * from "./userReducer";
khoadaxne15/LastProject
src/components/common/index.ts
<gh_stars>0 export { AdminNavigation } from "./AdminNavigation"; export { AdminSideBar } from "./AdminSidePanel"; export { Badge } from "./Badge"; export { Boundary } from "./Boundary"; export { ColorChooser } from "./ColorChooser"; export { Filters } from "./Filters"; export { FiltersToggle } from "./FiltersToggle"; export { Footer } from "./Footer"; export { ImageLoader } from "./ImageLoader"; export { MessageDisplay } from "./MessageDisplay"; export { MobileNavigation } from "./MobileNavigation"; export { Modal } from "./Modal"; export { Navigation } from "./Navigation"; export { Preloader } from "./Preloader"; export { PriceRange } from "./PriceRange"; export { SearchBar } from "./SearchBar"; export { SocialLogin } from "./SocialLogin";
khoadaxne15/LastProject
src/redux/sagas/productSaga.ts
<reponame>khoadaxne15/LastProject<gh_stars>0 import { SagaIterator } from "redux-saga"; import { all, call, put, select } from "redux-saga/effects"; import { AnyAction } from "typescript-fsa"; import { ADMIN_PRODUCTS } from "../../constants"; import { displayActionMessage } from "../../helpers"; import { history } from "../../routers/AppRouter"; import firebase from "../../services/firebase"; import { addProduct, clearSearchState, editProduct, EditProductPayload, getProducts, ImageFile, removeProduct, searchProduct, setLoading, setRequestStatus, } from "../actions"; import { Product } from "../reducers"; function* initRequest(): SagaIterator { yield put(setLoading(true)); yield put(setRequestStatus(undefined)); } export interface ProductError extends Error {} function* handleError(e: ProductError) { yield put(setLoading(false)); yield put(setRequestStatus({ message: e.message || "Failed to fetch products" })); console.log("ERROR: ", e); } function* handleAction(location: string | undefined, message: string, status: string) { if (location) { yield call(history.push, location); } yield call(displayActionMessage, message, status); } export function* productSaga(action: AnyAction): SagaIterator { if (getProducts.started.match(action)) { try { yield call(initRequest); const state = yield select(); const result: { items?: Product[]; lastKey: string; total: number } = yield call( firebase.getProducts, action.payload ); if (result.items?.length === 0) { handleError(new Error("No items found.")); } else { yield put( getProducts.done({ params: action.payload, result: { items: result.items ?? [], lastRefKey: result.lastKey ? result.lastKey : state.products.lastRefKey, total: result.total ? result.total : state.products.total, }, }) ); yield put(setRequestStatus({ message: "" })); } yield put(setLoading(false)); } catch (e) { console.log(e); yield call(handleError, e as ProductError); } return; } if (addProduct.started.match(action)) { try { yield call(initRequest); const { imageCollection } = action.payload; const key: string = yield call(firebase.generateKey); const downloadURL = yield call(firebase.storeImage, key, "products", action.payload.image); const image = { id: key, url: downloadURL }; let images: { id: string; url: string }[] = []; if (imageCollection.length !== 0 && imageCollection.every((e) => e.file)) { const imageKeys: string[] = yield all(imageCollection.map(() => call(firebase.generateKey))); const imageUrls: string[] = yield all( imageCollection.map((img, i) => call(firebase.storeImage, imageKeys[i], "products", img.file || "")) ); images = imageUrls.map((url, i) => ({ id: imageKeys[i], url })); } const product: Product = { ...action.payload, image: downloadURL, imageCollection: [image, ...images], }; yield call(firebase.addProduct, key, product); yield put( addProduct.done({ params: action.payload, result: { ...product, id: key, }, }) ); yield call(handleAction, ADMIN_PRODUCTS, "Item succesfully added", "success"); yield put(setLoading(false)); } catch (e) { yield call(handleError, e as ProductError); yield call(handleAction, undefined, `Item failed to add: ${(e as ProductError)?.message}`, "error"); } return; } if (editProduct.started.match(action)) { try { yield call(initRequest); const { image, imageCollection } = action.payload.updates; let newUpdates: EditProductPayload["updates"] = { ...action.payload.updates }; if (image?.constructor === File && typeof image === "object") { try { yield call(firebase.deleteImage, action.payload.id); } catch (e) { console.error("Failed to delete image ", e); } const url = yield call(firebase.storeImage, action.payload.id, "products", image); newUpdates = { ...newUpdates, image: url }; } if (imageCollection?.length && imageCollection.length > 1) { const existingUploads: ImageFile[] = []; const newUploads: { file: File }[] = []; imageCollection.forEach((img) => { const file = img.file; if (file) { newUploads.push({ file }); } else { existingUploads.push(img); } }); const imageKeys = yield all(newUploads.map(() => call(firebase.generateKey))); const imageUrls: string[] = yield all( newUploads.map((img, i) => call(firebase.storeImage, imageKeys[i](), "products", img.file)) ); const images = imageUrls.map((url, i) => ({ id: imageKeys[i](), url })); newUpdates = { ...newUpdates, imageCollection: [...existingUploads, ...images] }; } else if (newUpdates.image) { newUpdates = { ...newUpdates, imageCollection: [{ id: new Date().getTime().toString(), url: newUpdates.image }], }; // add image thumbnail to image collection from newUpdates to // make sure you're adding the url not the file object. } yield call(firebase.editProduct, action.payload.id, newUpdates); yield put( editProduct.done({ result: { id: action.payload.id, updates: newUpdates, }, params: action.payload, }) ); yield call(handleAction, ADMIN_PRODUCTS, "Item succesfully edited", "success"); yield put(setLoading(false)); } catch (e) { yield call(handleError, e as ProductError); yield call(handleAction, undefined, `Item failed to edit: ${(e as ProductError).message}`, "error"); } return; } if (removeProduct.started.match(action)) { try { yield call(initRequest); yield call(firebase.removeProduct, action.payload); yield put(removeProduct.done({ params: action.payload })); yield put(setLoading(false)); yield call(handleAction, ADMIN_PRODUCTS, "Item succesfully removed", "success"); } catch (e) { yield call(handleError, e as ProductError); yield call(handleAction, undefined, `Item failed to remove: ${(e as ProductError).message}`, "error"); } return; } if (searchProduct.started.match(action)) { try { yield call(initRequest); // clear search data yield put(clearSearchState()); const state = yield select(); const result: { products: Product[]; lastKey?: string; total?: number } = yield call( firebase.searchProducts, action.payload.searchKey ); if (result.products.length === 0) { yield call(handleError, new Error("No product found.")); yield put(clearSearchState()); } else { yield put( searchProduct.done({ result: { items: result.products, lastRefKey: result.lastKey ?? state.products.searchedProducts.lastRefKey, total: result.total ?? state.products.searchedProducts.total, }, params: action.payload, }) ); yield put(setRequestStatus({ message: "" })); } yield put(setLoading(false)); } catch (e) { yield call(handleError, e as ProductError); } return; } throw new Error(`Unexpected action type ${action.type}`); }
khoadaxne15/LastProject
src/views/checkout/step3/CreditPayment.tsx
import { Field, useFormikContext } from "formik"; import React, { useCallback, useEffect, useRef } from "react"; import { CustomInput } from "../../../components"; import { Payment } from "../../../redux"; export const CreditPayment: React.FC = () => { const { values, setValues } = useFormikContext<Payment>(); const collapseContainerRef = useRef<HTMLDivElement | null>(null); const cardInputRef = useRef<HTMLElement | null>(null); const containerRef = useRef<HTMLDivElement | null>(null); const checkboxContainerRef = useRef<HTMLDivElement | null>(null); const toggleCollapse = useCallback(() => { const cn = containerRef.current; const cb = checkboxContainerRef.current; const cl = collapseContainerRef.current; if (cb && cn && cl) { if (values.type === "credit") { cardInputRef.current?.focus(); cn.style.height = `${cb.offsetHeight + cl.offsetHeight}px`; } else { cardInputRef.current?.blur(); cn.style.height = `${cb.offsetHeight}px`; } } }, [values.type]); useEffect(() => { toggleCollapse(); }, [toggleCollapse, values.type]); const onCreditModeChange = (e: any) => { if (e.target.checked) { setValues({ ...values, type: "credit" }); toggleCollapse(); } }; const handleOnlyNumberInput = (e: any) => { const { key } = e.nativeEvent; if (/\D/.test(key) && key !== "Backspace") { e.preventDefault(); } }; return ( <> <h3 className="text-center">Payment</h3> <br /> <span className="d-block padding-s">Payment Option</span> <div ref={containerRef} className={`checkout-fieldset-collapse ${values.type === "credit" ? "is-selected-payment" : ""}`}> {/* ---- CHECKBOX TOGGLER ------ */} <div className="checkout-field margin-0"> <div className="checkout-checkbox-field" ref={checkboxContainerRef}> <input checked={values.type === "credit"} id="modeCredit" name="type" // the field name in formik I used is type onChange={onCreditModeChange} type="radio" /> <label className="d-flex w-100" htmlFor="modeCredit"> <div className="d-flex-grow-1 margin-left-s"> <h4 className="margin-0">Credit Card</h4> <span className="text-subtle d-block margin-top-s"> Pay with Visa, Master Card and other debit or credit card </span> </div> <div className="d-flex"> <div className="payment-img payment-img-visa" /> &nbsp; <div className="payment-img payment-img-mastercard" /> </div> </label> </div> </div> <div className="checkout-collapse-sub" ref={collapseContainerRef}> <span className="d-block padding-s text-center">Accepted Cards</span> <div className="checkout-cards-accepted d-flex-center"> <div className="payment-img payment-img-visa" title="Visa" /> <div className="payment-img payment-img-express" title="American Express" /> <div className="payment-img payment-img-mastercard" title="Master Card" /> <div className="payment-img payment-img-maestro" title="Maestro" /> <div className="payment-img payment-img-discover" title="Discover" /> </div> <br /> <div className="checkout-field margin-0"> <div className="checkout-fieldset"> <div className="checkout-field"> <Field name="name" type="text" label="* Name on Card" placeholder="<NAME>" component={CustomInput} style={{ textTransform: "capitalize" }} inputRef={cardInputRef} /> </div> <div className="checkout-field"> <Field name="cardnumber" type="text" maxLength={19} onKeyDown={handleOnlyNumberInput} label="* Card Number" placeholder="Enter your card number" component={CustomInput} /> </div> </div> <div className="checkout-fieldset"> <div className="checkout-field"> <Field name="expiry" type="date" label="* Expiry Date" placeholder="Enter your expiry date" component={CustomInput} /> </div> <div className="checkout-field"> <Field name="ccv" type="text" maxLength={4} onKeyDown={handleOnlyNumberInput} label="* CCV" placeholder="****" component={CustomInput} /> </div> </div> </div> </div> </div> </> ); };
khoadaxne15/LastProject
src/components/common/MessageDisplay.tsx
<filename>src/components/common/MessageDisplay.tsx<gh_stars>0 import React from "react"; export const MessageDisplay: React.FC<MessageDisplayProps> = ({ message, description, buttonLabel, action }) => ( <div className="loader"> <h2 className="text-center" style={{ wordBreak: "break-all" }}> {message || "Message"} </h2> {description && <span>{description}</span>} <br /> {action && ( <button className="button button-small" onClick={action} type="button"> {buttonLabel || "Okay"} </button> )} </div> ); MessageDisplay.defaultProps = { description: undefined, buttonLabel: "Okay", action: undefined, }; type MessageDisplayProps = { message: string; description?: string; buttonLabel?: string; action?: () => void; };
khoadaxne15/LastProject
src/views/admin/dashboard/index.tsx
import React from "react"; import { useDocumentTitle, useScrollTop } from "../../../hooks"; export const Dashboard: React.FC = () => { useDocumentTitle("Welcome | Admin Dashboard"); useScrollTop(); return ( <div className="loader"> <h2>Welcome to admin dashboard</h2> </div> ); };
khoadaxne15/LastProject
src/redux/sagas/authSaga.ts
import { SagaIterator } from "redux-saga"; import { call, put } from "redux-saga/effects"; import { AnyAction } from "typescript-fsa"; import defaultAvatar from "../../../static/defaultAvatar.jpg"; import defaultBanner from "../../../static/defaultBanner.jpg"; import { SIGNIN } from "../../constants"; import { history } from "../../routers/AppRouter"; import firebase from "../../services/firebase"; import { onAuthStateChanged, resetPassword, setAuthPersistence, signIn, signInWithFacebook, signInWithGithub, signInWithGoogle, signOut, signUp, resetCheckout, resetFilter, setAuthenticating, setAuthStatus, SetAuthStatusPayload, clearProfile, setProfile, clearBasket, setBasketItems, } from "../actions"; type AuthError = { code: string; message?: string; }; function* handleError(e: AuthError) { const obj: Omit<NonNullable<SetAuthStatusPayload>, "message"> = { success: false, type: "auth", isError: true }; yield put(setAuthenticating(false)); switch (e.code) { case "auth/network-request-failed": yield put(setAuthStatus({ ...obj, message: "Network error has occurred. Please try again." })); break; case "auth/email-already-in-use": yield put(setAuthStatus({ ...obj, message: "Email is already in use. Please use another email" })); break; case "auth/wrong-password": yield put(setAuthStatus({ ...obj, message: "Incorrect email or password" })); break; case "auth/user-not-found": yield put(setAuthStatus({ ...obj, message: "Incorrect email or password" })); break; case "auth/reset-password-error": yield put( setAuthStatus({ ...obj, message: "Failed to send password reset email. Did you type your email correctly?" }) ); break; default: yield put(setAuthStatus({ ...obj, message: e.message || "Unknown message" })); break; } } function* initRequest() { yield put(setAuthenticating(true)); yield put(setAuthStatus(null)); } export function* authSaga(action: AnyAction): SagaIterator { if (signIn.started.match(action)) { try { yield call(initRequest); yield call(firebase.signIn, action.payload.email, action.payload.password); } catch (e: unknown) { yield call(handleError, e as AuthError); } return; } if (signInWithGoogle.match(action)) { try { yield call(initRequest); yield call(firebase.signInWithGoogle); } catch (e) { yield call(handleError, e as AuthError); } return; } if (signInWithFacebook.match(action)) { try { yield call(initRequest); yield call(firebase.signInWithFacebook); } catch (e) { yield call(handleError, e as AuthError); } return; } if (signInWithGithub.match(action)) { try { yield call(initRequest); yield call(firebase.signInWithGithub); } catch (e) { yield call(handleError, e as AuthError); } return; } if (signUp.match(action)) { try { yield call(initRequest); const ref = yield call(firebase.createAccount, action.payload.email, action.payload.password); const fullname = action.payload.fullname .split(" ") .map((name) => name[0].toUpperCase().concat(name.substring(1))) .join(" "); const user = { fullname, avatar: defaultAvatar, banner: defaultBanner, email: action.payload.email, address: "", basket: [], mobile: {}, role: "USER", dateJoined: ref.user.metadata.creationTime || new Date().getTime(), }; yield call(firebase.addUser, ref.user.uid, user); yield put(setProfile(user)); yield put(setAuthenticating(false)); } catch (e) { yield call(handleError, e as AuthError); } return; } if (signOut.started.match(action)) { try { yield call(initRequest); yield call(firebase.signOut); yield put(clearBasket({})); yield put(clearProfile({})); yield put(resetFilter({})); yield put(resetCheckout({})); yield put(signOut.done({ params: {}, result: {} })); yield put(setAuthenticating(false)); yield call(history.push, SIGNIN); } catch (e) { console.log(e); } return; } if (resetPassword.match(action)) { try { yield call(initRequest); yield call(firebase.passwordReset, action.payload); yield put( setAuthStatus({ success: true, isError: false, type: "reset", message: "Password reset email has been sent to your provided email.", }) ); yield put(setAuthenticating(false)); } catch (e) { yield call(handleError, { code: "auth/reset-password-error" }); } return; } if (onAuthStateChanged.done.match(action)) { const snapshot = yield call(firebase.getUser, action.payload.result.uid); if (snapshot.data()) { // if user exists in database const user = snapshot.data(); yield put(setProfile(user)); yield put(setBasketItems(user.basket)); yield put( signIn.done({ params: user, result: { id: action.payload.result.uid, role: user.role, provider: action.payload.result.providerData[0]?.providerId, }, }) ); } else if (action.payload.result.providerData[0]?.providerId !== "password" && !snapshot.data()) { // add the user if auth provider is not password const user = { fullname: action.payload.result.displayName ?? "User", avatar: action.payload.result.photoURL ?? defaultAvatar, banner: defaultBanner, email: action.payload.result.email, address: "", basket: [], mobile: undefined, role: "USER", dateJoined: action.payload.result.metadata.creationTime, }; yield call(firebase.addUser, action.payload.result.uid, user); yield put(setProfile(user)); yield put( signIn.done( // @ts-ignore { result: { id: action.payload.result.uid, role: user.role, provider: action.payload.result.providerData[0]?.providerId, }, } ) ); } yield put( setAuthStatus({ success: true, type: "auth", isError: false, message: "Successfully signed in. Redirecting...", }) ); yield put(setAuthenticating(false)); return; } if (onAuthStateChanged.failed.match(action)) { yield put(clearProfile({})); yield put(signOut.done({ params: {}, result: {} })); return; } if (setAuthPersistence.match(action)) { try { yield call(firebase.setAuthPersistence); } catch (e) { console.log(e); } return; } throw new Error("AuthSaga.ts/Unexpected Action Type."); }
khoadaxne15/LastProject
src/views/account/edit_account/index.tsx
import { EditOutlined, LoadingOutlined } from "@ant-design/icons"; import { Formik } from "formik"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import * as Yup from "yup"; import { Boundary, ImageLoader } from "../../../components"; import { useDocumentTitle, useFileHandler, useModal, useScrollTop } from "../../../hooks"; import { AppState, AuthState, Credentials, Mobile, ProfileState, setLoading, updateProfile } from "../../../redux"; import { ConfirmModal } from "./ConfirmModal"; import { EditForm } from "./EditForm"; const FormSchema = Yup.object().shape({ fullname: Yup.string() .min(4, "Full name should be at least 4 characters.") .max(60, "Full name should be only be 4 characters long.") .required("Full name is required"), email: Yup.string().email("Email is not valid.").required("Email is required."), address: Yup.string(), mobile: Yup.object().shape({ country: Yup.string(), countryCode: Yup.string(), dialCode: Yup.string(), value: Yup.string(), }), }); export type EditAccountForm = { fullname: string; email: string; address?: string; mobile?: Mobile; }; export const EditAccount: React.FC = () => { useDocumentTitle("Edit Account | TK"); useScrollTop(); const modal = useModal(); const dispatch = useDispatch(); useEffect( () => () => { dispatch(setLoading(false)); }, [dispatch] ); const { profile, auth, isLoading } = useSelector< AppState, { profile: ProfileState; auth: AuthState; isLoading: boolean } >((state) => ({ profile: state.profile, auth: state.auth, isLoading: state.app.loading, })); const initFormikValues: EditAccountForm = { fullname: profile.fullname || "", email: profile.email || "", address: profile.address || "", mobile: profile.mobile, }; const { imageFile, isFileLoading, onFileChange } = useFileHandler({ avatar: [], banner: [] }); const update = (form: EditAccountForm, credentials: Credentials = {}) => { dispatch( updateProfile.started({ updates: { fullname: form.fullname, email: form.email, address: form.address, mobile: form.mobile, avatar: profile.avatar, banner: profile.banner, }, files: { bannerFile: imageFile.banner?.[0]?.file, avatarFile: imageFile.avatar?.[0]?.file, }, credentials, }) ); }; const onConfirmUpdate = (form: EditAccountForm, password: string | undefined) => { if (password) { update(form, { email: form.email, password }); } }; const onSubmitUpdate = (form: EditAccountForm) => { // check if data has changed // @ts-ignore const fieldsChanged = Object.keys(form).some((key) => profile[key] !== form[key]); if (fieldsChanged || Boolean(imageFile.banner?.[0]?.file || imageFile.avatar?.[0]?.file)) { if (form.email !== profile.email) { modal.onOpenModal(); } else { update(form); } } }; return ( <Boundary> <div className="edit-user"> <h3 className="text-center">Edit Account Details</h3> <Formik initialValues={initFormikValues} validateOnChange validationSchema={FormSchema} onSubmit={onSubmitUpdate}> {() => ( <> <div className="user-profile-banner"> <div className="user-profile-banner-wrapper"> <ImageLoader alt="Banner" className="user-profile-banner-img" src={imageFile.banner?.[0]?.url || profile.banner || ""} /> {isFileLoading ? ( <div className="loading-wrapper"> <LoadingOutlined /> </div> ) : ( <label className="edit-button edit-banner-button" htmlFor="edit-banner"> <input accept="image/x-png,image/jpeg" disabled={isLoading} hidden id="edit-banner" onChange={(e) => onFileChange(e, { name: "banner", type: "single" })} type="file" /> <EditOutlined /> </label> )} </div> <div className="user-profile-avatar-wrapper"> <ImageLoader alt="Avatar" className="user-profile-img" src={imageFile.avatar?.[0]?.url || profile.avatar || ""} /> {isFileLoading ? ( <div className="loading-wrapper"> <LoadingOutlined /> </div> ) : ( <label className="edit-button edit-avatar-button" htmlFor="edit-avatar"> <input accept="image/x-png,image/jpeg" disabled={isLoading} hidden id="edit-avatar" onChange={(e) => onFileChange(e, { name: "avatar", type: "single" })} type="file" /> <EditOutlined /> </label> )} </div> </div> <EditForm authProvider={auth?.provider ?? "unknown"} isLoading={isLoading} /> <ConfirmModal onConfirmUpdate={onConfirmUpdate} modal={modal} /> </> )} </Formik> </div> </Boundary> ); };
khoadaxne15/LastProject
src/views/account/components/UserTab.tsx
<reponame>khoadaxne15/LastProject import React, { useState } from "react"; export const UserTab: React.FC<UserTabProps> = (props) => { const { children } = props; const [activeTab, setActiveTab] = useState(0); const onClickTabItem = (index: number) => setActiveTab(index); return ( <div className="user-tab"> <div className="user-tab-nav"> <ul className="user-tab-menu"> {children.map((child, index) => ( <li key={index} className={`user-tab-item ${index === activeTab ? "user-tab-active" : ""}`} role="presentation" onClick={() => onClickTabItem(index)}> {child.props.label} </li> ))} </ul> </div> <div className="user-tab-content"> {children.map((child, index) => { if (index !== activeTab) { return null; } return child.props.children; })} </div> </div> ); }; type UserTabProps = { children: any[]; };
khoadaxne15/LastProject
src/components/common/Footer.tsx
<gh_stars>0 import React from "react"; import { useLocation } from "react-router-dom"; import logo from "../../../static/MainLogo.png"; import * as Route from "../../constants"; export const Footer = () => { const { pathname } = useLocation(); const visibleOnlyPath = [Route.HOME, Route.SHOP, Route.RECOMMENDED_PRODUCTS, Route.FEATURED_PRODUCTS]; return !visibleOnlyPath.includes(pathname) ? null : ( <footer className="footer"> <div className="footer-col-1"> <strong> <span> Developed by <a href="https://github.com/khoadaxne15"><NAME></a> </span> </strong> </div> <div className="footer-col-2"> <img alt="Footer logo" className="footer-logo" src={logo} /> <h5> &copy;&nbsp; {new Date().getFullYear()} </h5> </div> <div className="footer-col-3"> <strong> <span> Fork this project &nbsp; <a href="https://github.com/jgudo/ecommerce-react">HERE</a> </span> </strong> </div> </footer> ); };
khoadaxne15/LastProject
src/views/error/Error.tsx
<gh_stars>0 import React from "react"; import { useScrollTop } from "../../hooks"; export const Error: React.FC<ErrorProps> = ({ history }) => { useScrollTop(); return ( <div className="page-not-found"> <h1>:( An error has occured. Please try again.</h1> <br /> <button className="button" onClick={() => history.push("/")} type="button"> Try Again </button> </div> ); }; type ErrorProps = { history: { push: (path: string) => void; }; };
khoadaxne15/LastProject
src/views/checkout/step3/PayPalPayment.tsx
<gh_stars>0 import { useFormikContext } from "formik"; import React from "react"; import { Payment } from "../../../redux"; export const PayPalPayment: React.FC = () => { const { values, setValues } = useFormikContext<Payment>(); return ( <div className={`checkout-fieldset-collapse ${values.type === "paypal" ? "is-selected-payment" : ""}`}> <div className="checkout-field margin-0"> <div className="checkout-checkbox-field"> <input checked={values.type === "paypal"} id="modePayPal" name="type" onChange={(e) => { if (e.target.checked) { setValues({ ...values, type: "paypal" }); } }} type="radio" /> <label className="d-flex w-100" htmlFor="modePayPal"> <div className="d-flex-grow-1 margin-left-s"> <h4 className="margin-0">PayPal</h4> <span className="text-subtle d-block margin-top-s">Pay easily, fast and secure with PayPal.</span> </div> <div className="payment-img payment-img-paypal" /> </label> </div> </div> </div> ); };
khoadaxne15/LastProject
src/routers/AdminRoute.tsx
<reponame>khoadaxne15/LastProject import React from "react"; import { connect } from "react-redux"; import { Redirect, Route, Router, Switch } from "react-router-dom"; import { Footer, Navigation, Basket } from "../components"; import { AdminNavigation, AdminSideBar } from "../components"; import { AppState } from "../redux"; import * as ROUTES from "../constants/routes"; import { ClientRoute } from "./ClientRoute"; import { PublicRoute } from "./PublicRoute"; import { createBrowserHistory } from "history"; import { CheckOutStep1, CheckOutStep2, CheckOutStep3, EditAccount, AddProduct, Dashboard, EditProduct, FeaturedProducts, ForgotPassword, Home, PageNotFound, Products, RecommendedProducts, Search, Shop, SignIn, SignUp, UserAccount, ViewProduct, } from "../views"; const _AdminRoute: React.FC<AdminRouteProps> = ({ isAuth, role, component: Component, ...rest }) => ( <Route {...rest} component={(props: JSX.IntrinsicAttributes) => isAuth && role === "ADMIN" ? ( <> <AdminNavigation /> <main className="content-admin"> <AdminSideBar /> <div className="content-admin-wrapper"> <Component {...props} /> </div> </main> </> ) : ( <Redirect to="/" /> ) } /> ); const mapStateToProps = ({ auth }: AppState) => ({ isAuth: !!auth, role: auth?.role || "", }); _AdminRoute.defaultProps = { isAuth: false, role: "USER", }; type AdminRouteProps = { isAuth: boolean; role: string; component: any; exact?: boolean; path: string; }; export const history = createBrowserHistory(); export const AppRouter: React.FC = () => ( <Router history={history}> <> <Navigation /> <Basket /> <Switch> <Route component={Search} exact path={ROUTES.SEARCH} /> <Route component={Home} exact path={ROUTES.HOME} /> <Route component={Shop} exact path={ROUTES.SHOP} /> <Route component={FeaturedProducts} exact path={ROUTES.FEATURED_PRODUCTS} /> <Route component={RecommendedProducts} exact path={ROUTES.RECOMMENDED_PRODUCTS} /> <PublicRoute component={SignUp} path={ROUTES.SIGNUP} /> <PublicRoute component={SignIn} exact path={ROUTES.SIGNIN} /> <PublicRoute component={ForgotPassword} path={ROUTES.FORGOT_PASSWORD} /> <Route component={ViewProduct} path={ROUTES.VIEW_PRODUCT} /> <ClientRoute component={UserAccount} exact path={ROUTES.ACCOUNT} /> <ClientRoute component={EditAccount} exact path={ROUTES.ACCOUNT_EDIT} /> <ClientRoute component={CheckOutStep1} path={ROUTES.CHECKOUT_STEP_1} /> <ClientRoute component={CheckOutStep2} path={ROUTES.CHECKOUT_STEP_2} /> <ClientRoute component={CheckOutStep3} path={ROUTES.CHECKOUT_STEP_3} /> <AdminRoute component={Dashboard} exact path={ROUTES.ADMIN_DASHBOARD} /> <AdminRoute component={Products} path={ROUTES.ADMIN_PRODUCTS} /> <AdminRoute component={AddProduct} path={ROUTES.ADD_PRODUCT} /> <AdminRoute component={EditProduct} path={`${ROUTES.EDIT_PRODUCT}/:id`} /> <PublicRoute component={PageNotFound} /> </Switch> <Footer /> </> </Router> ); export const AdminRoute = connect(mapStateToProps)(_AdminRoute);
khoadaxne15/LastProject
src/views/featured/index.tsx
import React from "react"; import bannerImg from "../../../static/h3.jpg"; import { MessageDisplay, ProductShowcase } from "../../components"; import { useDocumentTitle, useFeaturedProducts, useScrollTop } from "../../hooks"; export const FeaturedProducts = () => { useDocumentTitle("Featured Products | TK"); useScrollTop(); const { featuredProducts, fetchFeaturedProducts, isLoading, error } = useFeaturedProducts(12); return ( <main className="content"> <div className="featured"> <div className="banner"> <div className="banner-desc"> <h1>Featured Products</h1> </div> <div className="banner-img"> <img src={bannerImg} alt="" /> </div> </div> <div className="display"> <div className="product-display-grid"> {error && !isLoading ? ( <MessageDisplay message={error} action={fetchFeaturedProducts} buttonLabel="Try Again" /> ) : ( <ProductShowcase products={featuredProducts} skeletonCount={6} /> )} </div> </div> </div> </main> ); };
khoadaxne15/LastProject
src/redux/sagas/profileSaga.ts
import { SagaIterator } from "redux-saga"; import { call, put, select } from "redux-saga/effects"; import { AnyAction } from "typescript-fsa"; import { ACCOUNT } from "../../constants"; import { displayActionMessage } from "../../helpers"; import { history } from "../../routers/AppRouter"; import firebase from "../../services/firebase"; import { updateEmail, updateProfile, setLoading } from "../actions"; import { Profile } from "../reducers"; interface ProfileError extends Error { code: string; } export function* profileSaga(action: AnyAction): SagaIterator { if (updateEmail.match(action)) { try { yield put(setLoading(false)); yield call(firebase.updateEmail, action.payload.password, action.payload.newEmail); yield put(setLoading(false)); yield call(history.push, "/profile"); yield call(displayActionMessage, "Email Updated Successfully!", "success"); } catch (e) { console.log((e as ProfileError).message); } return; } if (updateProfile.started.match(action)) { try { const state = yield select(); const { email, password } = action.payload.credentials; const { avatarFile, bannerFile } = action.payload.files; yield put(setLoading(true)); // if email & password exist && the email has been edited // update the email if (email && password && email !== state.profile.email) { yield call(firebase.updateEmail, password, email); } if (avatarFile || bannerFile) { const bannerURL = bannerFile ? yield call(firebase.storeImage, state.auth.id, "banner", bannerFile) : action.payload.updates.banner; const avatarURL = avatarFile ? yield call(firebase.storeImage, state.auth.id, "avatar", avatarFile) : action.payload.updates.avatar; const updates: Profile = { ...action.payload.updates, avatar: avatarURL, banner: bannerURL }; yield call(firebase.updateProfile, state.auth.id, updates); yield put(updateProfile.done({ params: action.payload, result: { updates } })); } else { yield call(firebase.updateProfile, state.auth.id, action.payload.updates); yield put(updateProfile.done({ params: action.payload, result: { updates: action.payload.updates } })); } yield put(setLoading(false)); yield call(history.push, ACCOUNT); yield call(displayActionMessage, "Profile Updated Successfully!", "success"); } catch (e) { console.log(e); yield put(setLoading(false)); if ((e as ProfileError).code === "auth/wrong-password") { yield call(displayActionMessage, "Wrong password, profile update failed :(", "error"); } else { yield call(displayActionMessage, `:( Failed to update profile. ${(e as ProfileError).message ?? ""}`, "error"); } } return; } throw new Error("Unexpected action type."); }
khoadaxne15/LastProject
src/components/common/SocialLogin.tsx
<reponame>khoadaxne15/LastProject<filename>src/components/common/SocialLogin.tsx import { FacebookOutlined, GithubFilled, GoogleOutlined } from "@ant-design/icons"; import React from "react"; import { useDispatch } from "react-redux"; import { signInWithFacebook, signInWithGithub, signInWithGoogle } from "../../redux"; export const SocialLogin: React.FC<SocialLoginProps> = ({ isLoading }) => { const dispatch = useDispatch(); const onSignInWithGoogle = () => { dispatch(signInWithGoogle({})); }; const onSignInWithFacebook = () => { dispatch(signInWithFacebook({})); }; const onSignInWithGithub = () => { dispatch(signInWithGithub({})); }; return ( <div className="auth-provider"> <button className="button auth-provider-button provider-facebook" disabled={isLoading} onClick={onSignInWithFacebook} type="button"> {/* <i className="fab fa-facebook" /> */} <FacebookOutlined /> Continue with Facebook </button> <button className="button auth-provider-button provider-google" disabled={isLoading} onClick={onSignInWithGoogle} type="button"> <GoogleOutlined /> Continue with Google </button> <button className="button auth-provider-button provider-github" disabled={isLoading} onClick={onSignInWithGithub} type="button"> <GithubFilled /> Continue with GitHub </button> </div> ); }; type SocialLoginProps = { isLoading: boolean; };
khoadaxne15/LastProject
src/components/formik/CustomCreatableSelect.tsx
<reponame>khoadaxne15/LastProject<filename>src/components/formik/CustomCreatableSelect.tsx import { useField } from "formik"; import React from "react"; import CreatableSelect from "react-select/creatable"; export const CustomCreatableSelect: React.FC<CustomCreatableSelectProps> = (props) => { // @ts-ignore const [field, meta, helpers] = useField(props); const { options, defaultValue, label, placeholder, isMulti, type, iid } = props; const { touched, error } = meta; const { setValue } = helpers; const handleChange = (newValue: { value: string }) => { if (Array.isArray(newValue)) { const arr = newValue.map((fieldKey) => fieldKey.value); setValue(arr); } else { setValue(newValue?.value); } }; const handleKeyDown = (e: any) => { if (type === "number") { const { key } = e.nativeEvent; if (/\D/.test(key) && key !== "Backspace") { e.preventDefault(); } } }; return ( <div className="input-group"> {touched && error ? ( <span className="label-input label-error">{error}</span> ) : ( <label className="label-input" htmlFor={field.name}> {label} </label> )} <CreatableSelect isMulti={isMulti} placeholder={placeholder} name={field.name} // @ts-ignore onChange={handleChange} onKeyDown={handleKeyDown} defaultValue={defaultValue} options={options} instanceId={iid} styles={{ menu: (provided) => ({ ...provided, zIndex: 10, }), container: (provided) => ({ ...provided, marginBottom: "1.2rem", }), control: (provided) => ({ ...provided, border: touched && error ? "1px solid red" : "1px solid #cacaca", }), }} /> </div> ); }; CustomCreatableSelect.defaultProps = { isMulti: false, placeholder: "", iid: "", options: [], type: "string", }; type CustomCreatableSelectProps = { options: object[]; defaultValue: object | object[]; label: string; placeholder?: string; isMulti?: boolean; type?: string; iid?: string; name?: string; disabled?: boolean; };
khoadaxne15/LastProject
src/components/common/ColorChooser.tsx
<filename>src/components/common/ColorChooser.tsx import React, { useState } from "react"; export const ColorChooser: React.FC<ColorChooserProps> = ({ availableColors, onSelectedColorChange }) => { const [selectedColor, setSelectedColor] = useState(""); const setColor = (color: string) => { setSelectedColor(color); onSelectedColorChange(color); }; return ( <div className="color-chooser"> {availableColors.map((color) => ( <div className={selectedColor === color ? "color-item color-item-selected" : "color-item"} key={color} onClick={() => setColor(color)} style={{ backgroundColor: color }} role="presentation" /> ))} </div> ); }; type ColorChooserProps = { availableColors: string[]; onSelectedColorChange: (params: string) => void; };
khoadaxne15/LastProject
src/views/account/components/UserAvatar.tsx
/* eslint-disable indent */ import { DownOutlined, LoadingOutlined, LogoutOutlined, UserOutlined } from "@ant-design/icons"; import React, { useEffect, useRef } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Link, RouteComponentProps, withRouter } from "react-router-dom"; import { ACCOUNT } from "../../../constants"; import { AppState, ProfileState, signOut } from "../../../redux"; const _UserNav: React.FC<UserNav> = () => { const { profile, isAuthenticating } = useSelector<AppState, { profile: ProfileState; isAuthenticating: boolean }>( (state) => ({ profile: state.profile, isAuthenticating: state.app.isAuthenticating, }) ); const userNav = useRef<HTMLDivElement | null>(null); const dispatch = useDispatch(); const toggleDropdown = (e: any) => { const closest = e.target.closest("div.user-nav"); try { if (!closest && userNav.current?.classList.contains("user-sub-open")) { userNav.current.classList.remove("user-sub-open"); } } catch (err) { console.log(err); } }; useEffect(() => { document.addEventListener("click", toggleDropdown); return () => document.removeEventListener("click", toggleDropdown); }, []); const onClickNav = () => { userNav.current?.classList.toggle("user-sub-open"); }; return isAuthenticating ? ( <div className="user-nav"> <span>Signing Out</span> &nbsp; <LoadingOutlined /> </div> ) : ( <div className="user-nav" onClick={onClickNav} ref={userNav} role="button" tabIndex={0}> <h5 className="text-overflow-ellipsis">{profile.fullname && profile.fullname.split(" ")[0]}</h5> <div className="user-nav-img-wrapper"> <img alt="" className="user-nav-img" src={profile.avatar} /> </div> <DownOutlined style={{ fontSize: "1.2rem", marginLeft: "1rem" }} /> <div className="user-nav-sub"> {profile.role !== "ADMIN" && ( <Link to={ACCOUNT} className="user-nav-sub-link"> View Account <UserOutlined /> </Link> )} <h6 className="user-nav-sub-link margin-0 d-flex" onClick={() => dispatch(signOut.started({}))} role="presentation"> Sign Out <LogoutOutlined /> </h6> </div> </div> ); }; type UserNav = RouteComponentProps; export const UserAvatar = withRouter(_UserNav);
khoadaxne15/LastProject
src/views/account/edit_account/EditForm.tsx
<reponame>khoadaxne15/LastProject<filename>src/views/account/edit_account/EditForm.tsx import { ArrowLeftOutlined, CheckOutlined, LoadingOutlined } from "@ant-design/icons"; import { Field, useFormikContext } from "formik"; import React from "react"; import { useHistory } from "react-router-dom"; import { CustomInput, CustomMobileInput } from "../../../components"; import { ACCOUNT } from "../../../constants"; export const EditForm: React.FC<EditFormProps> = ({ isLoading, authProvider }) => { const history = useHistory(); const { values, submitForm } = useFormikContext(); return ( <div className="user-profile-details"> <Field disabled={isLoading} name="fullname" type="text" label="* Full Name" placeholder="Enter your full name" component={CustomInput} style={{ textTransform: "capitalize" }} /> <Field disabled={authProvider !== "password" || isLoading} name="email" type="email" label="* Email Address" placeholder="<EMAIL>" component={CustomInput} /> <Field disabled={isLoading} name="address" type="text" label="Address (Will be used for checkout)" placeholder="#245 Brgy. Maligalig, Arayat Pampanga, Philippines" component={CustomInput} style={{ textTransform: "capitalize" }} /> <CustomMobileInput defaultValue={(values as any).mobile} name="mobile" disabled={isLoading} label="Mobile Number (Will be used for checkout)" /> <br /> <div className="edit-user-action"> <button className="button button-muted w-100-mobile" disabled={isLoading} onClick={() => history.push(ACCOUNT)} type="button"> <ArrowLeftOutlined /> &nbsp; Back to Profile </button> <button className="button w-100-mobile" disabled={isLoading} onClick={submitForm} type="button"> {isLoading ? <LoadingOutlined /> : <CheckOutlined />} &nbsp; {isLoading ? "Updating Profile" : "Update Profile"} </button> </div> </div> ); }; type EditFormProps = { isLoading: boolean; authProvider: string; };
khoadaxne15/LastProject
src/views/admin/components/ProductForm.tsx
import { CheckOutlined, LoadingOutlined } from "@ant-design/icons"; import { Field, FieldArray, Form, Formik } from "formik"; import React from "react"; import { v4 as uuidv4 } from "uuid"; import * as Yup from "yup"; import { ImageLoader, CustomColorInput, CustomCreatableSelect, CustomInput, CustomTextarea } from "../../../components"; import { useFileHandler } from "../../../hooks"; import { AddProductPayload } from "../../../redux"; // Default brand names that I used. You can use what you want const brandOptions = [ { value: "Salt Maalat", label: "Salt Maalat" }, { value: "Betsin Maalat", label: "Betsin Maalat" }, { value: "Sexbomb", label: "Sexbomb" }, { value: "Black Kibal", label: "Black Kibal" }, ]; const FormSchema = Yup.object().shape({ name: Yup.string() .required("Product name is required.") .max(60, "Product name must only be less than 60 characters."), brand: Yup.string().required("Brand name is required."), price: Yup.number() .positive("Price is invalid.") .integer("Price should be an integer.") .required("Price is required."), description: Yup.string().required("Description is required."), maxQuantity: Yup.number() .positive("Max quantity is invalid.") .integer("Max quantity should be an integer.") .required("Max quantity is required."), keywords: Yup.array().of(Yup.string()).min(1, "Please enter at least 1 keyword for this product."), sizes: Yup.array().of(Yup.number()).min(1, "Please enter a size for this product."), isFeatured: Yup.boolean(), isRecommended: Yup.boolean(), availableColors: Yup.array().of(Yup.string().required()).min(1, "Please add a default color for this product."), }); export type ProductFormSchema = { availableColors: string[]; brand: string; description: string; isFeatured?: boolean; isRecommended?: boolean; keywords?: string[]; maxQuantity: number; name: string; price: number; sizes: number[]; }; export const ProductForm: React.FC<ProductFormProps> = ({ product, onSubmit, isLoading }) => { const initFormikValues: ProductFormSchema = { name: product?.name || "", brand: product?.brand || "", price: product?.price || 0, maxQuantity: product?.maxQuantity || 0, description: product?.description || "", keywords: product?.keywords || [], sizes: product?.sizes || [], isFeatured: product?.isFeatured || false, isRecommended: product?.isRecommended || false, availableColors: product?.availableColors || [], }; const { imageFile, isFileLoading, onFileChange, removeImage } = useFileHandler({ image: [], imageCollection: product?.imageCollection || [], }); const onSubmitForm = (form: ProductFormSchema) => { const image = imageFile.image[0].file; if (image && product.imageUrl) { onSubmit({ ...form, quantity: 1, // due to firebase function billing policy, let's add lowercase version // of name here instead in firebase functions name_lower: form.name.toLowerCase(), dateAdded: new Date().getTime(), image, imageCollection: imageFile.imageCollection, id: uuidv4(), imageUrl: "", }); } else { // eslint-disable-next-line no-alert alert("Product thumbnail image is required."); } }; return ( <div> <Formik initialValues={initFormikValues} validateOnChange validationSchema={FormSchema} onSubmit={onSubmitForm}> {({ values, setValues }) => ( <Form className="product-form"> <div className="product-form-inputs"> <div className="d-flex"> <div className="product-form-field"> <Field disabled={isLoading} name="name" type="text" label="* Product Name" placeholder="Gago" style={{ textTransform: "capitalize" }} component={CustomInput} /> </div> &nbsp; <div className="product-form-field"> <CustomCreatableSelect defaultValue={{ label: values.brand, value: values.brand }} name="brand" iid="brand" options={brandOptions} disabled={isLoading} placeholder="Select/Create Brand" label="* Brand" /> </div> </div> <div className="product-form-field"> <Field disabled={isLoading} name="description" id="description" rows={3} label="* Product Description" component={CustomTextarea} /> </div> <div className="d-flex"> <div className="product-form-field"> <Field disabled={isLoading} name="price" id="price" type="number" label="* Price" component={CustomInput} /> </div> &nbsp; <div className="product-form-field"> <Field disabled={isLoading} name="maxQuantity" type="number" id="maxQuantity" label="* Max Quantity" component={CustomInput} /> </div> </div> <div className="d-flex"> <div className="product-form-field"> <CustomCreatableSelect defaultValue={values.keywords?.map((key) => ({ value: key, label: key })) ?? {}} name="keywords" iid="keywords" isMulti disabled={isLoading} placeholder="Create/Select Keywords" label="* Keywords" options={[]} /> </div> &nbsp; <div className="product-form-field"> <CustomCreatableSelect defaultValue={values.keywords?.map((key) => ({ value: key, label: key })) ?? {}} name="sizes" iid="sizes" type="number" isMulti disabled={isLoading} placeholder="Create/Select Sizes" label="* Sizes (Millimeter)" options={[]} /> </div> </div> <div className="product-form-field"> {/* @ts-ignore */} <FieldArray name="availableColors" disabled={isLoading} component={CustomColorInput} /> </div> <div className="product-form-field"> <span className="d-block padding-s">Image Collection</span> {!isFileLoading && ( <label htmlFor="product-input-file-collection"> <input disabled={isLoading} hidden id="product-input-file-collection" multiple onChange={(e) => onFileChange(e, { name: "imageCollection", type: "multiple" })} readOnly={isLoading} type="file" /> Choose Images </label> )} </div> <div className="product-form-collection"> <> {imageFile.imageCollection.length >= 1 && imageFile.imageCollection.map((image) => ( <div className="product-form-collection-image" key={image.id}> <ImageLoader alt="" src={image.url || ""} /> <button className="product-form-delete-image" onClick={() => removeImage({ id: image.id, name: "imageCollection" })} title="Delete Image" type="button"> <i className="fa fa-times-circle" /> </button> </div> ))} </> </div> <br /> <div className="d-flex"> <div className="product-form-field"> <input checked={values.isFeatured} className="" id="featured" onChange={(e) => setValues({ ...values, isFeatured: e.target.checked })} type="checkbox" /> <label htmlFor="featured"> <h5 className="d-flex-grow-1 margin-0">&nbsp; Add to Featured &nbsp;</h5> </label> </div> <div className="product-form-field"> <input checked={values.isRecommended} className="" id="recommended" onChange={(e) => setValues({ ...values, isRecommended: e.target.checked })} type="checkbox" /> <label htmlFor="recommended"> <h5 className="d-flex-grow-1 margin-0">&nbsp; Add to Recommended &nbsp;</h5> </label> </div> </div> <br /> <br /> <br /> <div className="product-form-field product-form-submit"> <button className="button" disabled={isLoading} type="submit"> {isLoading ? <LoadingOutlined /> : <CheckOutlined />} &nbsp; {isLoading ? "Saving Product" : "Save Product"} </button> </div> </div> {/* ----THUBMNAIL ---- */} <div className="product-form-file"> <div className="product-form-field"> <span className="d-block padding-s">* Thumbnail</span> {!isFileLoading && ( <label htmlFor="product-input-file"> <input disabled={isLoading} hidden id="product-input-file" onChange={(e) => onFileChange(e, { name: "image", type: "single" })} readOnly={isLoading} type="file" /> Choose Image </label> )} </div> <div className="product-form-image-wrapper"> {(imageFile.image[0].url || product.image) && ( <ImageLoader alt="" className="product-form-image-preview" src={imageFile.image[0].url || product.image || ""} /> )} </div> </div> </Form> )} </Formik> </div> ); }; type ProductFormProps = { product: AddProductPayload; onSubmit: ( params: AddProductPayload & { quantity: number; // of name here instead in firebase functions name_lower: string; dateAdded: number; } ) => void; isLoading: boolean; };
khoadaxne15/LastProject
src/components/common/Filters.tsx
<gh_stars>0 import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { RouteComponentProps, useHistory, withRouter } from "react-router-dom"; import { useDidMount } from "../../hooks"; import { applyFilter, AppState, FilterState, ProductState, resetFilter, selectMax, selectMin } from "../../redux"; import { PriceRange } from "./PriceRange"; const _Filters: React.FC<FiltersProps> = ({ closeModal }) => { const { filter, isLoading, products } = useSelector< AppState, { filter: FilterState; isLoading: boolean; products: ProductState["items"] } >((state) => ({ filter: state.filter, isLoading: state.app.loading, products: state.products.items, })); const [field, setFilter] = useState<FilterState>({ brand: filter.brand, minPrice: filter.minPrice, maxPrice: filter.maxPrice, sortBy: filter.sortBy, }); const dispatch = useDispatch(); const history = useHistory(); const didMount = useDidMount(); const max = selectMax(products); const min = selectMin(products); useEffect(() => { if (didMount && window.screen.width <= 480) { history.push("/"); } if (didMount && closeModal) { closeModal("useEffect"); } setFilter(filter); window.scrollTo(0, 0); }, [filter, history]); // eslint-disable-line react-hooks/exhaustive-deps const onPriceChange = (values: ReadonlyArray<number>) => { setFilter({ ...field, minPrice: values[0], maxPrice: values[1] }); }; const onBrandFilterChange: React.ChangeEventHandler<{ value: string }> = (e) => { const val = e.target.value; setFilter({ ...field, brand: val }); }; const onSortFilterChange: React.ChangeEventHandler<{ value: string }> = (e) => { setFilter({ ...field, sortBy: e.target.value }); }; const onApplyFilter = () => { const isChanged = Object.entries(field).some(([fieldKey, fieldValue]) => fieldValue !== (filter as any)[fieldKey]); if (field.minPrice > field.maxPrice) { return; } if (isChanged) { dispatch(applyFilter(field)); } else { closeModal("onApplyFilter"); } }; const onResetFilter = () => { const filterFields = ["brand", "minPrice", "maxPrice", "sortBy"]; if (filterFields.some((key) => !!(filter as any)[key])) { dispatch(resetFilter({})); } else { closeModal("onresetFilter"); } }; return ( <div className="filters"> <div className="filters-field"> <span>Brand</span> <br /> <br /> {products.length === 0 && isLoading ? ( <h5 className="text-subtle">Loading Filter</h5> ) : ( <select className="filters-brand" value={field.brand} disabled={isLoading || products.length === 0} onChange={onBrandFilterChange}> {products.map((p, i) => { return ( <option key={i} value={p.brand}> {p.brand} </option> ); })} </select> )} </div> <div className="filters-field"> <span>Sort By</span> <br /> <br /> <select className="filters-sort-by d-block" value={field.sortBy} disabled={isLoading || products.length === 0} onChange={onSortFilterChange}> <option value="">None</option> <option value="name-asc">Name Ascending A - Z</option> <option value="name-desc">Name Descending Z - A</option> <option value="price-desc">Price High - Low</option> <option value="price-asc">Price Low - High</option> </select> </div> <div className="filters-field"> <span>Price Range</span> <br /> <br /> {(products.length === 0 && isLoading) || max === 0 ? ( <h5 className="text-subtle">Loading Filter</h5> ) : products.length === 1 ? ( <h5 className="text-subtle">No Price Range</h5> ) : ( <PriceRange min={min} max={max} initMin={field.minPrice} initMax={field.maxPrice} onPriceChange={onPriceChange} productsCount={products.length} /> )} </div> <div className="filters-action"> <button className="filters-button button button-small" disabled={isLoading || products.length === 0} onClick={onApplyFilter} type="button"> Apply filters </button> <button className="filters-button button button-border button-small" disabled={isLoading || products.length === 0} onClick={onResetFilter} type="button"> Reset filters </button> </div> </div> ); }; type FiltersProps = RouteComponentProps & { closeModal: (path: string) => void; }; export const Filters = withRouter(_Filters);
khoadaxne15/LastProject
src/components/basket/Basket.tsx
import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useHistory, useLocation } from "react-router-dom"; import { CHECKOUT_STEP_1 } from "../../constants"; import { calculateTotal, displayMoney } from "../../helpers"; import { useDidMount, useModal } from "../../hooks"; import { AppState, AuthState, BasketState, clearBasket } from "../../redux"; import firebase from "../../services/firebase"; import { Boundary, Modal } from "../common"; import { BasketItem } from "./BasketItem"; import { BasketToggle } from "./BasketToggle"; export const Basket: React.FC = () => { const { isOpenModal, onOpenModal, onCloseModal } = useModal(); const { basket, user } = useSelector<AppState, { user: AuthState; basket: BasketState }>((state) => ({ basket: state.basket, user: state.auth, })); const history = useHistory(); const { pathname } = useLocation(); const dispatch = useDispatch(); const didMount = useDidMount(); useEffect(() => { if (didMount && firebase.auth.currentUser && basket.length !== 0) { firebase .saveBasketItems(basket, firebase.auth.currentUser.uid) .then(() => { console.log("Item saved to basket"); }) .catch((e) => { console.log(e); }); } }, [basket, basket.length, didMount]); const onCheckOut = () => { if (basket.length !== 0 && user) { document.body.classList.remove("is-basket-open"); history.push(CHECKOUT_STEP_1); } else { onOpenModal(); } }; const onSignInClick = () => { onCloseModal("basket"); document.body.classList.remove("basket-open"); history.push(CHECKOUT_STEP_1); }; const onClearBasket = () => { if (basket.length !== 0) { dispatch(clearBasket({})); } }; return user && user.role === "ADMIN" ? null : ( <Boundary> <Modal isOpen={isOpenModal} onRequestClose={() => onCloseModal("basket")}> <p className="text-center">You must sign in to continue checking out</p> <br /> <div className="d-flex-center"> <button className="button button-border button-border-gray button-small" onClick={() => onCloseModal("basket")} type="button"> Continue shopping </button> &nbsp; <button className="button button-small" onClick={onSignInClick} type="button"> Sign in to checkout </button> </div> </Modal> <div className="basket"> <div className="basket-list"> <div className="basket-header"> <h3 className="basket-header-title"> My Basket &nbsp; <span>({` ${basket.length} ${basket.length > 1 ? "items" : "item"}`})</span> </h3> <BasketToggle> {({ onClickToggle }) => ( <span className="basket-toggle button button-border button-border-gray button-small" onClick={onClickToggle} role="presentation"> Close </span> )} </BasketToggle> <button className="basket-clear button button-border button-border-gray button-small" disabled={basket.length === 0} onClick={onClearBasket} type="button"> <span>Clear Basket</span> </button> </div> {basket.length <= 0 && ( <div className="basket-empty"> <h5 className="basket-empty-msg">Your basket is empty</h5> </div> )} {basket.map((product, i) => ( <BasketItem basket={basket} key={`${product.id}_${i}`} product={product} /> ))} </div> <div className="basket-checkout"> <div className="basket-total"> <p className="basket-total-title">Subtotal Amout:</p> <h2 className="basket-total-amount"> {displayMoney(calculateTotal(basket.map((product) => product.price * product.quantity)))} </h2> </div> <button className="basket-checkout-button button" disabled={basket.length === 0 || pathname === "/checkout"} onClick={onCheckOut} type="button"> Check Out </button> </div> </div> </Boundary> ); };
khoadaxne15/LastProject
src/hooks/useDidMount.ts
<gh_stars>0 import { useEffect, useState } from "react"; export const useDidMount = (initState = false) => { const [didMount, setDidMount] = useState(initState); useEffect(() => { setDidMount(true); return () => { setDidMount(false); }; }, []); return didMount; };
khoadaxne15/LastProject
src/views/search/index.tsx
<reponame>khoadaxne15/LastProject<filename>src/views/search/index.tsx import { LoadingOutlined } from "@ant-design/icons"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Boundary, MessageDisplay, ProductGrid } from "../../components"; import { useDidMount } from "../../hooks"; import { setRequestStatus, searchProduct, AppState, Product, BasketState, MiscState } from "../../redux"; export const Search: React.FC<SearchProps> = ({ match }) => { const { searchKey } = match.params; const dispatch = useDispatch(); const didMount = useDidMount(true); const store = useSelector< AppState, { isLoading: boolean; products: Product[]; basket: BasketState; requestStatus: MiscState["requestStatus"] } >((state) => ({ isLoading: state.app.loading, products: state.products.searchedProducts.items, basket: state.basket, requestStatus: state.app.requestStatus, })); useEffect(() => { if (didMount && !store.isLoading && searchKey) { dispatch(searchProduct.started({ searchKey })); } }, [didMount, searchKey]); // eslint-disable-line react-hooks/exhaustive-deps useEffect( () => () => { dispatch(setRequestStatus({ message: "" })); }, [] // eslint-disable-line react-hooks/exhaustive-deps ); if (store.requestStatus && !store.isLoading) { return ( <main className="content"> <MessageDisplay message={store.requestStatus.message} description="Try using correct filters or keyword." /> </main> ); } if (!store.requestStatus && !store.isLoading) { return ( <Boundary> <main className="content"> <section className="product-list-wrapper product-list-search"> {!store.requestStatus && ( <div className="product-list-header"> <div className="product-list-header-title"> <h5> {`Found ${store.products.length} ${ store.products.length > 1 ? "products" : "product" } with keyword ${searchKey}`} </h5> </div> </div> )} <ProductGrid products={store.products} /> </section> </main> </Boundary> ); } return ( <main className="content"> <div className="loader"> <h4>Searching Product...</h4> <br /> <LoadingOutlined style={{ fontSize: "3rem" }} /> </div> </main> ); }; type SearchProps = { match: { params: { searchKey?: string }; }; };
khoadaxne15/LastProject
src/views/admin/components/ProductsNavbar.tsx
import { FilterOutlined, PlusOutlined } from "@ant-design/icons"; import React from "react"; import { useHistory } from "react-router-dom"; import { FiltersToggle, SearchBar } from "../../../components/common"; import { ADD_PRODUCT } from "../../../constants"; export const ProductsNavbar: React.FC<ProductsNavbarProps> = (props) => { const { productsCount, totalProductsCount } = props; const history = useHistory(); return ( <div className="product-admin-header"> <h3 className="product-admin-header-title">Products &nbsp; ({`${productsCount} / ${totalProductsCount}`})</h3> <SearchBar /> &nbsp; <FiltersToggle> <button className="button-muted button-small" type="button"> <FilterOutlined /> &nbsp;More Filters </button> </FiltersToggle> <button className="button button-small" onClick={() => history.push(ADD_PRODUCT)} type="button"> <PlusOutlined /> &nbsp; Add New Product </button> </div> ); }; type ProductsNavbarProps = { productsCount: number; totalProductsCount: number; };
khoadaxne15/LastProject
src/components/formik/CustomTextarea.tsx
import React from "react"; export const CustomTextarea: React.FC<CustomTextareaProps> = ({ field, form: { touched, errors }, label, ...props }) => ( <div className="input-group"> {touched[field.name] && errors[field.name] ? ( <span className="label-input label-error">{errors[field.name]}</span> ) : ( <label className="label-input" htmlFor={field.name}> {label} </label> )} <textarea cols={30} rows={4} id={field.name} className={`input-form ${touched[field.name] && errors[field.name] && "input-error"}`} {...field} {...props} name={field.name} /> </div> ); type CustomTextareaProps = { label: string; field: { name: string }; form: { touched: Record<string, string[]>; errors: Record<string, string[]> }; };
khoadaxne15/LastProject
src/redux/actions/index.ts
export * from "./authActions"; export * from "./basketActions"; export * from "./checkoutActions"; export * from "./filterActions"; export * from "./miscActions"; export * from "./productActions"; export * from "./profileActions"; export * from "./userActions";
khoadaxne15/LastProject
src/redux/reducers/productReducer.ts
import firebase from "firebase"; import { AnyAction } from "typescript-fsa"; import { ProductFormSchema } from "../../views/admin"; import { addProduct, clearSearchState, editProduct, getProducts, ImageCollection, removeProduct, searchProduct, } from "../actions"; import DocumentData = firebase.firestore.DocumentData; export interface Product extends DocumentData, ProductFormSchema { id: string; image?: File; imageCollection: ImageCollection; imageUrl: string; quantity: number; selectedColor?: string; selectedSize?: number; } export interface SearchedProduct { lastRefKey: string | null; total: number; items: Product[]; } export interface ProductState extends SearchedProduct { searchedProducts: SearchedProduct; } const initState: ProductState = { lastRefKey: null, total: 0, items: [], searchedProducts: { lastRefKey: null, total: 0, items: [], }, }; export function productReducer(state: ProductState | undefined, action: AnyAction): ProductState { if (state === undefined) { return initState; } if (getProducts.done.match(action)) { return { ...state, lastRefKey: action.payload.result.lastRefKey, total: action.payload.result.total, items: [...state.items, ...action.payload.result.items], }; } if (addProduct.done.match(action)) { return { ...state, items: [...state.items, action.payload.result], }; } if (searchProduct.done.match(action)) { return { ...state, searchedProducts: { lastRefKey: action.payload.result.lastRefKey, total: action.payload.result.total, items: [...state.searchedProducts.items, ...action.payload.result.items], }, }; } if (clearSearchState.match(action)) { return { ...state, searchedProducts: initState, }; } if (removeProduct.done.match(action)) { return { ...state, items: state.items.filter((product) => product.id !== action.payload.result), }; } if (editProduct.done.match(action)) { return { ...state, items: state.items.map((product) => { if (product.id === action.payload.result.id) { return { ...product, ...action.payload.result.updates, }; } return product; }), }; } return state; }
khoadaxne15/LastProject
src/views/view_product/index.tsx
<gh_stars>0 import { ArrowLeftOutlined, LoadingOutlined } from "@ant-design/icons"; import React, { useEffect, useRef, useState } from "react"; import { Link, useParams } from "react-router-dom"; import Select from "react-select"; import { v4 as uuidv4 } from "uuid"; import { ColorChooser, ImageLoader, MessageDisplay, ProductShowcase } from "../../components"; import { RECOMMENDED_PRODUCTS, SHOP } from "../../constants"; import { displayMoney } from "../../helpers"; import { useBasket, useDocumentTitle, useProduct, useRecommendedProducts, useScrollTop } from "../../hooks"; export const ViewProduct: React.FC = () => { const { id } = useParams<{ id: string }>(); const { product, isLoading, error } = useProduct(id); const { addToBasket, isItemOnBasket } = useBasket(); useScrollTop(); useDocumentTitle(`View ${product?.name || "Item"}`); const [selectedImage, setSelectedImage] = useState(product?.image || ""); const [selectedSize, setSelectedSize] = useState<number>(0); const [selectedColor, setSelectedColor] = useState(""); const { recommendedProducts, fetchRecommendedProducts, isLoading: isLoadingFeatured, error: errorFeatured, } = useRecommendedProducts(6); const colorOverlay = useRef<HTMLInputElement | null>(null); useEffect(() => { setSelectedImage(product?.image ?? ""); }, [product]); const onSelectedSizeChange = (newValue: any) => { setSelectedSize(newValue.value); }; const onSelectedColorChange = (color: any) => { setSelectedColor(color); if (colorOverlay.current) { colorOverlay.current.value = color; } }; const handleAddToBasket = () => { addToBasket({ availableColors: [], brand: "", description: "", isFeatured: false, isRecommended: false, maxQuantity: 0, name: "", price: 0, sizes: [], ...product, quantity: product?.quantity ?? 1, imageUrl: product?.imageUrl ?? "", imageCollection: product?.imageCollection ?? [], image: product?.image, id: product?.id || uuidv4(), selectedColor, selectedSize: selectedSize || product?.sizes[0], }); }; return ( <main className="content"> {isLoading && ( <div className="loader"> <h4>Loading Product...</h4> <br /> <LoadingOutlined style={{ fontSize: "3rem" }} /> </div> )} {error && <MessageDisplay message={error} />} {product && !isLoading && ( <div className="product-view"> <Link to={SHOP}> <h3 className="button-link d-inline-flex"> <ArrowLeftOutlined /> &nbsp; Back to shop </h3> </Link> <div className="product-modal"> {product.imageCollection.length !== 0 && ( <div className="product-modal-image-collection"> {/*{product.imageCollection.map((image) => (*/} {/* <div*/} {/* className="product-modal-image-collection-wrapper"*/} {/* key={image.id}*/} {/* onClick={() => setSelectedImage(image.url)}*/} {/* role="presentation">*/} {/* <ImageLoader alt="" className="product-modal-image-collection-img" src={image.url} />*/} {/* </div>*/} {/*))}*/} </div> )} <div className="product-modal-image-wrapper"> {selectedColor && <input type="color" disabled ref={colorOverlay} id="color-overlay" />} <ImageLoader alt={product.name} className="product-modal-image" src={selectedImage} /> </div> <div className="product-modal-details"> <br /> <span className="text-subtle">{product.brand}</span> <h1 className="margin-top-0">{product.name}</h1> <span>{product.description}</span> <br /> <br /> <div className="divider" /> <br /> <div> <span className="text-subtle">Lens Width and Frame Size</span> <br /> <br /> <Select placeholder="--Select Size--" onChange={onSelectedSizeChange} options={product.sizes .sort((a, b) => (a < b ? -1 : 1)) .map((size) => ({ label: `${size} mm`, value: size }))} styles={{ menu: (provided) => ({ ...provided, zIndex: 10 }) }} /> </div> <br /> {product.availableColors.length >= 1 && ( <div> <span className="text-subtle">Choose Color</span> <br /> <br /> <ColorChooser availableColors={product.availableColors} onSelectedColorChange={onSelectedColorChange} /> </div> )} <h1>{displayMoney(product.price)}</h1> <div className="product-modal-action"> <button className={`button button-small ${ isItemOnBasket(product.id) ? "button-border button-border-gray" : "" }`} onClick={handleAddToBasket} type="button"> {isItemOnBasket(product.id) ? "Remove From Basket" : "Add To Basket"} </button> </div> </div> </div> <div style={{ marginTop: "10rem" }}> <div className="display-header"> <h1>Recommended</h1> <Link to={RECOMMENDED_PRODUCTS}>See All</Link> </div> {errorFeatured && !isLoadingFeatured ? ( <MessageDisplay message={error ?? ""} action={fetchRecommendedProducts} buttonLabel="Try Again" /> ) : ( <ProductShowcase products={recommendedProducts} skeletonCount={3} /> )} </div> </div> )} </main> ); };
khoadaxne15/LastProject
src/components/common/PriceRange/Track.tsx
<reponame>khoadaxne15/LastProject<gh_stars>0 import React from "react"; export const Track: React.FC<TrackProps> = ({ source, target, getTrackProps, disabled }) => ( <div style={{ position: "absolute", transform: "translate(0%, -50%)", height: 14, zIndex: 1, backgroundColor: disabled ? "#ffd993" : "#ffa500", borderRadius: 7, cursor: "pointer", left: `${source.percent}%`, width: `${target.percent - source.percent}%`, }} {...getTrackProps()} /> ); type TrackProps = { source: { id: string; value: number; percent: number; }; target: { id: string; value: number; percent: number; }; getTrackProps: () => void; disabled?: boolean; }; Track.defaultProps = { disabled: false, };
khoadaxne15/LastProject
src/components/common/FiltersToggle.tsx
import React from "react"; import { useModal } from "../../hooks"; import { Filters } from "./Filters"; import { Modal } from "./Modal"; export const FiltersToggle: React.FC<FiltersToggleProps> = ({ children }) => { const { isOpenModal, onOpenModal, onCloseModal } = useModal(); return ( <> <div className="filters-toggle" onClick={onOpenModal} role="presentation"> {children} </div> <Modal isOpen={isOpenModal} onRequestClose={() => onCloseModal("filter 1")}> <div className="filters-toggle-sub"> <Filters closeModal={(subwhere: string) => { console.log({ subwhere }); onCloseModal("filter 2"); }} /> </div> <button className="modal-close-button" onClick={() => onCloseModal("filter 3")} type="button"> <i className="fa fa-times-circle" /> </button> </Modal> </> ); }; type FiltersToggleProps = { children: React.ReactNode | React.ReactNode[]; };
khoadaxne15/LastProject
src/views/account/user_account/index.tsx
import { LoadingOutlined } from "@ant-design/icons"; import React from "react"; import { useDocumentTitle, useScrollTop } from "../../../hooks"; import { UserAccountTab, UserOrdersTab, UserTab, UserWishListTab } from "../components"; export const Loader: React.FC = () => ( <div className="loader" style={{ minHeight: "80vh" }}> <LoadingOutlined /> <h6>Loading ... </h6> </div> ); export const UserAccount: React.FC = () => { useScrollTop(); useDocumentTitle("My Account | TK"); return ( <UserTab> {/* @ts-ignore */} <div key={0} label="Account"> <UserAccountTab /> </div> {/* @ts-ignore */} <div key={1} label="Wishlist"> <UserWishListTab /> </div> {/* @ts-ignore */} <div key={2} label="Orders"> <UserOrdersTab /> </div> </UserTab> ); };