Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor WebApp for improved readability and structure #8

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

davidescapolan01
Copy link
Contributor

@davidescapolan01 davidescapolan01 commented Apr 10, 2025

What this PR does

This PR refactors several parts of the code related to connection status handling, condition simplification, and event logic inside the WebApp.
It improves readability by reducing nesting, grouping related logic, and replacing unnecessary try/catch blocks with proper conditional checks.


Why it's needed

Some sections of the code used unnecessary try/catch blocks or scattered related logic across conditionals.
These changes streamline the logic, make the behavior easier to follow, and reduce potential confusion for future maintenance.


How to test

  • Trigger the success and error states in the connection status to verify correct color changes and that success messages disappear after 3 seconds.
  • Start an exam to verify the countdown behavior works as expected.
  • Run through the exam evaluation flow and check that polling behaves correctly for all statuses.

Expected result

  • The UI updates clearly reflect the current status (success/error).
  • Countdown logic works with clearer flow.
  • Polling and status logic handles all cases consistently with better structure.

Comment for the Contributor

Hey! 👋 Just wanted to streamline a few things in the logic—especially around how conditions are written and grouped.
This should make the flow more readable and a bit easier to maintain.
Let me know if you want me to split anything or adjust further!

Summary by CodeRabbit

  • Refactor

    • Streamlined connection status notifications for clearer feedback.
    • Simplified browser identification checks to improve overall stability.
  • Style

    • Made cosmetic formatting improvements for increased code consistency and readability.

Replaced try/catch with a safer and cleaner conditional check using optional chaining.
Using try/catch for value assignment is not considered good practice, especially when
the value can be checked with condition.
Replaced nested conditionals with simpler, more readable else-if structure.
This reduces indentation levels and improves clarity when checking for exam duration and start time.
Reorganized the logic to reduce nesting.
The counter is now checked first, and the exam starts when it reaches zero.
The button text is updated only when necessary, improving readability and flow.
Removed explicit check for 'EVALUATING' status. Now we only throw on
'EVALUATION_FAILED' or other unexpected statuses.
All other cases fall through to polling, making the logic cleaner and
easier to follow.
Moved the success timeout logic inside the success condition block
to improve readability and keep related logic together.
Copy link

coderabbitai bot commented Apr 10, 2025

Walkthrough

The changes refactor several JavaScript modules within the application. In the UI utilities component, redundant success handling code was removed and streamlined. Cosmetic formatting adjustments were applied across multiple modules, including the addition of spaces before parentheses in function declarations and event listener callbacks. The index module simplified error handling for retrieving the user agent by replacing a try-catch with a conditional check. Overall, the functionality remains unchanged while improving code readability and consistency.

Changes

File(s) Change Summary
app/public/js/components/ui-utils.js Removed redundant code in the showConnectionStatus function; integrated the setTimeout within the success condition to streamline background color setting.
app/public/js/exam.js Cosmetic formatting changes: added spaces before parentheses in function declarations and event listener callbacks; no logic was modified.
app/public/js/index.js Replaced the try-catch block for retrieving navigator.userAgent with a conditional check to verify the existence of navigator and its property; logs an error if unavailable.
app/public/js/results.js Cosmetic formatting changes: added spaces before parentheses in function declarations and event listener callbacks; no logic was modified.
app/public/js/answers.js Cosmetic formatting changes: added spaces before parentheses in function declarations and event listener callbacks; no logic was modified.
app/public/js/app.js Cosmetic formatting changes: added spaces before parentheses in function declarations for event listeners; no logic was modified.
app/public/js/feedback.js Cosmetic formatting changes: added spaces before parentheses in function declarations and event listener callbacks; no logic was modified.
app/public/js/panel-resizer.js Removed unnecessary blank lines and added a space before the opening parenthesis in the DOMContentLoaded event listener; no logic was modified.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ResultsHandler

    Client->>ResultsHandler: Request exam results
    alt Status is EVALUATION_FAILED
        ResultsHandler-->>Client: Throw evaluation failed error
    else Status is not EVALUATED
        ResultsHandler-->>Client: Throw "results not available" error
    else Status is EVALUATED but results missing
        Note right of ResultsHandler: Initiate polling for results
        ResultsHandler->>Client: Begin polling process
    end
Loading

Poem

I'm a rabbit hopping through code delight,
Bouncing past redundant blocks with all my might,
Formatting carrots lined up neat and clear,
Logical leaps in results that I cheer,
With each refactor, I hop on – oh, what a day! 🥕🐇

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

}

selectedLab.userAgent = userAgent;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we assignselectedLab.userAgent=navigator.userAgent; inside a if statement since userAgent not used anywhere else

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Absolutely.
I'll try this, evening if I have some time, to squeeze in this task

@@ -344,15 +344,13 @@ document.addEventListener('DOMContentLoaded', function() {
return response.json();
})
.then(data => {
if (data.status === 'EVALUATING') {
// Start polling if exam is being evaluated
startPolling(examId);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is needed for for refresh scenario in the result page. removing this causes any side effects ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so because the other cases don't match this one and the last else does exactly the same if I'm right.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh shut. You're actually right.
My bad the other scenario is with EVALUATED and not EVALUATING.
I'll rollback this one.

This reverts commit b65ad56.

The reverted commit introduced a bug where the state 'EVALUATING' was not
handled correctly.
Thisone fixes it rolling back the logit as it was befor that change.

How can we call that? A reverse typo? Let's just say I brainfarted: I
thought that the second `else if` was against 'EVALUATING'.
Too many hours coding, I'd say.

Thanks @nishanb for the catch! Updated accordingly.
Implemented the change suggested by @nishanb

Refs to commit 175670b
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
app/public/js/panel-resizer.js (2)

57-60: Optional Chaining Suggestion for ClientX Retrieval:
On line 58, consider using optional chaining to simplify the access of e.touches. This not only shortens the code but also improves readability.

Apply the following diff:

- this.startX = e.clientX || (e.touches && e.touches[0].clientX) || 0;
+ this.startX = e.clientX || e.touches?.[0]?.clientX || 0;
🧰 Tools
🪛 Biome (1.9.4)

[error] 58-58: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


75-83: Optional Chaining Suggestion in the drag Method:
Similarly, on line 79, using optional chaining for accessing e.touches can modernize the code and reduce the verbosity of manual checks.

Apply this diff:

- const clientX = e.clientX || (e.touches && e.touches[0].clientX) || 0;
+ const clientX = e.clientX || e.touches?.[0]?.clientX || 0;
🧰 Tools
🪛 Biome (1.9.4)

[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ca8416 and 126b2e3.

📒 Files selected for processing (6)
  • app/public/js/answers.js (6 hunks)
  • app/public/js/app.js (1 hunks)
  • app/public/js/feedback.js (2 hunks)
  • app/public/js/index.js (20 hunks)
  • app/public/js/panel-resizer.js (2 hunks)
  • app/public/js/results.js (9 hunks)
✅ Files skipped from review due to trivial changes (3)
  • app/public/js/app.js
  • app/public/js/answers.js
  • app/public/js/feedback.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • app/public/js/results.js
  • app/public/js/index.js
🧰 Additional context used
🪛 Biome (1.9.4)
app/public/js/panel-resizer.js

[error] 58-58: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 79-79: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (6)
app/public/js/panel-resizer.js (6)

10-25: Cosmetic Formatting in Constructor:
The removal of unnecessary blank lines and the consistent spacing in the constructor (affecting lines 12, 16, 19, 22, and 25) improves readability without altering functionality.


26-35: Cosmetic Formatting in the init Method:
Adjustments made on lines 28 and 35 (and similar spacing changes) help clarify the code structure while keeping the logic intact.


50-73: Cosmetic Formatting in the startDrag Method:
Minor spacing adjustments (e.g., on lines 53 and 56) enhance clarity in this method, ensuring a cleaner visual flow during drag initialization.

🧰 Tools
🪛 Biome (1.9.4)

[error] 58-58: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


112-121: Cosmetic Formatting in the stopDrag Method:
The removal or adjustment of extraneous blank lines (e.g., on lines 114, 118, and 121) improves code consistency and readability in this method.


127-131: Cosmetic Formatting in the resetPanels Method:
A minor formatting change on line 131 helps maintain a consistent code style.


139-151: Event Listener Formatting for DOMContentLoaded:
The addition of a space before the opening parenthesis in the callback registration for DOMContentLoaded (line 139 and onward) standardizes the code formatting.

@nishanb
Copy link
Owner

nishanb commented Apr 13, 2025

@davidescapolan01 thanks for these changes. I believe you have refactored the code and tested E2E. since we do not have any unit test or E2E test making sure it works before merging the changes !!

@davidescapolan01
Copy link
Contributor Author

davidescapolan01 commented Apr 13, 2025

@davidescapolan01 thanks for these changes. I believe you have refactored the code and tested E2E. since we do not have any unit test or E2E test making sure it works before merging the changes !!

Hm, actually I didn't — my bad!
I'm still figuring out how to do that.
I'm not very used to working on the Frontend, and the fact that I'm constantly switching between different machines doesn’t really help either.

Would it be okay if I mark this PR as a Draft and come back to it once I’ve managed to test it end-to-end?

Also, what kind of tests should I perform?
Do I need to create a test suite, or is manual testing enough for now?

I'm asking because I’m not sure I have the skills yet to write proper frontend tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants