Skip to content

Support custom options for autocomplete dropdown#2187

Merged
Crabcyborg merged 17 commits into
masterfrom
autocomplete-dropdown
Apr 23, 2025
Merged

Support custom options for autocomplete dropdown#2187
Crabcyborg merged 17 commits into
masterfrom
autocomplete-dropdown

Conversation

@truongwp
Copy link
Copy Markdown
Contributor

No description provided.

@truongwp truongwp marked this pull request as ready for review December 31, 2024 13:21
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 31, 2024

Walkthrough

This pull request enhances autocomplete functionality across both PHP and JavaScript components. In the PHP helper, a new method is introduced to conditionally render either a dropdown or an autocomplete input based on the number of options, along with a helper method for extracting option data. An existing method is updated to check for the existence of the publish property before comparison. In the JavaScript files, method signatures are updated to accept a container parameter, new hooks are added for autocomplete clear and select events, and an autocomplete initialization call is changed to use the selection-based method.

Changes

File(s) Change Summary
classes/helpers/FrmAppHelper.php • Added public static method maybe_autocomplete_options to conditionally render a dropdown or autocomplete input based on option count.
• Added private static method get_dropdown_value_and_label_from_option to extract option data.
• Modified maybe_autocomplete_pages_options to check for the existence of the publish property before comparison.
js/admin/dom.js • Updated initSelectionAutocomplete and initAutocomplete to accept an additional container parameter.
• Modified initAutocomplete to dynamically set the autocomplete source from element data attributes.
• Added new actions triggered on autocomplete clear and select events for extensibility.
js/formidable_admin.js • Changed autocomplete initialization call in AJAX callback from initAutocomplete('page', inside) to initSelectionAutocomplete(inside).

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Helper as FrmAppHelper
    participant Renderer as Renderer

    Caller->>Helper: maybe_autocomplete_options(args)
    alt Option count within dropdown_limit
        Helper->>Renderer: Render dropdown input
    else
        Helper->>Helper: Call get_dropdown_value_and_label_from_option for each option
        Helper->>Renderer: Render autocomplete input
    end
Loading
sequenceDiagram
    participant User as User/Event
    participant DOM as js/admin/dom.js
    participant Init as initAutocomplete
    participant Hooks as wp.hooks

    User->>DOM: Trigger autocomplete initialization (with container)
    DOM->>Init: Call initAutocomplete(type, container)
    Init->>Init: Determine element source from data attribute
    Init->>Hooks: Trigger doAction on clear and select events
Loading

Suggested labels

action: needs qa

Suggested reviewers

  • Crabcyborg

📜 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 8a118c5 and 00bd3ec.

📒 Files selected for processing (1)
  • classes/helpers/FrmAppHelper.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • classes/helpers/FrmAppHelper.php
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: PHP 8 tests in WP trunk
  • GitHub Check: PHP 7.4 tests in WP trunk
  • GitHub Check: Cypress

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

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 (4)
classes/helpers/FrmAppHelper.php (2)

1656-1659: Use the correct version for the @since tag.
The doc block currently uses @since x.x. Please replace x.x with the actual version number to maintain accurate version tracking.


1725-1745: Rename references from 'autodropdown' to 'autocomplete' for clarity.
The doc block references “autodropdown” within the function description. Renaming to “autocomplete” may maintain consistency with the rest of the code.

classes/views/shared/views-info.php (1)

8-25: Limit the number of retrieved posts to improve performance.
Using 'post_type' => 'any' with posts_per_page set to -1 can result in large resource usage. Consider adding a limit or a different post retrieval strategy if the dataset is large.

js/formidable_admin.js (1)

Line range hint 8382-8448: New functionality for handling field type changes

This adds new functionality to handle field type changes in the form builder:

  1. Adds a change event handler that checks if a field type is changed
  2. Shows a "Save and Reload" modal when field type changes
  3. Provides options to save and reload immediately or cancel
  4. Improves UX by giving users clear feedback about the impact of changing field types

Consider adding a loading indicator while the page reloads after saving to provide better visual feedback to users.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 850097c and 2e60845.

📒 Files selected for processing (4)
  • classes/helpers/FrmAppHelper.php (2 hunks)
  • classes/views/shared/views-info.php (1 hunks)
  • js/admin/dom.js (3 hunks)
  • js/formidable_admin.js (3 hunks)
🔇 Additional comments (8)
classes/helpers/FrmAppHelper.php (2)

1631-1634: Ensure correct handling of $pages_count->publish.
The added check avoids undefined property errors. This looks good to me.


1660-1723: Validate $args['source'] before counting.
In maybe_autocomplete_options(), consider verifying that $args['source'] is an array to avoid potential type errors during the count() check.

js/admin/dom.js (5)

252-252: Check if container is valid before usage.
When calling initSelectionAutocomplete, ensure that container is a valid DOM element or selector to avoid potential runtime errors.


254-256: Chained autocomplete initializations look good.
Calling initAutocomplete for different types in succession is concise. No issues found.


282-290: Handle JSON parsing failures.
When this.dataset.source has invalid JSON, JSON.parse() may throw an error. Consider wrapping it in a try/catch to fail gracefully.


294-294: No issues with referencing source here.
The code properly references the source variable. Looks good.


347-353: Action hook on autocomplete selection looks good.
Calling wp.hooks.doAction( 'frm_autocomplete_select' ) ensures extensibility. Well implemented.

js/formidable_admin.js (1)

688-689: Change from initAutocomplete to initSelectionAutocomplete

The code changes from using frmDom.autocomplete.initAutocomplete to frmDom.autocomplete.initSelectionAutocomplete. This appears to be a more specific and descriptive function name for initializing autocomplete functionality.

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

🧹 Nitpick comments (1)
js/admin/dom.js (1)

340-346: Update version placeholder in documentation.

The implementation of the action hooks is good, but the documentation uses placeholder versions ("x.x"). Please update these to reflect the actual version where these hooks will be introduced.

Apply these diffs to update the version:

- * @since x.x
+ * @since 6.0

Also applies to: 354-360

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e60845 and af928f3.

📒 Files selected for processing (2)
  • classes/helpers/FrmAppHelper.php (2 hunks)
  • js/admin/dom.js (3 hunks)
🧰 Additional context used
🪛 GitHub Actions: Inspections
classes/helpers/FrmAppHelper.php

[error] 1666-1666: Spaces must be used for mid-line alignment; tabs are not allowed


[error] 1699-1699: Equals sign not aligned with surrounding assignments; expected 12 spaces but found 1 space


[error] 1711-1711: Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space


[error] 1721-1721: End comment for long condition not found; expected '//end if'

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cypress
🔇 Additional comments (4)
js/admin/dom.js (1)

252-257: LGTM! Clean implementation of container-scoped initialization.

The changes effectively support initializing autocomplete within specific containers and add support for custom types.

classes/helpers/FrmAppHelper.php (3)

1631-1631: Good defensive programming!

Adding the isset() check for the publish property prevents potential PHP notices/warnings if the property is undefined.


1656-1749: Well-structured implementation of autocomplete/dropdown functionality

The implementation provides a flexible UI that switches between dropdown and autocomplete based on the number of options. Good separation of concerns and parameter handling.

🧰 Tools
🪛 GitHub Actions: Inspections

[error] 1666-1666: Spaces must be used for mid-line alignment; tabs are not allowed


[error] 1699-1699: Equals sign not aligned with surrounding assignments; expected 12 spaces but found 1 space


[error] 1711-1711: Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space


[error] 1721-1721: End comment for long condition not found; expected '//end if'


1666-1721: ⚠️ Potential issue

Fix code style issues

Please fix the following code style issues:

  1. Line 1666: Use spaces instead of tabs for alignment
  2. Line 1699: Align equals sign with surrounding assignments (12 spaces expected)
  3. Line 1711: Align equals sign (2 spaces expected)
  4. Add proper end comment for the if condition

Apply these fixes:

- 			'truncate'                 => false,
+ 			'truncate'                => false,
- 					<option value="<?php echo esc_attr( $value_label['value'] ); ?>" <?php selected( $value_label['value'], $args['selected'] ); ?>><?php echo esc_html( $value_label['label'] ); ?></option>
+ 					<option value="<?php echo esc_attr( $value_label['value'] ); ?>"            <?php selected( $value_label['value'], $args['selected'] ); ?>><?php echo esc_html( $value_label['label'] ); ?></option>
- 				$autocomplete_value = $value_label['label'];
+ 				$autocomplete_value  = $value_label['label'];
+ 			} //end if

Likely invalid or redundant comment.

🧰 Tools
🪛 GitHub Actions: Inspections

[error] 1666-1666: Spaces must be used for mid-line alignment; tabs are not allowed


[error] 1699-1699: Equals sign not aligned with surrounding assignments; expected 12 spaces but found 1 space


[error] 1711-1711: Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space


[error] 1721-1721: End comment for long condition not found; expected '//end if'

Comment thread js/admin/dom.js
@Crabcyborg
Copy link
Copy Markdown
Contributor

@truongwp It might be nice to get this merged if it's required for another update, so a core release isn't blocking the other update.

It looks like there are some workflow issues at the moment.

Do you think you could get this PR ready to get merged soon?

Thank you!

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)
classes/helpers/FrmAppHelper.php (1)

1739-1749: Consider adding input validation.

While the implementation is clean, consider adding validation to handle edge cases:

  1. Validate array keys exist when accessing $args['value_key'] and $args['label_key']
  2. Add type checking for the $option parameter
 private static function get_dropdown_value_and_label_from_option( $option, $key, $args ) {
+    if ( ! isset( $args['value_key'], $args['label_key'] ) ) {
+        return array( 'value' => '', 'label' => '' );
+    }
+
     if ( is_array( $option ) ) {
         $value = isset( $option[ $args['value_key'] ] ) ? $option[ $args['value_key'] ] : '';
         $label = isset( $option[ $args['label_key'] ] ) ? $option[ $args['label_key'] ] : '';
     } else {
+        if ( ! is_scalar( $option ) ) {
+            return array( 'value' => '', 'label' => '' );
+        }
         $value = $key;
         $label = $option;
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7812b38 and 363ab23.

📒 Files selected for processing (2)
  • classes/helpers/FrmAppHelper.php (2 hunks)
  • classes/views/shared/views-info.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • classes/views/shared/views-info.php
🧰 Additional context used
🪛 GitHub Actions: Inspections
classes/helpers/FrmAppHelper.php

[warning] 1-1: phpdoc_types_order issue found. Please reorder the PHPDoc types.

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: PHP 8 tests in WP trunk
  • GitHub Check: Cypress
  • GitHub Check: PHP 7.4 tests in WP trunk
🔇 Additional comments (2)
classes/helpers/FrmAppHelper.php (2)

631-631: LGTM! Defensive programming improvement.

The added check for publish property existence helps prevent potential PHP notices when the property is not set.


1663-1727: Well-structured implementation for handling dropdown/autocomplete options!

The method provides a robust solution for dynamically switching between dropdown and autocomplete based on the number of options. Key strengths include:

  • Proper parameter validation with defaults
  • Secure output escaping
  • Clean separation of dropdown vs autocomplete logic
  • Efficient handling of selected values

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)
classes/helpers/FrmAppHelper.php (1)

1657-1662: Consider these improvements to the implementation.

  1. Update the "x.x" version number in the PHPDoc to reflect the actual version.
  2. Consider adding error handling for invalid option formats.
  3. Add input validation for the $args parameter.
 /**
- * @since x.x
+ * @since 6.16.3
  *
  * @param array $args Args. See the method for details.
+ * @throws InvalidArgumentException If required arguments are missing or invalid.
  */
 public static function maybe_autocomplete_options( $args ) {
+    if ( ! is_array( $args ) ) {
+        throw new InvalidArgumentException( 'Args must be an array.' );
+    }
     $defaults = array(

Also applies to: 1739-1749

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 363ab23 and 9961d93.

📒 Files selected for processing (2)
  • classes/helpers/FrmAppHelper.php (2 hunks)
  • classes/views/shared/views-info.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • classes/views/shared/views-info.php
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: PHP 8 tests in WP trunk
  • GitHub Check: Cypress
  • GitHub Check: PHP 7.4 tests in WP trunk
🔇 Additional comments (2)
classes/helpers/FrmAppHelper.php (2)

631-631: LGTM! Improved property access safety.

The added check for isset($pages_count->publish) before comparison improves code robustness by preventing potential errors when accessing object properties.


1663-1727: LGTM! Well-implemented autocomplete/dropdown functionality.

The new method provides a flexible solution for rendering either a dropdown or autocomplete input based on the number of options. The implementation includes proper escaping, validation, and separation of concerns.

@truongwp
Copy link
Copy Markdown
Contributor Author

@Crabcyborg I fixed all PHPCS errors. The PHP CS Fixer doesn't give me the line of error so I can't fix it. The Psalm errors should be fixed in another PR.

Comment thread classes/views/shared/views-info.php Outdated
Comment thread classes/helpers/FrmAppHelper.php Outdated
@Crabcyborg Crabcyborg added this to the 6.21 milestone Apr 11, 2025
Comment thread classes/helpers/FrmAppHelper.php
Copy link
Copy Markdown
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 @truongwp!

This works great!

🚀

@Crabcyborg Crabcyborg merged commit 95e011e into master Apr 23, 2025
15 of 16 checks passed
@Crabcyborg Crabcyborg deleted the autocomplete-dropdown branch April 23, 2025 18:06
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.

2 participants