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

Set char limit on rich text #662

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

chiragchhatrala
Copy link
Collaborator

@chiragchhatrala chiragchhatrala commented Jan 7, 2025

Summary by CodeRabbit

  • New Features

    • Added character count functionality to Rich Text Area Input.
    • Enabled character limit configuration for rich text fields.
  • Improvements

    • Implemented real-time character usage feedback.
    • Set default maximum character limit of 2000 for rich text fields.

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

The pull request introduces character limit functionality for rich text input fields. A new prop maxCharLimit is added to the RichTextAreaInput component to enable character counting. The FieldOptions component is updated to support character limits for rich text field types, with a default limit of 2000 characters. This enhancement provides users with real-time feedback on character usage across rich text input fields.

Changes

File Change Summary
client/components/forms/RichTextAreaInput.client.vue - Added maxCharLimit prop
- Implemented character count computation
- Added conditional rendering for character count display
client/components/open/forms/fields/components/FieldOptions.vue - Extended max_char_limit input field rendering to include rich_text type
- Added default max_char_limit: 2000 for rich text fields

Sequence Diagram

sequenceDiagram
    participant User
    participant RichTextInput
    participant CharCounter
    
    User->>RichTextInput: Enters text
    RichTextInput->>CharCounter: Calculate current characters
    CharCounter-->>RichTextInput: Return character count
    RichTextInput->>User: Display character count (X/Max)
Loading

Poem

🐰 Hop, hop, coding with glee,
Character limits now set us free!
Rich text fields count each letter's dance,
Two thousand chars at just a glance!
Coding magic, rabbit's delight! 🥕


📜 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 8a41e0f and d368395.

📒 Files selected for processing (1)
  • client/components/forms/RichTextAreaInput.client.vue (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/components/forms/RichTextAreaInput.client.vue
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build the Nuxt app

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

@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: 3

🧹 Nitpick comments (2)
client/components/open/forms/fields/components/FieldOptions.vue (1)

844-846: Default character limit aligns with other field types.

The default character limit of 2000 for rich text fields matches the limits set for other text-based fields, maintaining consistency across the application.

However, consider extracting these magic numbers into named constants to improve maintainability.

 export default {
   data() {
     return {
+      DEFAULT_CHAR_LIMIT: 2000,
       typesWithoutPlaceholder: ['date', 'checkbox', 'files'],
       // ...
     }
   },
   methods: {
     setDefaultFieldValues() {
       const defaultFieldValues = {
         text: {
           multi_lines: false,
-          max_char_limit: 2000
+          max_char_limit: this.DEFAULT_CHAR_LIMIT
         },
         rich_text: {
-          max_char_limit: 2000
+          max_char_limit: this.DEFAULT_CHAR_LIMIT
         },
         email: {
-          max_char_limit: 2000
+          max_char_limit: this.DEFAULT_CHAR_LIMIT
         },
         url: {
-          max_char_limit: 2000
+          max_char_limit: this.DEFAULT_CHAR_LIMIT
         },
         // ...
       }
     }
   }
 }
client/components/forms/RichTextAreaInput.client.vue (1)

45-52: Enhance character count display with visual feedback.

Consider adding visual feedback when approaching or exceeding the character limit:

  • Color coding (green/yellow/red) based on usage percentage
  • Visual indicator when limit is exceeded
 <template v-if="maxCharLimit && showCharLimit" #bottom_after_help>
   <small :class="[
     theme.default.help,
+    {
+      'text-red-500': charCount > maxCharLimit,
+      'text-yellow-500': charCount >= maxCharLimit * 0.9 && charCount <= maxCharLimit,
+      'text-green-500': charCount < maxCharLimit * 0.9
+    }
   ]">
     {{ charCount }}/{{ maxCharLimit }}
   </small>
 </template>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cc62f61 and 8a41e0f.

📒 Files selected for processing (2)
  • client/components/forms/RichTextAreaInput.client.vue (3 hunks)
  • client/components/open/forms/fields/components/FieldOptions.vue (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build the Nuxt app
🔇 Additional comments (3)
client/components/open/forms/fields/components/FieldOptions.vue (1)

555-555: LGTM! Character limit support added for rich text fields.

The template correctly includes 'rich_text' in the list of field types that support character limits, maintaining consistency with other text-based field types.

client/components/forms/RichTextAreaInput.client.vue (2)

38-41: LGTM! Good defensive programming.

The conditional checks for slot existence (v-if="$slots.help" and v-if="$slots.error") prevent rendering empty slots.

Also applies to: 54-57


132-134: 🛠️ Refactor suggestion

Improve character counting accuracy and performance.

The current implementation has several potential issues:

  1. HTML entities (e.g., &nbsp;) are counted as multiple characters
  2. Unicode characters and emojis might not be counted correctly
  3. Regular expression performance might degrade with large content

Consider using DOMParser for more accurate character counting:

 const charCount = computed(() => {
-  return compVal.value ? compVal.value.replace(/<[^>]*>/g, '').trim().length : 0
+  if (!compVal.value) return 0;
+  const parser = new DOMParser();
+  const doc = parser.parseFromString(compVal.value, 'text/html');
+  return doc.body.textContent.trim().length;
 })

Let's verify the performance impact with different content sizes:

@@ -552,7 +552,7 @@
@update:model-value="onFieldHelpPositionChange"
/>

<template v-if="['text', 'number', 'url', 'email'].includes(field.type)">
<template v-if="['text', 'rich_text', 'number', 'url', 'email'].includes(field.type)">
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing prop definition and character limit enforcement in RichTextAreaInput

  • showCharLimit is used in template but not defined as a prop
  • Character limit is displayed but not enforced through validation or input restriction
🔗 Analysis chain

Verify integration with RichTextAreaInput component.

The changes look good, but we should verify that the RichTextAreaInput component correctly handles these character limit properties.

Also applies to: 844-846

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that RichTextAreaInput component handles maxCharLimit and showCharLimit props

# Search for RichTextAreaInput component definition
echo "Searching for RichTextAreaInput component definition..."
ast-grep --pattern 'export default {
  name: "RichTextAreaInput",
  $$$
}'

# Search for maxCharLimit and showCharLimit prop definitions
echo "Searching for character limit prop definitions..."
rg -A 5 'props.*\{' client/components/**/RichTextAreaInput*.vue

# Search for character limit usage in template
echo "Searching for character limit usage in template..."
rg -A 5 'maxCharLimit|showCharLimit' client/components/**/RichTextAreaInput*.vue

Length of output: 1895


Script:

#!/bin/bash
# Search for showCharLimit prop and charCount implementation
echo "Searching for showCharLimit prop..."
rg -A 2 'showCharLimit.*\{' client/components/forms/RichTextAreaInput.client.vue

echo "Searching for charCount implementation..."
rg -A 5 'charCount' client/components/forms/RichTextAreaInput.client.vue

echo "Searching for validation or restriction logic..."
rg -A 10 'maxCharLimit' client/components/forms/RichTextAreaInput.client.vue

Length of output: 1305

@@ -59,6 +76,7 @@ import registerMentionExtension from '~/lib/quill/quillMentionExtension.js'

const props = defineProps({
...inputProps,
maxCharLimit: { type: Number, required: false, default: null },
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for maxCharLimit prop.

The maxCharLimit prop should validate:

  • Non-negative numbers
  • Reasonable maximum value to prevent performance issues
-  maxCharLimit: { type: Number, required: false, default: null },
+  maxCharLimit: {
+    type: Number,
+    required: false,
+    default: null,
+    validator: (value) => {
+      return value === null || (value > 0 && value <= 100000);
+    }
+  },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
maxCharLimit: { type: Number, required: false, default: null },
maxCharLimit: {
type: Number,
required: false,
default: null,
validator: (value) => {
return value === null || (value > 0 && value <= 100000);
}
},

Comment on lines +38 to +60
<template
v-if="$slots.help"
#help
>
<slot name="help" />
</template>
<template #error>

<template
v-if="maxCharLimit && showCharLimit"
#bottom_after_help
>
<small :class="theme.default.help">
{{ charCount }}/{{ maxCharLimit }}
</small>
</template>

<template
v-if="$slots.error"
#error
>
<slot name="error" />
</template>

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Prevent input when character limit is exceeded.

Currently, the component only displays the character count but doesn't prevent users from exceeding the limit. Consider adding an input prevention mechanism:

 <QuillyEditor
   :id="id ? id : name"
   ref="editor"
   v-model="compVal"
   :options="quillOptions"
   :disabled="disabled"
   :placeholder="placeholder"
   :style="inputStyle"
+  @text-change="handleTextChange"
 />

+const handleTextChange = (delta, oldDelta, source) => {
+  if (source === 'user' && props.maxCharLimit && charCount.value > props.maxCharLimit) {
+    // Revert the change
+    editor.value.quill.history.undo();
+  }
+};

Committable suggestion skipped: line range outside the PR's diff.

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.

1 participant