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/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/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/Router.jsx b/src/Router.jsx index 60e2160..217c696 100644 --- a/src/Router.jsx +++ b/src/Router.jsx @@ -2,6 +2,7 @@ import { RouterProvider, createBrowserRouter } from "react-router-dom"; import Home from "./pages/Home"; import Posts from "./pages/Posts"; import Root from "./pages/Root"; +import MovieSeats from "./pages/MovieSeats"; const router = createBrowserRouter([ { @@ -10,6 +11,7 @@ const router = createBrowserRouter([ children: [ { path: "/", element: }, { path: "/posts", element: }, + { path: "/movie-seats", element: }, ], }, ]); diff --git a/src/index.css b/src/index.css index c4110f5..bad5509 100644 --- a/src/index.css +++ b/src/index.css @@ -3,3 +3,116 @@ @tailwind base; @tailwind components; @tailwind utilities; + +.elem-disabled { + opacity: 0.5; + cursor: not-allowed; + pointer-events: none; +} + +.errors-list { + list-style-type: none; + font-size: 13.5px; +} + +.movie-rownum-container { + border-radius: 10px; + box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px; + display: flex; + overflow: hidden; +} + +.movie-rownum-container > input { + width: 40px; +} + +.movie-rownum-container input[type='number']::-webkit-inner-spin-button, +.movie-rownum-container input[type='number']::-webkit-outer-spin-button { + -webkit-appearance: none; + margin: 0; +} + +.movie-rownum-container input:focus { + outline: none !important; +} + +.movie-rownum-container button:focus { + outline: none !important; +} + +.movie-seats-table { + margin-top: 20px; + border-radius: 20px; + padding: 20px; + background-color: white; +} + +.seat-row { + display: flex; + align-items: center; + outline: 1px solid #777; +} + +.seat-row > div:first-of-type { + padding: 8px 10px; + border-right: 1px solid #777; + width: 75px; +} + +.seat-row > div:last-of-type { + padding: 8px 0; + flex-grow: 1; + display: flex; + justify-content: center; +} + +.seat-row .seat { + width: 18px; + height: 18px; + outline: 1px solid #222; + margin: 0 2.5px; + cursor: pointer; + line-height: 18px; + text-align: center; + font-size: 12px; +} + +.seat-row .seat.reserved { + background-color: #bbb; + cursor: not-allowed; + pointer-events: none; +} + +.seat-row .seat.selected { + background-color: greenyellow; +} + +.seat-legend { + display: flex; + align-items: center; + margin-top: 15px; +} + +.seat-legend > div:nth-of-type(even) { + border: 1px solid black; + height: 14px; + width: 14px; + margin-right: 7px; +} + +.seat-legend > div:nth-of-type(odd) { + margin-right: 25px; +} + +.seat-legend > div:nth-of-type(1) { + font-weight: 500; + margin-right: 30px; +} + +.seat-legend > div:nth-of-type(2) { + background-color: #bbb; +} + +.seat-legend > div:nth-of-type(4) { + background-color: greenyellow; +} diff --git a/src/pages/Home.jsx b/src/pages/Home.jsx index 16836af..5aa65fb 100644 --- a/src/pages/Home.jsx +++ b/src/pages/Home.jsx @@ -1,7 +1,116 @@ import { Icon } from "@iconify/react"; -import { Link } from "react-router-dom"; +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(""); + const [lastName, setLastName] = useState(""); + const [address, setAddress] = useState(""); + const [countryCode, setCountryCode] = useState(""); + const [phoneNumber, setPhoneNumber] = useState(""); + const [atac, setATAC] = useState(false); + const navigate = useNavigate(); + + useEffect(() => { + if (maxStepNo < stepNo) setMaxStepNo(stepNo); + }, [maxStepNo, stepNo]); + + const back = () => { + if (stepNo > 1) setStepNo(stepNo - 1); + }; + + const showTab = (num) => { + if (num <= maxStepNo) setStepNo(num); + }; + + const showErrorList = (errList) => { + toast.error( +
    + {errList.map((msg) => ( +
  • {msg}
  • + ))} +
, + ); + }; + + 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 (

@@ -11,17 +120,167 @@ 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? -

- - - Posts - - +
+ + {(() => { + switch (stepNo) { + case 1: + return ( + <> +
+ + setEmailId(e.target.value)} + /> +
+
+ + setPassword(e.target.value)} + /> +
+ + ); + case 2: + return ( + <> +
+ + setFirstName(e.target.value)} + /> +
+
+ + setLastName(e.target.value)} + /> +
+
+ + setAddress(e.target.value)} + /> +
+ + ); + case 3: + return ( + <> +
+ + +
+
+ + setPhoneNumber(e.target.value)} + /> +
+
+ setATAC(e.target.value)} + /> + +
+ + ); + default: + return <>; + } + })()} +
+ + + +
+
+ +
); }; diff --git a/src/pages/MovieSeats.jsx b/src/pages/MovieSeats.jsx new file mode 100644 index 0000000..7651288 --- /dev/null +++ b/src/pages/MovieSeats.jsx @@ -0,0 +1,181 @@ +import { useState, useEffect } from "react"; +import { ToastContainer, toast } from "react-toastify"; +import "react-toastify/dist/ReactToastify.css"; + +const MovieSeats = () => { + const restrictedChars = ["e", ".", "-", "+"]; + const [rows, setRows] = useState(3); + const [seats, setSeats] = useState([]); + const [selectedSeats, setSelectedSeats] = useState(null); + const [totalPrice, setTotalPrice] = useState(0); + + useEffect(() => { + fetchSeats(3); + }, []); + + useEffect(() => { + if (selectedSeats == null) return; + let price = 0; + let arr = Object.keys(selectedSeats); + arr.forEach((e) => { + price += (selectedSeats[e].row + 1) * 10 + 20; + }); + setTotalPrice(price); + }, [selectedSeats]); + + const fetchSeats = async (num) => { + if (isNaN(num) || num < 3 || num > 10) { + toast.error("Invalid number/out of range."); + return; + } + num = Number(num); + setRows(num); + setSelectedSeats({}); + let resp = await fetch(`https://codebuddy.review/seats?count=${num}`); + resp.json().then( + (res) => { + console.log(res.data); + setSeats(res.data); + }, + (err) => { + console.error("SEATS LIST FETCH ERROR:", err); + }, + ); + }; + + const selectSeat = (seat) => { + let tmp = selectedSeats ? { ...selectedSeats } : {}; + if (Object.keys(tmp).length >= 5) { + toast.error("Maximum 5 seats can be selected"); + return; + } + if (tmp[seat.seatNumber]) { + delete tmp[seat.seatNumber]; + } else { + tmp[seat.seatNumber] = { ...seat }; + } + setSelectedSeats(tmp); + }; + + const bookSeats = async () => { + if (!totalPrice) return; + let arr = Object.values(selectedSeats).map((seat) => seat.id); + const resp = await fetch("https://codebuddy.review/submit", { + method: "POST", + body: JSON.stringify(arr), + }); + resp.json().then( + () => { + toast.success("Seats have been booked!"); + }, + (err) => { + console.err("POST API SEND ERROR:", err); + }, + ); + }; + + return ( +
+
+
Rows:
+ {/*
+
3 ? "" : " elem-disabled")} + onClick={() => updateRowCount(rows - 1)} + > + - +
+
{rows}
+
updateRowCount(rows + 1)} + > + + +
+
*/} +
+ + { + 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; 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}

+ +
+ ))}
);