Skip to content

Stop using jQuery in captcha render code#2189

Merged
Crabcyborg merged 2 commits into
masterfrom
remove_jquery_from_captcha_render_code
Dec 23, 2024
Merged

Stop using jQuery in captcha render code#2189
Crabcyborg merged 2 commits into
masterfrom
remove_jquery_from_captcha_render_code

Conversation

@Crabcyborg
Copy link
Copy Markdown
Contributor

@Crabcyborg Crabcyborg commented Dec 23, 2024

Related issue https://github.com/Strategy11/formidable-pro/issues/5002

This update removes a use of the jQuery .hide() function, as well as .find(), and 2 uses of .closest().

This also updates a lot of uses of let to const, removes some quotes around object keys, and I added some type comments. I also optimized the rendered check, so it happens before we do everything else.

And it fixes a bug. The code was intended to hide the invisible captcha field's label, but the .closest() call was incorrect and it would never select anything.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 23, 2024

Walkthrough

The pull request introduces a new method renderCaptcha to the frmFrontForm object in the formidable.js file. This method is designed to handle the rendering of captcha fields with improved logic for checking existing captcha rendering, managing captcha size and parameters, and handling label visibility. The implementation includes a callback mechanism for post-captcha validation and streamlines the code structure with more concise variable declarations and safer property access.

Changes

File Change Summary
js/formidable.js - Added new renderCaptcha method to frmFrontForm object
- Simplified captcha rendering logic
- Updated variable declarations to use const
- Implemented optional chaining for safer property access
- Added callback for afterRecaptcha method on captcha validation

Sequence Diagram

sequenceDiagram
    participant Form as Form Component
    participant Captcha as Captcha Renderer
    participant Validator as Captcha Validator

    Form->>Captcha: renderCaptcha(captcha, selector)
    Captcha-->>Captcha: Check existing render
    Captcha->>Validator: Validate Captcha
    Validator-->>Captcha: Validation Result
    Captcha->>Form: Trigger afterRecaptcha callback
Loading

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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
Copy Markdown
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 (1)
js/formidable.js (1)

1677-1683: Fix JSDoc block alignment

ESLint flagged these lines for alignment issues within the JSDoc comment block. Correcting the indentation will ensure the code adheres to style guidelines.

Apply the following diff to align the comment lines properly:

-		/**
-		 * Render a captcha field.
-		 *
-		 * @param {HTMLElement} captcha
-		 * @param {string} captchaSelector
-		 * @return {void}
-		 */
+		/**
+		 * Render a captcha field.
+		 *
+		 * @param {HTMLElement} captcha
+		 * @param {string} captchaSelector
+		 * @return {void}
+		 */
🧰 Tools
🪛 eslint

[error] 1677-1683: Expected JSDoc block lines to be aligned.

(jsdoc/check-line-alignment)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f88671 and baec085.

📒 Files selected for processing (1)
  • js/formidable.js (1 hunks)
🧰 Additional context used
🪛 eslint
js/formidable.js

[error] 1677-1683: Expected JSDoc block lines to be aligned.

(jsdoc/check-line-alignment)

🔇 Additional comments (4)
js/formidable.js (4)

1685-1685: Good use of 'data-rid' attribute check

Using getAttribute('data-rid') to determine if the captcha is already rendered is a clean approach to prevent duplicate rendering. No issues detected.


1690-1696: Parameter assignments are clear and maintainable

Declaring captcha parameters with const and grouping them in a single object is neat. This approach enhances readability by keeping all config options together.


1698-1704: Optional chaining for DOM lookups is safe

Leveraging optional chaining when searching for the form and the label is a good defensive coding strategy to prevent runtime errors. Hiding the captcha label when size equals "invisible" is logically sound.


1710-1712: Robust fallback with dynamic captcha references

Conditionally using turnstile or a different captcha library is a flexible pattern. Using the captcha ID as the container reference is a neat trick for dynamic usage.

Copy link
Copy Markdown
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 comments (1)
js/formidable.js (1)

Line range hint 1748-1758: Fix inconsistent turnstile check.

The turnstile check should use the provided selector parameter for consistency.

 function getSelectedCaptcha( captchaSelector ) {
   if ( captchaSelector === '.frm-g-recaptcha' ) {
     return grecaptcha;
   }
-  if ( document.querySelector( '.cf-turnstile' ) ) {
+  if ( captchaSelector === '.cf-turnstile' ) {
     return turnstile;
   }
   return hcaptcha;
 }
🧹 Nitpick comments (3)
js/formidable.js (3)

1690-1695: Add error handling for missing required attributes.

The code assumes that required attributes like data-sitekey will always be present. Consider adding validation.

 const size   = captcha.getAttribute( 'data-size' );
+if ( ! captcha.getAttribute( 'data-sitekey' ) ) {
+  console.error( 'Captcha is missing required data-sitekey attribute' );
+  return;
+}
 const params = {
   sitekey: captcha.getAttribute( 'data-sitekey' ),
   size: size,
   theme: captcha.getAttribute( 'data-theme' )
 };

1697-1709: Extract callback function for better readability.

Consider extracting the callback function to improve code organization.

+function createInvisibleCaptchaCallback( formID ) {
+  return function( token ) {
+    frmFrontForm.afterRecaptcha( token, formID );
+  };
+}

 if ( size === 'invisible' ) {
   const formID = captcha.closest( 'form' )?.querySelector( 'input[name="form_id"]' )?.value;

   const captchaLabel = captcha.closest( '.frm_form_field' )?.querySelector( '.frm_primary_label' );
   if ( captchaLabel ) {
     captchaLabel.style.display = 'none';
   }

-  params.callback = function( token ) {
-    frmFrontForm.afterRecaptcha( token, formID );
-  };
+  params.callback = createInvisibleCaptchaCallback( formID );
 }

1710-1712: Simplify turnstile condition.

The turnstile condition could be simplified for better readability.

-const activeCaptcha    = getSelectedCaptcha( captchaSelector );
-const captchaContainer = typeof turnstile !== 'undefined' && turnstile === activeCaptcha ? '#' + captcha.id : captcha.id;
-const captchaID        = activeCaptcha.render( captchaContainer, params );
+const activeCaptcha = getSelectedCaptcha( captchaSelector );
+const isTurnstile   = typeof turnstile !== 'undefined' && turnstile === activeCaptcha;
+const containerId   = isTurnstile ? '#' + captcha.id : captcha.id;
+const captchaID     = activeCaptcha.render( containerId, params );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between baec085 and 85fcb99.

📒 Files selected for processing (1)
  • js/formidable.js (1 hunks)
🔇 Additional comments (2)
js/formidable.js (2)

1677-1683: LGTM! Clear function documentation.

The JSDoc comments clearly document the function parameters and purpose.


1685-1688: LGTM! Early return pattern.

Good use of early return pattern to avoid unnecessary processing if the captcha is already rendered.

@Crabcyborg Crabcyborg merged commit 8bfc980 into master Dec 23, 2024
@Crabcyborg Crabcyborg deleted the remove_jquery_from_captcha_render_code branch December 23, 2024 14:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant