From af873d8155176fcb4c9a6e1d09de4a71dc75ecda Mon Sep 17 00:00:00 2001 From: Sumit Kumar Mridha <3sumit5@gmail.com> Date: Sun, 24 Dec 2023 18:47:41 +0530 Subject: [PATCH 1/5] First commit --- .vscode/settings.json | 4 +- index.html | 4 +- public/mockServiceWorker.js | 189 ++++++++++++++++++------------------ src/pages/Home.jsx | 135 ++++++++++++++++++++++++-- 4 files changed, 226 insertions(+), 106 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 6f6e64a..47e36fb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -6,7 +6,7 @@ "scss.validate": false, "less.validate": false, "editor.codeActionsOnSave": { - "source.fixAll.stylelint": true, - "source.fixAll.eslint": true + "source.fixAll.stylelint": "explicit", + "source.fixAll.eslint": "explicit" } } diff --git a/index.html b/index.html index 7a8272f..caf7097 100644 --- a/index.html +++ b/index.html @@ -5,8 +5,8 @@ Codebuddy React Interview - - + +
diff --git a/public/mockServiceWorker.js b/public/mockServiceWorker.js index 2f1d1d5..6bc04ab 100644 --- a/public/mockServiceWorker.js +++ b/public/mockServiceWorker.js @@ -8,124 +8,124 @@ * - Please do NOT serve this file on production. */ -const INTEGRITY_CHECKSUM = 'c5f7f8e188b673ea4e677df7ea3c5a39' -const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') -const activeClientIds = new Set() +const INTEGRITY_CHECKSUM = "c5f7f8e188b673ea4e677df7ea3c5a39"; +const IS_MOCKED_RESPONSE = Symbol("isMockedResponse"); +const activeClientIds = new Set(); -self.addEventListener('install', function () { - self.skipWaiting() -}) +self.addEventListener("install", function () { + self.skipWaiting(); +}); -self.addEventListener('activate', function (event) { - event.waitUntil(self.clients.claim()) -}) +self.addEventListener("activate", function (event) { + event.waitUntil(self.clients.claim()); +}); -self.addEventListener('message', async function (event) { - const clientId = event.source.id +self.addEventListener("message", async function (event) { + const clientId = event.source.id; if (!clientId || !self.clients) { - return + return; } - const client = await self.clients.get(clientId) + const client = await self.clients.get(clientId); if (!client) { - return + return; } const allClients = await self.clients.matchAll({ - type: 'window', - }) + type: "window", + }); switch (event.data) { - case 'KEEPALIVE_REQUEST': { + case "KEEPALIVE_REQUEST": { sendToClient(client, { - type: 'KEEPALIVE_RESPONSE', - }) - break + type: "KEEPALIVE_RESPONSE", + }); + break; } - case 'INTEGRITY_CHECK_REQUEST': { + case "INTEGRITY_CHECK_REQUEST": { sendToClient(client, { - type: 'INTEGRITY_CHECK_RESPONSE', + type: "INTEGRITY_CHECK_RESPONSE", payload: INTEGRITY_CHECKSUM, - }) - break + }); + break; } - case 'MOCK_ACTIVATE': { - activeClientIds.add(clientId) + case "MOCK_ACTIVATE": { + activeClientIds.add(clientId); sendToClient(client, { - type: 'MOCKING_ENABLED', + type: "MOCKING_ENABLED", payload: true, - }) - break + }); + break; } - case 'MOCK_DEACTIVATE': { - activeClientIds.delete(clientId) - break + case "MOCK_DEACTIVATE": { + activeClientIds.delete(clientId); + break; } - case 'CLIENT_CLOSED': { - activeClientIds.delete(clientId) + case "CLIENT_CLOSED": { + activeClientIds.delete(clientId); const remainingClients = allClients.filter((client) => { - return client.id !== clientId - }) + return client.id !== clientId; + }); // Unregister itself when there are no more clients if (remainingClients.length === 0) { - self.registration.unregister() + self.registration.unregister(); } - break + break; } } -}) +}); -self.addEventListener('fetch', function (event) { - const { request } = event +self.addEventListener("fetch", function (event) { + const { request } = event; // Bypass navigation requests. - if (request.mode === 'navigate') { - return + if (request.mode === "navigate") { + return; } // Opening the DevTools triggers the "only-if-cached" request // that cannot be handled by the worker. Bypass such requests. - if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { - return + if (request.cache === "only-if-cached" && request.mode !== "same-origin") { + return; } // Bypass all requests when there are no active clients. // Prevents the self-unregistered worked from handling requests // after it's been deleted (still remains active until the next reload). if (activeClientIds.size === 0) { - return + return; } // Generate unique request ID. - const requestId = crypto.randomUUID() - event.respondWith(handleRequest(event, requestId)) -}) + const requestId = crypto.randomUUID(); + event.respondWith(handleRequest(event, requestId)); +}); async function handleRequest(event, requestId) { - const client = await resolveMainClient(event) - const response = await getResponse(event, client, requestId) + const client = await resolveMainClient(event); + const response = await getResponse(event, client, requestId); // Send back the response clone for the "response:*" life-cycle events. // Ensure MSW is active and ready to handle the message, otherwise // this message will pend indefinitely. if (client && activeClientIds.has(client.id)) { - ;(async function () { - const responseClone = response.clone() + (async function () { + const responseClone = response.clone(); sendToClient( client, { - type: 'RESPONSE', + type: "RESPONSE", payload: { requestId, isMockedResponse: IS_MOCKED_RESPONSE in response, @@ -137,11 +137,11 @@ async function handleRequest(event, requestId) { }, }, [responseClone.body], - ) - })() + ); + })(); } - return response + return response; } // Resolve the main client for the given event. @@ -149,49 +149,49 @@ async function handleRequest(event, requestId) { // that registered the worker. It's with the latter the worker should // communicate with during the response resolving phase. async function resolveMainClient(event) { - const client = await self.clients.get(event.clientId) + const client = await self.clients.get(event.clientId); - if (client?.frameType === 'top-level') { - return client + if (client?.frameType === "top-level") { + return client; } const allClients = await self.clients.matchAll({ - type: 'window', - }) + type: "window", + }); return allClients .filter((client) => { // Get only those clients that are currently visible. - return client.visibilityState === 'visible' + return client.visibilityState === "visible"; }) .find((client) => { // Find the client ID that's recorded in the // set of clients that have registered the worker. - return activeClientIds.has(client.id) - }) + return activeClientIds.has(client.id); + }); } async function getResponse(event, client, requestId) { - const { request } = event + const { request } = event; // Clone the request because it might've been already used // (i.e. its body has been read and sent to the client). - const requestClone = request.clone() + const requestClone = request.clone(); function passthrough() { - const headers = Object.fromEntries(requestClone.headers.entries()) + const headers = Object.fromEntries(requestClone.headers.entries()); // Remove internal MSW request header so the passthrough request // complies with any potential CORS preflight checks on the server. // Some servers forbid unknown request headers. - delete headers['x-msw-intention'] + delete headers["x-msw-intention"]; - return fetch(requestClone, { headers }) + return fetch(requestClone, { headers }); } // Bypass mocking when the client is not active. if (!client) { - return passthrough() + return passthrough(); } // Bypass initial page load requests (i.e. static assets). @@ -199,22 +199,22 @@ async function getResponse(event, client, requestId) { // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet // and is not ready to handle requests. if (!activeClientIds.has(client.id)) { - return passthrough() + return passthrough(); } // Bypass requests with the explicit bypass header. // Such requests can be issued by "ctx.fetch()". - const mswIntention = request.headers.get('x-msw-intention') - if (['bypass', 'passthrough'].includes(mswIntention)) { - return passthrough() + const mswIntention = request.headers.get("x-msw-intention"); + if (["bypass", "passthrough"].includes(mswIntention)) { + return passthrough(); } // Notify the client that a request has been intercepted. - const requestBuffer = await request.arrayBuffer() + const requestBuffer = await request.arrayBuffer(); const clientMessage = await sendToClient( client, { - type: 'REQUEST', + type: "REQUEST", payload: { id: requestId, url: request.url, @@ -233,38 +233,35 @@ async function getResponse(event, client, requestId) { }, }, [requestBuffer], - ) + ); switch (clientMessage.type) { - case 'MOCK_RESPONSE': { - return respondWithMock(clientMessage.data) + case "MOCK_RESPONSE": { + return respondWithMock(clientMessage.data); } - case 'MOCK_NOT_FOUND': { - return passthrough() + case "MOCK_NOT_FOUND": { + return passthrough(); } } - return passthrough() + return passthrough(); } function sendToClient(client, message, transferrables = []) { return new Promise((resolve, reject) => { - const channel = new MessageChannel() + const channel = new MessageChannel(); channel.port1.onmessage = (event) => { if (event.data && event.data.error) { - return reject(event.data.error) + return reject(event.data.error); } - resolve(event.data) - } + resolve(event.data); + }; - client.postMessage( - message, - [channel.port2].concat(transferrables.filter(Boolean)), - ) - }) + client.postMessage(message, [channel.port2].concat(transferrables.filter(Boolean))); + }); } async function respondWithMock(response) { @@ -273,15 +270,15 @@ async function respondWithMock(response) { // instance will have status code set to 0. Since it's not possible to create // a Response instance with status code 0, handle that use-case separately. if (response.status === 0) { - return Response.error() + return Response.error(); } - const mockedResponse = new Response(response.body, response) + const mockedResponse = new Response(response.body, response); Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { value: true, enumerable: true, - }) + }); - return mockedResponse + return mockedResponse; } diff --git a/src/pages/Home.jsx b/src/pages/Home.jsx index 16836af..993ef66 100644 --- a/src/pages/Home.jsx +++ b/src/pages/Home.jsx @@ -1,7 +1,19 @@ import { Icon } from "@iconify/react"; +import { useState } from "react"; import { Link } from "react-router-dom"; const Home = () => { + const [stepNo, setStepNo] = useState(1); + + const back = () => { + if (stepNo > 1) setStepNo(stepNo - 1); + }; + + const saveAndNext = () => { + console.log("hello"); + if (stepNo < 3) setStepNo(stepNo + 1); + }; + return (

@@ -11,12 +23,123 @@ const Home = () => {

Welcome to the home page!

-

- Lorem ipsum dolor, sit amet consectetur adipisicing elit. Natus eos quis iure unde incidunt? - Hic, quisquam. Voluptate placeat officiis corporis dolores ea unde maxime, sed nulla cumque - amet quam aliquam quas incidunt debitis sit aut a soluta quisquam repellat dignissimos qui. - Perspiciatis similique quaerat reiciendis nam aliquam? -

+
+ {(() => { + switch (stepNo) { + case 1: + return ( + <> +
+ + +
+
+ + +
+ + ); + case 2: + return ( + <> +
+ + +
+
+ + +
+
+ + +
+ + ); + case 3: + return ( + <> +
+ + +
+
+ + +
+
+ + +
+ + ); + default: + return <>; + } + })()} +
+ + +
+
Posts From 91bcb91b042d83e874b2d1619f5edb5e9ca924ff Mon Sep 17 00:00:00 2001 From: Sumit Kumar Mridha <3sumit5@gmail.com> Date: Mon, 25 Dec 2023 12:13:57 +0530 Subject: [PATCH 2/5] css done --- package-lock.json | 21 +++++ package.json | 1 + src/index.css | 11 +++ src/pages/Home.jsx | 185 ++++++++++++++++++++++++++++++++++---------- src/pages/Posts.jsx | 65 ++++++++-------- 5 files changed, 213 insertions(+), 70 deletions(-) diff --git a/package-lock.json b/package-lock.json index b9b1e5b..fe6f02d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.20.1", + "react-toastify": "^9.1.3", "sort-by": "^1.2.0", "uuid": "^9.0.1" }, @@ -2014,6 +2015,14 @@ "node": ">=0.8" } }, + "node_modules/clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==", + "engines": { + "node": ">=6" + } + }, "node_modules/color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", @@ -5248,6 +5257,18 @@ "react-dom": ">=16.8" } }, + "node_modules/react-toastify": { + "version": "9.1.3", + "resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-9.1.3.tgz", + "integrity": "sha512-fPfb8ghtn/XMxw3LkxQBk3IyagNpF/LIKjOBflbexr2AWxAH1MJgvnESwEwBn9liLFXgTKWgBSdZpw9m4OTHTg==", + "dependencies": { + "clsx": "^1.1.1" + }, + "peerDependencies": { + "react": ">=16", + "react-dom": ">=16" + } + }, "node_modules/read-cache": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", diff --git a/package.json b/package.json index a1c9bb2..9d1385d 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.20.1", + "react-toastify": "^9.1.3", "sort-by": "^1.2.0", "uuid": "^9.0.1" }, diff --git a/src/index.css b/src/index.css index c4110f5..3136ecd 100644 --- a/src/index.css +++ b/src/index.css @@ -3,3 +3,14 @@ @tailwind base; @tailwind components; @tailwind utilities; + +.btn-disabled { + opacity: 0.5; + cursor: not-allowed; + pointer-events: none; +} + +.errors-list { + list-style-type: none; + font-size: 13.5px; +} diff --git a/src/pages/Home.jsx b/src/pages/Home.jsx index 993ef66..bc98804 100644 --- a/src/pages/Home.jsx +++ b/src/pages/Home.jsx @@ -1,17 +1,105 @@ import { Icon } from "@iconify/react"; import { useState } from "react"; -import { Link } from "react-router-dom"; +import { useNavigate } from "react-router-dom"; +import { ToastContainer, toast } from "react-toastify"; +import "react-toastify/dist/ReactToastify.css"; const Home = () => { const [stepNo, setStepNo] = useState(1); + const [emailId, setEmailId] = useState(""); + const [password, setPassword] = useState(""); + const [firstName, setFirstName] = useState(""); + const [lastName, setLastName] = useState(""); + const [address, setAddress] = useState(""); + const [countryCode, setCountryCode] = useState(""); + const [phoneNumber, setPhoneNumber] = useState(""); + const [atac, setATAC] = useState(false); + const navigate = useNavigate(); const back = () => { if (stepNo > 1) setStepNo(stepNo - 1); }; - const saveAndNext = () => { - console.log("hello"); - if (stepNo < 3) setStepNo(stepNo + 1); + const showErrorList = (errList) => { + toast.error( + , + ); + }; + + const save = async () => { + const errList = []; + switch (stepNo) { + case 1: + if (!/^[A-Z0-9_%+-](.[A-Z0-9_%+-]+)*@[A-Z0-9-]+(.[A-Z]{2,4})?$/i.test(emailId)) + errList.push("Email is invalid. Kindly provide valid email."); + if ( + !/^(?=.*[A-Z]{2,})(?=.*[a-z]{2,})(?=.*\d{2,})(?=.*[@$!%*#?&]{2,})[A-Za-z\d@$!%*#?&]{8,}$/.test( + password, + ) + ) { + errList.push( + "Password should contain atleast 8 characters. It should also contain atleast 2 capital letters, 2 small letters, 2 digits, 2 special characters.", + ); + } + if (errList.length) showErrorList(errList); + else toast.success("Data saved!"); + return !errList.length; + case 2: + if (!/^[a-zA-Z]{2,50}$/.test(firstName)) { + errList.push( + "First Name cannot be empty and can only have alphabets; minimum 2 and maximum 50.", + ); + } + if (lastName && !/^[a-zA-Z]+$/.test(lastName)) + errList.push("Last Name can only have alphabets."); + if (!/^.{10,}$/.test(address)) + errList.push("Address is required, and it should contain minimum 10 characters."); + if (errList.length) showErrorList(errList); + else toast.success("Data saved!"); + return !errList.length; + case 3: + if (!countryCode) { + errList.push("Please select a country code."); + } + if (!/^\d{10}$/.test(phoneNumber)) + errList.push("Phone Number should have exactly 10 digits."); + if (!atac) errList.push("Please accept the terms and conditions."); + if (errList.length) showErrorList(errList); + else { + toast.success("Details sent successfully."); + const resp = await fetch("https://codebuddy.review/submit", { + method: "POST", + body: JSON.stringify({ + emailId, + password, + firstName, + lastName, + address, + countryCode, + phoneNumber, + }), + }); + resp.json().then( + (data) => { + console.log(data); + navigate("/posts"); + }, + (err) => { + console.err("POST API SEND ERROR:", err); + }, + ); + } + } + }; + + const saveAndNext = async () => { + if (stepNo < 3) { + if (save()) setStepNo(stepNo + 1); + } }; return ( @@ -30,21 +118,23 @@ const Home = () => { return ( <>
- + setEmailId(e.target.value)} />
setPassword(e.target.value)} />
@@ -56,27 +146,30 @@ const Home = () => { setFirstName(e.target.value)} />
setLastName(e.target.value)} />
setAddress(e.target.value)} />
@@ -88,12 +181,15 @@ const Home = () => { - +
setPhoneNumber(e.target.value)} />
-
- +
setATAC(e.target.value)} /> +
); @@ -123,28 +220,38 @@ const Home = () => { return <>; } })()} -
+
+
- - Posts - - +
); }; diff --git a/src/pages/Posts.jsx b/src/pages/Posts.jsx index f74e4b3..28de2cc 100644 --- a/src/pages/Posts.jsx +++ b/src/pages/Posts.jsx @@ -1,40 +1,43 @@ -import { Icon } from "@iconify/react"; -import { Link } from "react-router-dom"; +import { useState, useEffect } from "react"; const Posts = () => { + const [posts, setPosts] = useState([]); + + const getPostsList = async () => { + const resp = await fetch("https://codebuddy.review/posts"); + resp.json().then( + (res) => { + setPosts(res.data); + }, + (err) => { + console.error("POSTS LIST FETCH ERROR:", err); + }, + ); + }; + + useEffect(() => { + getPostsList(); + }, []); + return (

Posts

- - - Back to Home - -
-
-

Post 1

-

- Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo voluptatem, quibusdam, - quos, voluptatum voluptas quod quas voluptates quia doloribus nobis voluptatibus. Quam, - voluptate voluptatum. Quod, voluptate? Quisquam, voluptate voluptatum. -

-
-
-

Post 2

-

- Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo voluptatem, quibusdam, - quos, voluptatum voluptas quod quas voluptates quia doloribus nobis voluptatibus. Quam, - voluptate voluptatum. Quod, voluptate? Quisquam, voluptate voluptatum. -

-
-
-

Post 3

-

- Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo voluptatem, quibusdam, - quos, voluptatum voluptas quod quas voluptates quia doloribus nobis voluptatibus. Quam, - voluptate voluptatum. Quod, voluptate? Quisquam, voluptate voluptatum. -

-
+
+ {posts.map((obj) => ( +
+
+
+ Author: {obj.firstName} {obj.lastName} +
+
+ +
+
+

{obj.writeup}

+ +
+ ))}
); From f59cc443f7610d15e0195867414cb9f0ec5fc469 Mon Sep 17 00:00:00 2001 From: Sumit Kumar Mridha <3sumit5@gmail.com> Date: Tue, 26 Dec 2023 14:04:49 +0530 Subject: [PATCH 3/5] included tabbed navigation --- src/index.css | 2 +- src/pages/Home.jsx | 38 ++++++++++++++++++++++++++++++++++---- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/index.css b/src/index.css index 3136ecd..a73483c 100644 --- a/src/index.css +++ b/src/index.css @@ -4,7 +4,7 @@ @tailwind components; @tailwind utilities; -.btn-disabled { +.elem-disabled { opacity: 0.5; cursor: not-allowed; pointer-events: none; diff --git a/src/pages/Home.jsx b/src/pages/Home.jsx index bc98804..f1e15ed 100644 --- a/src/pages/Home.jsx +++ b/src/pages/Home.jsx @@ -1,11 +1,12 @@ import { Icon } from "@iconify/react"; -import { useState } from "react"; +import { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; const Home = () => { const [stepNo, setStepNo] = useState(1); + const [maxStepNo, setMaxStepNo] = useState(1); const [emailId, setEmailId] = useState(""); const [password, setPassword] = useState(""); const [firstName, setFirstName] = useState(""); @@ -16,10 +17,19 @@ const Home = () => { const [atac, setATAC] = useState(false); const navigate = useNavigate(); + useEffect(() => { + if (maxStepNo < stepNo) setMaxStepNo(stepNo); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [stepNo]); + const back = () => { if (stepNo > 1) setStepNo(stepNo - 1); }; + const showTab = (num) => { + if (num <= maxStepNo) setStepNo(num); + }; + const showErrorList = (errList) => { toast.error(
    @@ -112,6 +122,26 @@ const Home = () => {

    Welcome to the home page!

    + {(() => { switch (stepNo) { case 1: @@ -130,7 +160,7 @@ const Home = () => {
    { + { + if (restrictedChars.includes(e.key)) e.preventDefault(); + }} + onChange={(e) => setRows(e.target.value)} + > + +
    + +
+
+ {seats.map((seatArr, i) => ( +
+
Row {seats.length - i}
+
+ {seatArr.seats.map((seat, j) => ( +
selectSeat(seat)} + > + {seat.seatNumber} +
+ ))} +
+
+ ))} +
+
Legend:
+
+
Seats Reserved
+
+
Seats Selected
+
+
Seats Not Selected
+
+
+
Total cost of seats: ${totalPrice}
+ +
+
+ +
+ ); +}; + +export default MovieSeats;