Skip to content

feat: character limitations to free text question#4047

Merged
gupta-piyush19 merged 47 commits intoformbricks:mainfrom
DeepaPrasanna:feat/char-limit-to-text
Dec 9, 2024
Merged

feat: character limitations to free text question#4047
gupta-piyush19 merged 47 commits intoformbricks:mainfrom
DeepaPrasanna:feat/char-limit-to-text

Conversation

@DeepaPrasanna
Copy link
Contributor

@DeepaPrasanna DeepaPrasanna commented Oct 26, 2024

What does this PR do?

Fixes #3798
Given max length as 50 chars and min length as 3 chars. Please let me know if I need to change that.

https://www.loom.com/share/e53065dde39f40cd90a7f91dfefedef7?sid=493a8157-0972-48fe-ac5d-bd1c2956b598

Note: Please excuse the error shown at the last seconds in the video. The server kills frequently due to low ram issue, thats why the error failed to fetch shows

How should this be tested?

  • Add a question of type free text and type the characters. The input box will have a red border color if the characters are less than the min length and it will not let you add characters if it crosses max length

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read How we Code at Formbricks
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand bits
  • Ran pnpm build
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues
  • First PR at Formbricks? Please sign the CLA! Without it we wont be able to merge it 🙏

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Formbricks Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Enhanced character limit management for open text questions in surveys.
    • Added toggle options for enabling/disabling character limits on input fields.
    • Introduced real-time character count feedback for users.
  • Bug Fixes

    • Improved validation for character limit settings in survey questions.
  • Documentation

    • Updated localization files to include new keys for character limits in multiple languages.
  • Chores

    • Updated mock data structures to reflect new character limit properties for testing purposes.

@vercel
Copy link

vercel bot commented Oct 26, 2024

@DeepaPrasanna is attempting to deploy a commit to the formbricks Team on Vercel.

A member of the Team first needs to authorize it.

@CLAassistant
Copy link

CLAassistant commented Oct 26, 2024

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 26, 2024

Walkthrough

The pull request introduces significant modifications to enhance character limit management for open text questions within the survey editor. Key changes include the addition of two state variables, showCharLimits and isCharLimitEnabled, to the OpenQuestionForm component, which control the visibility and functionality of character limits. The handleInputChange function is updated to reset character limit attributes when the input type changes. A new useEffect hook is implemented to set isCharLimitEnabled based on the question object’s minLength and maxLength.

The ZSurveyOpenTextQuestion schema is updated to include a new charLimit property, which consists of optional fields for enabling character limits and specifying minimum and maximum lengths. Localization files for multiple languages are updated to include new keys related to character limits. Additionally, mock data structures in testing files are enhanced to reflect these changes, ensuring that the character limit functionality is well-integrated into the testing framework. Overall, these updates provide a comprehensive approach to managing character limits in open text questions across the application.

Assessment against linked issues

Objective Addressed Explanation
Add min and max limits to the free text field question (3798)
Ensure character limitations are configurable for questions (3798)

Possibly related PRs

Suggested labels

good first issue, hacktoberfest, 🕹️ oss.gg, 🕹️ 150 points

Suggested reviewers

  • jobenjada

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 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.

@github-actions
Copy link
Contributor

github-actions bot commented Oct 26, 2024

Thank you for following the naming conventions for pull request titles! 🙏

@github-actions github-actions bot added community request enhancement New feature or request low priority Created by Linear-GitHub Sync labels Oct 26, 2024
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: 2

🧹 Outside diff range and nitpick comments (3)
apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/OpenQuestionForm.tsx (2)

73-74: Implementation matches requirements but could be more flexible.

The addition of character limits aligns with the PR objectives. However, consider the following improvements:

  1. Make the limits configurable via props instead of hardcoding:
interface OpenQuestionFormProps {
+  headlineMaxLength?: number;
+  headlineMinLength?: number;
  // ... other props
}

// In component
<QuestionFormInput
  // ... other props
-  maxLength={50}
-  minLength={3}
+  maxLength={props.headlineMaxLength ?? 50}
+  minLength={props.headlineMinLength ?? 3}
/>

73-74: Enhance user experience with character limit feedback.

Users should be informed about the character limitations before hitting the limits.

Consider adding:

  1. Character count display
  2. Visual feedback when approaching limits
  3. Clear validation messages

Would you like me to provide an example implementation of these UX enhancements?

packages/ui/components/QuestionFormInput/index.tsx (1)

Line range hint 1-658: Consider adding unit tests for character limitations.

The implementation of character limitations is a critical feature that should be thoroughly tested.

Would you like me to help create unit tests for:

  • Minimum length validation
  • Maximum length validation
  • Error message display
  • Initial state validation
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ef7df0f and 0595259.

📒 Files selected for processing (2)
  • apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/OpenQuestionForm.tsx (1 hunks)
  • packages/ui/components/QuestionFormInput/index.tsx (5 hunks)
🔇 Additional comments (3)
apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/OpenQuestionForm.tsx (1)

73-74: Verify character limit handling in QuestionFormInput component.

Let's ensure the QuestionFormInput component properly handles these new props.

✅ Verification successful

QuestionFormInput component properly handles maxLength and minLength props

The verification confirms that the QuestionFormInput component correctly implements both maxLength and minLength validation:

  1. Props are properly defined in the interface and passed through to the component
  2. The component implements minLength validation through state management:
    if (minLength && value.length < minLength) {
      SetHasMinChars(false);
    } else {
      SetHasMinChars(true);
    }
  3. Both props are correctly passed to the underlying Input component:
    maxLength={maxLength ?? undefined}
    minLength={minLength ?? undefined}
  4. Invalid state is properly handled when minLength requirement isn't met:
    isInvalid={!!(... || (minLength && !hasMinChars))}

The implementation is complete and handles the character limits as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for QuestionFormInput implementation to verify proper handling of maxLength and minLength
ast-grep --pattern 'interface QuestionFormInputProps {
  $$$
}'

# Search for validation logic
rg -A 5 'maxLength|minLength' --type typescript

Length of output: 2133


Script:

#!/bin/bash
# Search for the implementation of QuestionFormInput to verify how maxLength and minLength are used
ast-grep --pattern 'function QuestionFormInput({$$$}) {
  $$$
}'

# Search for validation logic with proper file type
rg -A 5 'maxLength|minLength' --type ts --type tsx

Length of output: 147


Script:

#!/bin/bash
# Let's try to find the QuestionFormInput implementation and its usage of maxLength/minLength
cat packages/ui/components/QuestionFormInput/index.tsx

# Also search for any validation logic using ripgrep without file type specification
rg -A 5 'maxLength|minLength'

Length of output: 34506

packages/ui/components/QuestionFormInput/index.tsx (2)

62-63: LGTM: Props interface changes look good.

The addition of optional minLength and maxLength properties to QuestionFormInputProps interface is well-structured and follows TypeScript best practices.


592-592: 🛠️ Refactor suggestion

Verify error message display for minLength validation.

The isInvalid prop logic has been updated to include minLength validation, but there's no visible error message specifically for the minimum length requirement. Users won't know why their input is invalid.

Let's check if there are any error message components in the codebase:

Consider adding an error message for minimum length validation:

+ {minLength && !hasMinChars && (
+   <div className="mt-1 text-xs text-red-400">
+     Minimum {minLength} characters required
+   </div>
+ )}

Also applies to: 594-600

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0595259 and 7316c1f.

📒 Files selected for processing (1)
  • packages/ui/components/QuestionFormInput/index.tsx (5 hunks)
🔇 Additional comments (2)
packages/ui/components/QuestionFormInput/index.tsx (2)

62-63: LGTM: Interface changes are well-defined.

The new optional properties minLength and maxLength are properly typed and follow TypeScript conventions.


488-491: LGTM: Clean validation logic.

The minLength validation is implemented correctly and provides real-time feedback.

@jobenjada
Copy link
Member

Hey!

I'm sorry, the ticket isn't very useful.

Her is what we need:

To the Free Text Question Form, add a toggle:

image

And then store that in the survey object and use that in the surveys package ( under packages/survey ) to then limit the charactes in the TEXT INPUT field in the survey.

image

Only show the toggle for input type: Text (doesnt make sense for the others)

image

In the survey package, use the standard HTML error messages, if possible. Display the error message below the text area, if the text is not matching the length requirements on "next"

image

@jobenjada jobenjada marked this pull request as draft October 26, 2024 22:25
@DeepaPrasanna DeepaPrasanna marked this pull request as ready for review October 29, 2024 12:35
@DeepaPrasanna
Copy link
Contributor Author

DeepaPrasanna commented Oct 29, 2024

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

🧹 Outside diff range and nitpick comments (1)
packages/types/surveys/types.ts (1)

478-479: Add validation rules for length constraints.

The implementation of minLength and maxLength properties aligns with the PR objectives. However, consider adding validation rules to ensure data integrity.

Apply this diff to add validation rules:

-  minLength: z.number().optional(),
-  maxLength: z.number().optional(),
+  minLength: z.number().min(0).optional(),
+  maxLength: z.number().min(1).optional(),

Also consider adding a .superRefine() to validate that maxLength is greater than minLength when both are provided:

}).superRefine((val, ctx) => {
  if (val.minLength !== undefined && val.maxLength !== undefined && val.minLength >= val.maxLength) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Maximum length must be greater than minimum length",
      path: ["maxLength"],
    });
  }
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7316c1f and 97429b6.

📒 Files selected for processing (3)
  • apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/OpenQuestionForm.tsx (3 hunks)
  • packages/surveys/src/components/questions/OpenTextQuestion.tsx (3 hunks)
  • packages/types/surveys/types.ts (1 hunks)
🔇 Additional comments (3)
packages/surveys/src/components/questions/OpenTextQuestion.tsx (1)

Line range hint 95-137: Verify character limit constraints from PR objectives.

The PR objectives specify min=3 and max=50 characters, but the implementation allows for flexible limits. We should verify if these constraints are enforced at the schema/form level.

apps/web/app/(app)/(survey-editor)/environments/[environmentId]/surveys/[surveyId]/edit/components/OpenQuestionForm.tsx (2)

5-5: Imports are correctly added.

The import statements for useState, AdvancedOptionToggle, and Input are properly added and will allow the component to utilize state management and UI elements for the new features.

Also applies to: 13-13, 15-15


60-61: 🛠️ Refactor suggestion

Confirm resetting minLength and maxLength on input type change.

When the inputType changes, minLength and maxLength are set to undefined. If the user switches back to a text input, their previously entered character limits will be lost.

Consider preserving the character limit values when toggling between input types or informing the user that their character limits will be reset.

@jobenjada
Copy link
Member

The UX isn't ideal, mostly because people who'd fill out the survey when it has a max count are not informed that they've reached the max limit.

But this is a design short-coming on my end, so here are /award 750

thanks a lot for your good work!

@oss-gg
Copy link

oss-gg bot commented Oct 31, 2024

Awarding DeepaPrasanna: 750 points 🕹️ Well done! Check out your new contribution on oss.gg/DeepaPrasanna

@jobenjada jobenjada self-requested a review October 31, 2024 02:52
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

🧹 Outside diff range and nitpick comments (1)
packages/lib/survey/tests/__mock__/survey.mock.ts (1)

163-165: LGTM with a suggestion for test coverage.

The charLimit property is consistently implemented across all open text questions with appropriate structure. However, consider enhancing test coverage:

Consider adding test cases with charLimit.enabled: true and various character limit values to ensure the feature works correctly when enabled. For example:

 {
   id: "q1",
   type: TSurveyQuestionTypeEnum.OpenText,
   inputType: "text",
   headline: { default: "What is your favorite color?" },
   required: true,
   charLimit: {
-    enabled: false
+    enabled: true,
+    minCharacters: 3,
+    maxCharacters: 50
   },

Also applies to: 316-318, 344-346, 378-380, 442-444

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c28bf91 and c29040a.

📒 Files selected for processing (2)
  • packages/lib/response/tests/__mocks__/data.mock.ts (1 hunks)
  • packages/lib/survey/tests/__mock__/survey.mock.ts (5 hunks)
🔇 Additional comments (1)
packages/lib/response/tests/__mocks__/data.mock.ts (1)

403-405: LGTM: Character limit property correctly structured.

The addition of the charLimit property with enabled: false is well-structured and provides appropriate default values for testing backward compatibility.

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 and nitpick comments (2)
apps/web/app/(app)/(onboarding)/environments/[environmentId]/xm-templates/lib/xm-templates.ts (1)

Line range hint 54-439: Consider adding validation rules in templates

While the character limit infrastructure is in place, consider pre-configuring some templates with enabled character limits and reasonable defaults based on their specific use cases. For example:

  • NPS feedback questions might benefit from a maximum limit to encourage concise feedback
  • CSAT improvement suggestions could have a minimum limit to ensure meaningful responses

Example for NPS survey's second question:

   {
     id: createId(),
     type: TSurveyQuestionTypeEnum.OpenText,
     headline: { default: translate("nps_survey_question_2_headline", locale) },
     required: false,
     inputType: "text",
     charLimit: {
-      enabled: false,
+      enabled: true,
+      max: 500  // Set a reasonable maximum for detailed feedback
     },
   },
packages/lib/templates.ts (1)

OpenText questions need character limit configuration update

The implementation needs to be modified to include proper character limits. According to the type definition:

  1. charLimit should be an object with:
    • enabled: true (to enable the limits)
    • min: 3 (minimum 3 characters)
    • max: 50 (maximum 50 characters)

The current implementation only sets enabled: false which effectively disables character limits. This should be updated to:

charLimit: {
  enabled: true,
  min: 3,
  max: 50
}
🔗 Analysis chain

Line range hint 1-6972: Verify the implementation aligns with requirements.

The current implementation adds the charLimit property with enabled: false to all OpenText questions. However, according to the PR objectives, there should be:

  • A maximum length of 50 characters
  • A minimum length of 3 characters

Let's verify if we need additional properties for min/max limits:


The search results reveal important context about character limits in the codebase:

  1. The types definition in packages/types/surveys/types.ts shows that charLimit is an object that can have min and max properties
  2. The OpenTextQuestion component in packages/surveys/src/components/questions/OpenTextQuestion.tsx implements these limits using minlength and maxlength HTML attributes
  3. The UI in apps/web/app/(app)/(survey-editor)/.../OpenQuestionForm.tsx shows there's a toggle and inputs for setting character limits

Let's verify the exact type definition to understand the required structure:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if any OpenText questions have min/max character limits defined

# Search for charLimit configurations that might include min/max
rg -A 5 'charLimit:\s*{' 

# Search for any other character limit related configurations
rg -i 'char.*limit|min.*length|max.*length'

Length of output: 17809


Script:

#!/bin/bash
# Get the charLimit type definition
rg -A 10 'charLimit: z\.object' packages/types/surveys/types.ts

Length of output: 480

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c29040a and 10bfc05.

📒 Files selected for processing (2)
  • apps/web/app/(app)/(onboarding)/environments/[environmentId]/xm-templates/lib/xm-templates.ts (7 hunks)
  • packages/lib/templates.ts (81 hunks)
🔇 Additional comments (2)
apps/web/app/(app)/(onboarding)/environments/[environmentId]/xm-templates/lib/xm-templates.ts (2)

Line range hint 1-459: Verify error handling and type definitions

The implementation maintains existing error handling patterns. However, we should verify that the type system properly enforces the new charLimit property structure.

Let's check the type definitions and their usage:

✅ Verification successful

Type definitions and error handling are properly implemented

The verification shows that:

  • The charLimit property is properly typed in packages/types/surveys/types.ts with Zod schema validation
  • Error handling for charLimit includes validation for:
    • Enabled state with undefined min/max
    • Negative values
    • Min greater than max
  • The implementation across all survey templates consistently follows the type structure
  • No type assertions or bypasses are used with charLimit
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify type definitions and their usage across the codebase

# Check if charLimit is properly typed in the schema
rg -p 'charLimit.*{' --type typescript

# Look for any type-related comments or TODOs
rg -p 'TODO.*type' --type typescript

# Check for any type assertion usage that might bypass type safety
rg -p 'as.*{.*charLimit' --type typescript

Length of output: 351


Script:

#!/bin/bash
# Search for charLimit type definitions and usage
rg -p "charLimit" --type ts

# Search for OpenText question type definitions
ast-grep --pattern 'type TSurveyQuestion = {
  $$$
  charLimit?: $_
  $$$
}'

# Search for any type errors or warnings in comments
rg -p "(TODO|FIXME|NOTE).*type" --type ts

# Look for type assertions related to charLimit
rg -p "as.*charLimit" --type ts

Length of output: 5637


54-56: LGTM! Consistent implementation of character limit property across all templates.

The changes systematically add the charLimit property to all OpenText questions across different survey templates, with a consistent default state of enabled: false. This aligns well with the PR objectives and provides a uniform foundation for character limit functionality.

Let's verify the type safety of these changes:

Also applies to: 64-66, 165-167, 254-256, 265-267, 296-298, 397-399, 427-429, 437-439

✅ Verification successful

Based on the search results, I can see that:

  1. The OpenText question type is properly defined in the types with a charLimit property that includes enabled, min, and max fields.
  2. The charLimit property is validated in the ZSurveyOpenTextQuestion schema with proper validation rules.
  3. The type definition shows that charLimit.enabled defaults to false, which matches the implementation in the review.

Implementation of charLimit property is type-safe and consistent

The charLimit property implementation in the OpenText questions is properly typed and follows the schema definition:

  • Property structure matches the type definition: { enabled: boolean, min?: number, max?: number }
  • Default value of enabled: false aligns with the schema
  • Schema includes validation rules for min/max values when enabled is true
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all OpenText questions have the charLimit property
# and that the types are properly defined

# Search for OpenText type questions to ensure all have charLimit property
ast-grep --pattern 'type: TSurveyQuestionTypeEnum.OpenText'

# Check if the TSurveyQuestionTypeEnum and related types are properly updated
rg -A 10 'interface.*OpenText.*{' 

Length of output: 205


Script:

#!/bin/bash
# Let's fix the regex and search patterns

# Search for OpenText type questions
rg "type: .*OpenText"

# Check interfaces and types related to OpenText
rg "interface.*OpenText"

# Search for charLimit property definitions
rg "charLimit.*enabled"

# Look for type definitions
fd "types?.ts" --exec cat {}

Length of output: 74798

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 and nitpick comments (3)
packages/js/index.html (1)

10-10: Consider using environment variables for configuration.

Hardcoding environment IDs directly in source files can lead to accidental commits of development configurations. Consider using environment variables or configuration files to manage these values.

packages/surveys/src/components/questions/open-text-question.tsx (2)

116-117: Add aria attributes for accessibility.

Consider adding aria attributes to improve accessibility when character limits are enabled:

 minlength={question.inputType === "text" ? question.charLimit?.min : undefined}
 maxlength={question.inputType === "text" ? question.charLimit?.max : undefined}
+aria-describedby={`${question.id}-char-limit`}

Also applies to: 140-141


144-149: Enhance character count UX.

The current implementation only shows the count when approaching the maximum. Consider:

  1. Always showing the count when limits are enabled
  2. Adding a more descriptive message when limit is reached
-{question.inputType === "text" && question.charLimit?.max !== undefined && (
+{question.inputType === "text" && question.charLimit?.enabled && (
   <span
+    id={`${question.id}-char-limit`}
     className={`fb-text-xs ${
       currentLength >= question.charLimit?.max 
-      ? "fb-text-red-500 font-semibold" 
+      ? "fb-text-red-500 font-semibold"
       : "text-neutral-400"}`}>
-    {currentLength}/{question.charLimit?.max}
+    {currentLength >= question.charLimit?.max
+      ? `Maximum ${question.charLimit.max} characters reached`
+      : `${currentLength}/${question.charLimit.max} characters`}
   </span>
 )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 10bfc05 and ad98e10.

📒 Files selected for processing (7)
  • apps/web/playwright/api/management/survey.spec.ts (1 hunks)
  • packages/js/index.html (1 hunks)
  • packages/lib/messages/de-DE.json (2 hunks)
  • packages/lib/messages/en-US.json (2 hunks)
  • packages/lib/messages/fr-FR.json (2 hunks)
  • packages/lib/messages/pt-BR.json (2 hunks)
  • packages/surveys/src/components/questions/open-text-question.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/lib/messages/fr-FR.json
🧰 Additional context used
📓 Learnings (1)
packages/surveys/src/components/questions/open-text-question.tsx (2)
Learnt from: DeepaPrasanna
PR: formbricks/formbricks#4047
File: packages/surveys/src/components/questions/OpenTextQuestion.tsx:136-137
Timestamp: 2024-11-12T04:24:22.684Z
Learning: In the `OpenTextQuestion` component, using camelCase `minLength` and `maxLength` attributes in React can cause undefined values to default to `0`, preventing user input. Therefore, it's acceptable to use lowercase `minlength` and `maxlength` attributes to avoid this issue.
Learnt from: DeepaPrasanna
PR: formbricks/formbricks#4047
File: packages/surveys/src/components/questions/OpenTextQuestion.tsx:113-114
Timestamp: 2024-11-12T04:24:22.684Z
Learning: When setting `minLength` and `maxLength` attributes in React components, passing `undefined` can result in them being set to `0`, which can prevent user input. Use conditional rendering to apply these attributes only when their values are defined.
🔇 Additional comments (4)
packages/surveys/src/components/questions/open-text-question.tsx (1)

45-45: LGTM: State initialization looks good.

The currentLength state is properly initialized with the existing value length, with a fallback to 0.

packages/lib/messages/en-US.json (1)

246-246: Translations for character limits feature look good!

The translations are clear, concise and appropriately placed in their respective sections:

  • Common section: "maximum" and "minimum" for reuse
  • Surveys section: Toggle specific texts with clear descriptions

Also applies to: 252-252, 1366-1367

packages/lib/messages/pt-BR.json (1)

246-246: LGTM! The new translations for character limits are well-implemented.

The added translations are grammatically correct and maintain consistency with the existing tone. The translations accurately convey the meaning of:

  • Maximum/minimum values
  • Character limit toggle functionality
  • Description of the feature's purpose

Let's verify these translations are used consistently across the codebase:

Also applies to: 252-252, 1366-1367

✅ Verification successful

The character limit translations are correctly implemented and used consistently

The verification shows that:

  • The new Portuguese translations align with existing translations in other language files (en-US, fr-FR, de-DE)
  • The translation keys are actively used in the OpenQuestionForm component
  • The implementation maintains consistency across the internationalization system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new character limit translations
# Test: Search for character limit related keys in other language files and components
rg -g '!pt-BR.json' "character_limit_toggle"

Length of output: 1157

packages/lib/messages/de-DE.json (1)

246-246: LGTM! The German translations for character limits look good.

The translations are properly added to the common section and use appropriate German terms for "maximum" and "minimum".

Also applies to: 252-252

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community request enhancement New feature or request low priority Created by Linear-GitHub Sync

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Add character limitations to free text question

4 participants