Skip to content

Conversation

dwang3851
Copy link
Contributor

@dwang3851 dwang3851 commented Mar 30, 2025

Description

Passing cuds through session storage prevents the cookie that the cuds were previously passed through from overflowing.

Motivation and Context

Resolves issue #2274

How Has This Been Tested?

Tested locally by creating missing submissions for >400 students.
image

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • I have run rubocop and erblint for style check. If you haven't, run overcommit --install && overcommit --sign to use pre-commit hook for linting
  • My change requires a change to the documentation, which is located at Autolab Docs
  • I have updated the documentation accordingly, included in this PR

Other issues / help required

If unsure, feel free to submit first and we'll help you along.

Copy link
Contributor

coderabbitai bot commented Mar 30, 2025

📝 Walkthrough

Walkthrough

The changes rework how missing student IDs are handled during submission creation. The previous approach, which passed missing IDs as URL parameters, has been replaced with a session storage mechanism. A new JavaScript function in the missing submissions view collects the IDs and stores them, while the submission creation view now retrieves these stored IDs during the page load, adjusts the form elements accordingly, and updates the URL with the retrieved IDs.

Changes

File(s) Change Summary
app/views/submissions/missing.html.erb Added a new JavaScript function submitMissingIds that collects missing student IDs from the @missing array, stores them as a JSON string in session storage, and redirects the user to the submission creation page. The direct URL parameter usage has been removed, with a placeholder link ("#") now in place.
app/views/submissions/new.html.erb Modified the check for course_user_datum_id from nil? to blank?. Introduced a JavaScript block that runs on DOMContentLoaded to retrieve stored IDs from session storage, update the input field for course_user_datum_id, toggle visibility of related form sections, and adjust the window location to include the retrieved IDs as a query parameter. A new div for stored IDs display was also added.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant M as Missing Submissions Page
    participant JS as JavaScript
    participant S as sessionStorage
    participant N as New Submission Page

    U->>M: Click "Fill In Empty Submissions"
    M->>JS: Trigger submitMissingIds()
    JS->>S: Store missing student IDs (JSON)
    JS->>M: Redirect to submission creation page
    U->>N: Load New Submission Page
    N->>JS: DOMContentLoaded event triggers
    JS->>S: Retrieve stored IDs
    JS-->>N: Update input field, toggle display, modify URL with IDs
Loading

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

Copy link
Contributor

@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 (3)
app/views/submissions/missing.html.erb (1)

18-25: Well-implemented session storage solution

The submitMissingIds function effectively collects all missing student IDs, stores them in session storage as JSON, and redirects to the submission creation page. This is a good approach to handle potentially large data sets that would exceed URL parameter or cookie size limitations.

A few suggestions for improvement:

  • Consider adding error handling in case the JSON stringification fails
  • Add a user feedback mechanism (like a loading spinner) during the redirect process, especially for large datasets
function submitMissingIds() {
    var ids = [<%= @missing.map { |u| u[:id] }.join(',') %>];
    var url = '<%= new_course_assessment_submission_path(@course, @assessment) %>';
+   try {
        sessionStorage.setItem('course_user_datum_ids', JSON.stringify(ids));
+       // Optional: Show loading indicator for better UX
+       // document.getElementById('loading-indicator').style.display = 'block';
        window.location.href = url;
+   } catch (e) {
+       alert('Failed to process student IDs. Please try with fewer students or contact support.');
+       console.error(e);
+   }
}
app/views/submissions/new.html.erb (2)

19-37: Well-structured session storage retrieval mechanism

This code effectively retrieves the IDs stored in session storage, updates the form, and modifies the UI accordingly. The approach is sound and addresses the PR objectives.

A few observations:

  1. Line 35 updates window.location.href which causes a page reload after the DOM has already been manipulated. This could lead to a flash of content where users briefly see the form before redirect.
  2. The code does not handle potential JSON parsing errors.
  3. The code does not validate that the retrieved IDs are valid before using them.
document.addEventListener('DOMContentLoaded', function() {
    var storedIds = sessionStorage.getItem('course_user_datum_ids');
    if (storedIds) {
        sessionStorage.removeItem('course_user_datum_ids');
+       try {
            var ids = JSON.parse(storedIds);
+           if (!Array.isArray(ids) || ids.length === 0) {
+               console.error('Retrieved IDs are not in expected format:', ids);
+               return;
+           }
            document.querySelector('input[name="submission[course_user_datum_id]"]').value = ids.join(',');
            var studentSelectArea = document.getElementById('student_select_area');
            if (studentSelectArea) {
                studentSelectArea.style.display = 'none';
                var storedIdsArea = document.getElementById('stored_ids_area');
                if (storedIdsArea) {
                    storedIdsArea.style.display = 'block';
+                   // Optionally: Show a count of selected students
+                   storedIdsArea.textContent = ids.length + ' students selected';
                }
            }
-           window.location.href = window.location.pathname + '?course_user_datum_id=' + ids.join(',');
+           // Use history.replaceState instead of location.href to avoid page reload
+           if (!window.location.search.includes('course_user_datum_id=')) {
+               var newUrl = window.location.pathname + '?course_user_datum_id=' + ids.join(',');
+               history.replaceState(null, '', newUrl);
+           }
+       } catch (e) {
+           console.error('Error processing stored IDs:', e);
+       }
    }
});

40-54: Clear UI structure for showing student selection or stored IDs

The UI structure is well-organized with appropriate conditional rendering. The added stored_ids_area div provides a designated place to show information about the selected students from session storage.

Consider enhancing this section to:

  1. Show the number of selected students in the stored_ids_area
  2. Allow users to clear the selection and return to individual student selection
<% if params[:course_user_datum_id].nil? %>
  <div id="student_select_area">
    <div class="input-field">
      <input type="text" size="3" id="student_autocomplete" class="autocomplete" autocomplete="off">
      <label for="student_autocomplete">Start typing student name or email</label>
    </div>
    <%= f.hidden_field(:course_user_datum_id) %>
  </div>

  <div id="stored_ids_area" style="display: none;">
+   <div>Multiple students selected (<span id="student-count">0</span>)</div>
+   <a href="#" onclick="clearSelection(); return false;" class="btn-small">Clear Selection</a>
  </div>
<% else %>
  <%= @cuds.collect(&:email).join(", ") %>
  <input type='hidden' name='submission[course_user_datum_id]' value='<%= @cuds.collect(&:id).join(',') %>'>
<% end %>

Add this JavaScript function to handle clearing the selection:

function clearSelection() {
  document.querySelector('input[name="submission[course_user_datum_id]"]').value = '';
  document.getElementById('student_select_area').style.display = 'block';
  document.getElementById('stored_ids_area').style.display = 'none';
  history.replaceState(null, '', window.location.pathname);
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 398b5c5 and df7468d.

📒 Files selected for processing (2)
  • app/views/submissions/missing.html.erb (1 hunks)
  • app/views/submissions/new.html.erb (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: test
🔇 Additional comments (2)
app/views/submissions/missing.html.erb (1)

14-16: Good change to prevent URL parameter overflows

This change replaces a direct URL with many parameters to an onclick handler that will use session storage instead. This addresses the cookie overflow issue mentioned in PR #2274 by avoiding the URL parameter size limitations when dealing with a large number of student IDs.

app/views/submissions/new.html.erb (1)

15-17: Improved condition check with blank? instead of nil?

Good change from nil? to blank? which is more robust as it will handle empty strings and other falsy values in addition to nil.

@KesterTan KesterTan requested review from a team and coder6583 and removed request for a team April 21, 2025 20:06
Copy link
Contributor

@coder6583 coder6583 left a comment

Choose a reason for hiding this comment

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

LGTM, but I think you should resolve the errors in the Ruby on Rails CI.

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