Skip to content

Commit

Permalink
Upgrade package & view perf
Browse files Browse the repository at this point in the history
  • Loading branch information
slhmy committed Feb 7, 2024
1 parent 76784da commit af82017
Show file tree
Hide file tree
Showing 15 changed files with 2,623 additions and 2,000 deletions.
4,149 changes: 2,376 additions & 1,773 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.64",
"@types/node": "^18.0.0",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.6",
"axios": "^1.3.4",
"framer-motion": "^10.16.1",
"i18next": "^23.5.1",
"monaco-editor": "^0.39.0",
"msw": "^1.1.0",
"msw": "^2.1.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^13.2.2",
Expand Down Expand Up @@ -70,15 +70,15 @@
"devDependencies": {
"@tailwindcss/typography": "^0.5.10",
"@types/redux-logger": "^3.0.9",
"@vitejs/plugin-react": "^2.0.1",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.15",
"daisyui": "^4.6.0",
"eslint-config-react-app": "^7.0.1",
"postcss": "^8.4.28",
"prettier": "3.0.2",
"prettier-plugin-tailwindcss": "^0.5.3",
"tailwindcss": "^3.3.3",
"vite": "^3.0.7"
"vite": "^5.0.12"
},
"msw": {
"workerDirectory": "public"
Expand Down
170 changes: 77 additions & 93 deletions public/mockServiceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
/* tslint:disable */

/**
* Mock Service Worker (1.1.0).
* Mock Service Worker (2.1.7).
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
*/

const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'
const INTEGRITY_CHECKSUM = '223d191a56023cd36aa88c802961b911'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()

self.addEventListener('install', function () {
Expand Down Expand Up @@ -86,12 +87,6 @@ self.addEventListener('message', async function (event) {

self.addEventListener('fetch', function (event) {
const { request } = event
const accept = request.headers.get('accept') || ''

// Bypass server-sent events.
if (accept.includes('text/event-stream')) {
return
}

// Bypass navigation requests.
if (request.mode === 'navigate') {
Expand All @@ -112,29 +107,8 @@ self.addEventListener('fetch', function (event) {
}

// Generate unique request ID.
const requestId = Math.random().toString(16).slice(2)

event.respondWith(
handleRequest(event, requestId).catch((error) => {
if (error.name === 'NetworkError') {
console.warn(
'[MSW] Successfully emulated a network error for the "%s %s" request.',
request.method,
request.url,
)
return
}

// At this point, any exception indicates an issue with the original request/response.
console.error(
`\
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
request.method,
request.url,
`${error.name}: ${error.message}`,
)
}),
)
const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId))
})

async function handleRequest(event, requestId) {
Expand All @@ -146,21 +120,24 @@ async function handleRequest(event, requestId) {
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
;(async function () {
const clonedResponse = response.clone()
sendToClient(client, {
type: 'RESPONSE',
payload: {
requestId,
type: clonedResponse.type,
ok: clonedResponse.ok,
status: clonedResponse.status,
statusText: clonedResponse.statusText,
body:
clonedResponse.body === null ? null : await clonedResponse.text(),
headers: Object.fromEntries(clonedResponse.headers.entries()),
redirected: clonedResponse.redirected,
const responseClone = response.clone()

sendToClient(
client,
{
type: 'RESPONSE',
payload: {
requestId,
isMockedResponse: IS_MOCKED_RESPONSE in response,
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
body: responseClone.body,
headers: Object.fromEntries(responseClone.headers.entries()),
},
},
})
[responseClone.body],
)
})()
}

Expand Down Expand Up @@ -196,20 +173,20 @@ async function resolveMainClient(event) {

async function getResponse(event, client, requestId) {
const { request } = event
const clonedRequest = request.clone()

// 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()

function passthrough() {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const headers = Object.fromEntries(clonedRequest.headers.entries())
const headers = Object.fromEntries(requestClone.headers.entries())

// Remove MSW-specific request headers so the bypassed requests
// comply with the server's CORS preflight check.
// Operate with the headers as an object because request "Headers"
// are immutable.
delete headers['x-msw-bypass']
// 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']

return fetch(clonedRequest, { headers })
return fetch(requestClone, { headers })
}

// Bypass mocking when the client is not active.
Expand All @@ -227,31 +204,36 @@ async function getResponse(event, client, requestId) {

// Bypass requests with the explicit bypass header.
// Such requests can be issued by "ctx.fetch()".
if (request.headers.get('x-msw-bypass') === 'true') {
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 clientMessage = await sendToClient(client, {
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
mode: request.mode,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: await request.text(),
bodyUsed: request.bodyUsed,
keepalive: request.keepalive,
const requestBuffer = await request.arrayBuffer()
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: requestBuffer,
keepalive: request.keepalive,
},
},
})
[requestBuffer],
)

switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
Expand All @@ -261,21 +243,12 @@ async function getResponse(event, client, requestId) {
case 'MOCK_NOT_FOUND': {
return passthrough()
}

case 'NETWORK_ERROR': {
const { name, message } = clientMessage.data
const networkError = new Error(message)
networkError.name = name

// Rejecting a "respondWith" promise emulates a network error.
throw networkError
}
}

return passthrough()
}

function sendToClient(client, message) {
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()

Expand All @@ -287,17 +260,28 @@ function sendToClient(client, message) {
resolve(event.data)
}

client.postMessage(message, [channel.port2])
client.postMessage(
message,
[channel.port2].concat(transferrables.filter(Boolean)),
)
})
}

function sleep(timeMs) {
return new Promise((resolve) => {
setTimeout(resolve, timeMs)
async function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced 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()
}

const mockedResponse = new Response(response.body, response)

Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})
}

async function respondWithMock(response) {
await sleep(response.delay)
return new Response(response.body, response)
return mockedResponse
}
10 changes: 8 additions & 2 deletions src/components/ProblemTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,19 @@ const ProblemTable: React.FC<ProblemTableProps> = (props) => {
</thead>
<tbody>
{props.data.map((problemInfo) => (
<tr className="hover" onClick={() => navigate(problemInfo.slug)}>
<tr
key={problemInfo.slug}
className="hover"
onClick={() => navigate(problemInfo.slug)}
>
<th>{problemInfo.slug}</th>
<td>{problemInfo.title}</td>
<td>
<div className="space-x-2">
{problemInfo.tags.map((tag) => (
<div className="badge badge-outline">{tag.name}</div>
<div key={tag.slug} className="badge badge-outline">
{tag.name}
</div>
))}
</div>
</td>
Expand Down
15 changes: 14 additions & 1 deletion src/components/SubmissionTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ export interface SubmissionTableProps {
className?: string;
}

function getBadgeColorClasses(status: string): string {
switch (status) {
case "finished":
return "badge-success";
case "pending":
return "badge-warning";
case "wrong answer":
return "badge-error";
default:
return "";
}
}

const SubmissionTable: React.FC<SubmissionTableProps> = (props) => {
const navigate = useNavigate();

Expand All @@ -40,7 +53,7 @@ const SubmissionTable: React.FC<SubmissionTableProps> = (props) => {
<div
className={joinClasses(
"badge badge-outline",
submission.status === "finished" ? "badge-success" : "",
getBadgeColorClasses(submission.status),
)}
>
{submission.status}
Expand Down
Loading

0 comments on commit af82017

Please sign in to comment.