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

Avoid selecting text when multiselecting fields #2211

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

AbdiTolesa
Copy link
Contributor

@AbdiTolesa AbdiTolesa commented Jan 9, 2025

Fix https://github.com/Strategy11/formidable-pro/issues/5224

This is just an implementation improvement than a feature to test. We have been unselecting selected text after fields are multiselected but we are now preventing text selection at the first place.

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request modifies the js/formidable_admin.js file to enhance text selection behavior within the form builder interface. It introduces an event listener for the mousedown event on the .frm_form_builder element, which prevents text selection when the Shift key is held down. Additionally, it removes existing code that managed text selection when holding the Shift key, simplifying the text selection logic to focus solely on preventing accidental selections.

Changes

File Change Summary
js/formidable_admin.js - Added event listener for mousedown to prevent text selection in .frm_form_builder when Shift is held
- Removed code handling text selection prevention with Shift key

Possibly related PRs

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

@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 (4)
js/formidable_admin.js (4)

Line range hint 1156-1180: Potential memory leak in event handler

The event handler for field group hover is not properly cleaned up. The mousemove event listener should be removed when no longer needed.

function maybeRemoveHoverTargetOnMouseMove(event) {
  const elementFromPoint = document.elementFromPoint(event.clientX, event.clientY);
  if (null !== elementFromPoint && null !== elementFromPoint.closest('#frm-show-fields')) {
    return;
  }
  maybeRemoveGroupHoverTarget();
+ jQuery('#wpbody-content').off('mousemove', maybeRemoveHoverTargetOnMouseMove); 
}

Line range hint 2178-2201: Security vulnerability in HTML sanitization

The purifyHtml function needs to be more robust to prevent XSS attacks. Consider using a dedicated HTML sanitization library.

function purifyHtml(html) {
+ // Use DOMPurify or similar library
+ return DOMPurify.sanitize(html, {
+   ALLOWED_TAGS: ['b', 'i', 'em', 'strong'],
+   ALLOWED_ATTR: []  
+ });
- // Current implementation may allow unsafe HTML
- return clean;
}

Line range hint 3012-3040: Improve error handling in AJAX requests

The AJAX error handling in postAjax could be more robust. Add proper error handling and user feedback.

function postAjax(data, success) {
  const xmlHttp = new XMLHttpRequest();
+ xmlHttp.onerror = function() {
+   // Handle network errors
+   console.error('Network error occurred');
+   showErrorMessage('Network error occurred. Please try again.');
+ };
+ xmlHttp.ontimeout = function() {
+   // Handle timeouts
+   console.error('Request timed out');
+   showErrorMessage('Request timed out. Please try again.'); 
+ };
}

Line range hint 3452-3475: Add accessibility improvements

The modal dialog implementation needs better accessibility support.

function initModal(id, width) {
  const dialogArgs = {
    modal: true,
+   role: 'dialog',
+   aria: {
+     labelledby: id + '-title',
+     describedby: id + '-description'
+   },
+   // Add keyboard navigation support
+   onKeyDown: function(e) {
+     if (e.key === 'Escape') {
+       $info.dialog('close'); 
+     }
+   }
  };
}
🧹 Nitpick comments (1)
js/formidable_admin.js (1)

Line range hint 1-50: Code organization needs improvement

The code would benefit from better modularization and separation of concerns. Consider:

  1. Breaking down the large frmAdminBuildJS function into smaller, focused modules
  2. Using ES modules for better code organization
  3. Adding JSDoc documentation for the main function and public methods
// Break into modules like:
import { formBuilder } from './modules/form-builder';
import { settings } from './modules/settings';
import { exports } from './modules/exports';

const frmAdminBuild = () => {
  // Core functionality
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e69aea4 and f2ee8d8.

📒 Files selected for processing (1)
  • js/formidable_admin.js (1 hunks)

@AbdiTolesa AbdiTolesa requested a review from truongwp January 9, 2025 14:45
Copy link
Contributor

@truongwp truongwp left a comment

Choose a reason for hiding this comment

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

This looks good. Thanks @AbdiTolesa!

@truongwp truongwp requested a review from Crabcyborg January 10, 2025 16:14
js/formidable_admin.js Outdated Show resolved Hide resolved
Copy link

codecov bot commented Jan 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 26.97%. Comparing base (1c7bd47) to head (195feba).
Report is 39 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #2211      +/-   ##
============================================
+ Coverage     26.94%   26.97%   +0.02%     
- Complexity     8247     8258      +11     
============================================
  Files           127      127              
  Lines         27305    27316      +11     
============================================
+ Hits           7357     7368      +11     
  Misses        19948    19948              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@AbdiTolesa AbdiTolesa requested a review from Crabcyborg January 12, 2025 19:29
Copy link
Contributor

@Crabcyborg Crabcyborg left a comment

Choose a reason for hiding this comment

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

Thanks @AbdiTolesa.

It looks like this update is working in Chrome but now the text is getting selected in Firefox and not getting unselected (since the other code was also removed).

Could you test it in FIrefox as well?

@AbdiTolesa AbdiTolesa requested a review from Crabcyborg January 14, 2025 12:04
Copy link
Contributor

@Crabcyborg Crabcyborg left a comment

Choose a reason for hiding this comment

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

Thank you @AbdiTolesa and @truongwp!

I think this is good to merge.

🚀

@Crabcyborg
Copy link
Contributor

Crabcyborg commented Jan 15, 2025

Actually, I thought this was working, but I'm still seeing the same issue sometimes.

🫤

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 comments (5)
js/formidable_admin.js (5)

Line range hint 1-100: Add error handling for AJAX requests

The AJAX requests throughout the code should include error handling to gracefully handle failures. Add catch blocks and error notifications.

Example improvement for one of the AJAX calls:

 jQuery.ajax({
     type: 'POST',
     url: ajaxurl,
     data: data,
     success: function( response ) {
         // Success handling
+    },
+    error: function( xhr, status, error ) {
+        // Show error notification
+        console.error( 'Request failed:', error );
+        infoModal( frm_admin_js.ajax_error );
     }
 });

Line range hint 400-500: Add input validation

The form field validation could be improved by adding more robust input validation before processing.

function validateInput(value, type) {
    switch(type) {
        case 'email':
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
        case 'number':
            return !isNaN(value) && value !== '';
        // Add more validation types
    }
    return true;
}

Line range hint 800-900: Add debouncing for resource-intensive operations

Some operations like field updates and AJAX calls should be debounced to prevent excessive server requests.

const debouncedFieldUpdate = debounce(function(fieldId, value) {
    updateField(fieldId, value);
}, 250);

Line range hint 1400-1500: Implement proper cleanup in event handlers

Event handlers should be properly cleaned up to prevent memory leaks, especially for dynamically added/removed elements.

function addEventHandlers() {
    const handlers = new Map();
    return {
        add: function(element, event, handler) {
            element.addEventListener(event, handler);
            handlers.set(element, {event, handler});
        },
        cleanup: function() {
            handlers.forEach((value, element) => {
                element.removeEventListener(value.event, value.handler);
            });
            handlers.clear();
        }
    };
}

Line range hint 1600-1700: Add comprehensive error logging

Implement better error logging and monitoring throughout the application.

const logger = {
    error: function(error, context) {
        console.error('Error:', error);
        // Send to error monitoring service
        if (typeof errorMonitoring !== 'undefined') {
            errorMonitoring.captureException(error, {extra: context});
        }
    }
};
🧹 Nitpick comments (5)
js/formidable_admin.js (5)

10706-10710: Remove unnecessary event handler

The mousedown event handler that only prevents default when shift key is pressed appears to be redundant and doesn't serve a clear purpose. Consider removing it or documenting its necessity.

- document.querySelector( '.frm_form_builder' ).addEventListener( 'mousedown', event => {
-   if ( event.shiftKey ) {
-     event.preventDefault();
-   }
- });

Line range hint 200-300: Improve event delegation

Multiple event handlers are attached directly to elements. Use event delegation for better performance, especially for dynamically added elements.

- jQuery('.frm_form_builder form').on('submit', function() {
+ jQuery(document).on('submit', '.frm_form_builder form', function() {

Line range hint 600-700: Implement caching for frequently accessed DOM elements

Cache frequently accessed DOM elements to improve performance instead of repeatedly querying them.

const cache = {
    $formBuilder: null,
    $fieldOptions: null,
    init: function() {
        this.$formBuilder = jQuery('#frm_form_builder');
        this.$fieldOptions = jQuery('#frm_field_options');
    }
};

Line range hint 1000-1100: Improve code organization with modules

The code would benefit from being split into modules using ES6 modules for better organization and maintainability.

// field-manager.js
export class FieldManager {
    constructor() {
        // Initialize field management
    }
    // Field related methods
}

// settings-manager.js
export class SettingsManager {
    // Settings related methods
}

Line range hint 1200-1300: Add TypeScript type definitions

Consider adding TypeScript type definitions to improve code maintainability and catch potential errors during development.

interface FieldOptions {
    id: number;
    type: string;
    label: string;
    // Add more field properties
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ad3213b and 2872a96.

📒 Files selected for processing (1)
  • js/formidable_admin.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cypress

@AbdiTolesa
Copy link
Contributor Author

Actually, I thought this was working, but I'm still seeing the same issue sometimes.

🫤

I tried hooking into mousedown and the result seems more reliable now.

@AbdiTolesa AbdiTolesa requested a review from Crabcyborg January 16, 2025 09:25
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.

3 participants