Skip to content

feature: allow users to paste a multi line string into the options #223

Merged
fsargent merged 2 commits intomainfrom
feat/create-paste-multi-line
Feb 12, 2025
Merged

feature: allow users to paste a multi line string into the options #223
fsargent merged 2 commits intomainfrom
feat/create-paste-multi-line

Conversation

@fsargent
Copy link
Contributor

@fsargent fsargent commented Feb 12, 2025

field and convert it into multiple bullet points
Resolves #222

Summary by Sourcery

New Features:

  • Users can now paste multi-line text into the option fields to quickly create multiple options.

…eld and convert it into multiple bullet points
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Feb 12, 2025

Reviewer's Guide by Sourcery

This PR enhances the poll options functionality by enabling users to paste multi-line strings, which are then split into multiple options. It implements a paste handler to process the pasted text and updates the addChoiceField function to accommodate preset values when creating new options.

Sequence diagram for multi-line paste handling

sequenceDiagram
  actor User
  participant "Poll Options Input" as Input
  participant "Paste Event Handler" as Handler
  participant "addChoiceField" as AddOption

  User->>Input: Paste multi-line string
  Input->>Handler: Trigger paste event
  Handler->>Handler: Retrieve clipboardData
  Handler->>Handler: Check if pastedData contains newlines
  alt Multi-line detected
    Handler->>Handler: Prevent default paste
    Handler->>Handler: Split text into lines
    Handler->>Input: Set current input value to first line
    loop For each additional line
      Handler->>AddOption: addChoiceField(line)
    end
  else Single line
    Handler->>Input: Normal paste handling
  end
Loading

File-Level Changes

Change Details Files
Implemented multi-line paste handling for poll option inputs
  • Added an event listener for paste events on input elements within the poll options container
  • Detected and prevented the default paste behavior when newlines are present in the pasted content
  • Split the pasted string into individual lines and cleaned each line by removing any bullet point characters
  • Set the first line into the current input field and created new option fields for the remaining lines
approval_polls/staticfiles/create.js
Enhanced addChoiceField function to accept default option values
  • Modified the addChoiceField function to include an optional parameter for a preset value
  • Updated the input field generation to set the value attribute based on the provided argument
approval_polls/staticfiles/create.js

Assessment against linked issues

Issue Objective Addressed Explanation
#222 Users should be able to copy paste a bullet point list into the choices section
#222 The pasted list should be converted into multiple choices automatically

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes add functionality to handle pasted input within the poll options section. When a user pastes text into an option field, the code checks for newline characters. If found, it prevents the default action, inserts the first line into the current input, and creates additional input fields for subsequent lines using the modified addChoiceField function, which now accepts an optional value parameter.

Changes

File Change Summary
approval_polls/staticfiles/create.js • Added a paste event handler on text inputs within the poll options container.
• Prevents default paste when newlines are detected, splitting pasted content.
• Updated addChoiceField to accept an optional parameter to set the input value for new choice fields.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant Input as Input Field
    participant Handler as Paste Event Handler
    participant Function as addChoiceField()

    User->>Input: Paste text with newlines
    Input->>Handler: Trigger paste event
    Handler->>Handler: Check for newline characters
    alt Newlines detected
        Handler->>Input: Set first line as current input value
        Handler->>Function: For each extra line, call addChoiceField(line)
    else No newlines
        Handler->>Input: Process default paste behavior
    end
Loading

Poem

I'm a little rabbit, hopping with delight,
Spreading fresh code vibes in the text input light.
Pasting lines like carrots from a magical patch,
New fields appear with every line you dispatch!
Hooray to changes that make our poll options bright!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 115fb5f and dff65c4.

📒 Files selected for processing (1)
  • approval_polls/staticfiles/create.js (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @fsargent - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a more specific selector to the paste event listener to only target the option inputs you want to enable this feature on.
  • It might be good to have a configuration option to disable the multi-line paste functionality.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +19 to +28
pollOptions.container.on("paste", "input[type=text]", function (e) {
// Get the pasted content
const pastedData = e.originalEvent.clipboardData.getData("text");

// Check if the pasted content contains newlines
if (pastedData.includes("\n")) {
e.preventDefault(); // Prevent default paste

// Split the pasted content into lines
const lines = pastedData
Copy link
Contributor

Choose a reason for hiding this comment

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

issue: Check for empty pasted lines before setting the value.

If the pasted data consists entirely of newlines or spaces (resulting in an empty array after filtering), then accessing lines[0] may assign undefined to the input value. Consider adding a guard to ensure that there is at least one non-empty line before setting the value and creating additional options.

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: 1

🔭 Outside diff range comments (1)
approval_polls/staticfiles/create.js (1)

46-66: ⚠️ Potential issue

Prevent XSS by escaping the value parameter.

The value parameter is inserted directly into the HTML template without escaping, which could lead to XSS attacks.

Add value escaping:

   const addChoiceField = (value = "") => {
     lastId++;
+    // Escape HTML special characters
+    const escapedValue = value
+      .replace(/&/g, "&amp;")
+      .replace(/</g, "&lt;")
+      .replace(/>/g, "&gt;")
+      .replace(/"/g, "&quot;")
+      .replace(/'/g, "&#039;");
+
     const newOption = `
       <div class="mb-3 poll-option">
         <label for="choice${lastId}" class="form-label">Option ${lastId}</label>
         <div class="input-group">
           <input type="text"
                  class="form-control"
                  id="choice${lastId}"
                  name="choice${lastId}"
                  maxlength="100"
                  placeholder="Option Name"
-                 value="${value}">
+                 value="${escapedValue}">
           <button class="btn btn-outline-primary remove-choice" type="button" title="Remove Choice">
             <i class="fa fa-times"></i>
           </button>
         </div>
       </div>
     `;
     pollOptions.container.append(newOption);
   };
🧹 Nitpick comments (1)
approval_polls/staticfiles/create.js (1)

18-41: Consider enhancing the paste handling.

The paste handling implementation is good but could be improved in a few ways:

  1. Consider handling tab-separated values
  2. Add support for copying from spreadsheets
  3. Consider adding a maximum limit to prevent too many options

Here's an enhanced implementation:

     pollOptions.container.on("paste", "input[type=text]", function (e) {
       const pastedData = e.originalEvent.clipboardData.getData("text");
 
-      if (pastedData.includes("\n")) {
+      if (pastedData.includes("\n") || pastedData.includes("\t")) {
         e.preventDefault();
 
         // Split the pasted content into lines
         const lines = pastedData
-          .split("\n")
+          .split(/[\n\t]/)
           .map((line) => line.replace(/^(-|•|\*|⁃|◦|▪︎|●|■)+/, "").trim())
           .filter((line) => line.length > 0);
 
+        // Limit the number of options
+        const MAX_OPTIONS = 50;
+        if (lines.length > MAX_OPTIONS) {
+          alert(`Maximum ${MAX_OPTIONS} options allowed`);
+          return;
+        }
+
         // Set the first line in the current input
         $(this).val(lines[0]);
 
         // Create new options for the remaining lines
         lines.slice(1).forEach((line) => {
           addChoiceField(line);
         });
       }
     });
🧰 Tools
🪛 Biome (1.9.4)

[error] 30-30: A character class cannot match a character and a combining character.

A character and a combining character forms a new character. Replace the character class with an alternation.

(lint/suspicious/noMisleadingCharacterClass)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 24fb9cb and 115fb5f.

📒 Files selected for processing (1)
  • approval_polls/staticfiles/create.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
approval_polls/staticfiles/create.js

[error] 30-30: A character class cannot match a character and a combining character.

A character and a combining character forms a new character. Replace the character class with an alternation.

(lint/suspicious/noMisleadingCharacterClass)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: review_app

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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.

Paste a bullet point list into the choices section

1 participant