Skip to content

gw-rich-text-html-fields.php: Added image upload capabilities. #1075

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

Merged
merged 2 commits into from
May 5, 2025

Conversation

saifsultanc
Copy link
Contributor

@saifsultanc saifsultanc commented Apr 15, 2025

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/2898113899/81765

Summary

Adding support for adding images with our Rich Text HTML snippet. Details from David here.

How this update works:
https://www.loom.com/share/dc2214ba5a9c4155899051559b89ce1e

Copy link

coderabbitai bot commented Apr 15, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This change enhances the rich text HTML field in Gravity Forms by integrating the WordPress media uploader into the TinyMCE editor within the form editor page. It enqueues the necessary media scripts and modifies the TinyMCE toolbar to include an image button. When this button is clicked, the WordPress media library is opened for image selection, and the selected image is inserted into the editor content as an <img> tag with its URL and alt text.

Changes

File(s) Change Summary
gravity-forms/gw-rich-text-html-fields.php Enqueues WordPress media uploader scripts on the admin page, extends TinyMCE toolbar with an image button, and adds JavaScript to allow image insertion from the media library into the rich text HTML field editor.

Sequence Diagram(s)

sequenceDiagram
    participant AdminUser as Admin User
    participant FormEditor as Form Editor Page
    participant TinyMCE as TinyMCE Editor
    participant WP_Media as WordPress Media Library

    AdminUser->>FormEditor: Loads form editor page
    FormEditor->>FormEditor: Enqueue wp_enqueue_media()
    FormEditor->>TinyMCE: Initialize editor with image button
    AdminUser->>TinyMCE: Clicks image button
    TinyMCE->>WP_Media: Opens media library (image selection)
    AdminUser->>WP_Media: Selects image
    WP_Media->>TinyMCE: Returns image URL and alt text
    TinyMCE->>FormEditor: Inserts <img> tag into editor content
Loading

Possibly related PRs


📜 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 355facd and e0bc1c6.

📒 Files selected for processing (1)
  • gravity-forms/gw-rich-text-html-fields.php (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

Warnings
⚠️ When ready, don't forget to request reviews on this pull request from your fellow wizards.

Generated by 🚫 dangerJS against 355facd

@saifsultanc
Copy link
Contributor Author

An alternate and easier fix could have been to include 'insert' on the toolbar (https://www.tiny.cloud/docs/tinymce/latest/quickbars/). Like so:

editor.settings.toolbar1 = 'bold,italic,underline,bullist,numlist,alignleft,aligncenter,alignright,link,insert';

But it would have added other stuff along with insert image, not exactly as what David described.

Copy link

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0390f25 and 355facd.

📒 Files selected for processing (1)
  • gravity-forms/gw-rich-text-html-fields.php (2 hunks)
🔇 Additional comments (2)
gravity-forms/gw-rich-text-html-fields.php (2)

19-19: Well done adding the media uploader.

The addition of wp_enqueue_media() is essential for the image upload functionality and is properly placed within the admin_init hook for the form editor page.


74-74: Good addition of the 'image' button to the toolbar.

You've successfully extended the TinyMCE toolbar to include the image button, which is necessary for the new image upload functionality.

Comment on lines 76 to 95
// Handle image insertion from media library
editor.addButton( 'image', {
icon: 'image',
tooltip: 'Insert Image',
onclick: function() {
var frame = wp.media({
title: 'Insert Media',
button: { text: 'Insert into HTML Field' },
multiple: false,
library: { type: 'image' }
} );

frame.on('select', function() {
var attachment = frame.state().get('selection').first().toJSON();
editor.insertContent('<img src="' + attachment.url + '" alt="' + attachment.alt + '" />');
} );

frame.open();
}
} );
Copy link

@coderabbitai coderabbitai bot Apr 15, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Image upload functionality looks good, but could use some enhancements.

The implementation correctly uses WordPress media API to handle image selection and insertion. The code appropriately:

  1. Opens the media library restricted to images
  2. Sets up the selection handler
  3. Inserts the selected image into the editor

A few suggestions for improvement:

Consider enhancing the implementation with:

 frame.on('select', function() {
     var attachment = frame.state().get('selection').first().toJSON();
-    editor.insertContent('<img src="' + attachment.url + '" alt="' + attachment.alt + '" />');
+    // Escape attributes for security
+    var url = attachment.url.replace(/"/g, '&quot;');
+    var alt = (attachment.alt || '').replace(/"/g, '&quot;');
+    
+    // Insert image with more attributes for better accessibility and control
+    editor.insertContent('<img src="' + url + '" alt="' + alt + '" class="size-full" />');
 } );

It might also be helpful to check if the TODO item related to image support should be removed from the file's header since it's now implemented:


🏁 Script executed:

#!/bin/bash
# Look for the TODO item related to image support
grep -n "Add support for inserting images" gravity-forms/gw-rich-text-html-fields.php

Length of output: 130


Image Upload Enhancement and Header Cleanup

  • The image insertion functionality using the WordPress media API is working well.

  • To further improve security and accessibility, update the image insertion code to escape attribute values and include an extra class. For example:

     frame.on('select', function() {
         var attachment = frame.state().get('selection').first().toJSON();
    -    editor.insertContent('<img src="' + attachment.url + '" alt="' + attachment.alt + '" />');
    +    // Escape attributes for security
    +    var url = attachment.url.replace(/"/g, '&quot;');
    +    var alt = (attachment.alt || '').replace(/"/g, '&quot;');
    +    // Insert image with enhanced accessibility and control
    +    editor.insertContent('<img src="' + url + '" alt="' + alt + '" class="size-full" />');
     } );
  • Additionally, the file header still contains the TODO "* 2. Add support for inserting images." (line 13). Since image support is now implemented, please remove this outdated comment.

📝 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
// Handle image insertion from media library
editor.addButton( 'image', {
icon: 'image',
tooltip: 'Insert Image',
onclick: function() {
var frame = wp.media({
title: 'Insert Media',
button: { text: 'Insert into HTML Field' },
multiple: false,
library: { type: 'image' }
} );
frame.on('select', function() {
var attachment = frame.state().get('selection').first().toJSON();
editor.insertContent('<img src="' + attachment.url + '" alt="' + attachment.alt + '" />');
} );
frame.open();
}
} );
// Handle image insertion from media library
editor.addButton( 'image', {
icon: 'image',
tooltip: 'Insert Image',
onclick: function() {
var frame = wp.media({
title: 'Insert Media',
button: { text: 'Insert into HTML Field' },
multiple: false,
library: { type: 'image' }
} );
frame.on('select', function() {
var attachment = frame.state().get('selection').first().toJSON();
// Escape attributes for security
var url = attachment.url.replace(/"/g, '&quot;');
var alt = (attachment.alt || '').replace(/"/g, '&quot;');
// Insert image with more attributes for better accessibility and control
editor.insertContent('<img src="' + url + '" alt="' + alt + '" class="size-full" />');
} );
frame.open();
}
} );

Copy link
Contributor

Choose a reason for hiding this comment

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

@saifsultanc

I do dig the suggestion to escape attribute values. The additional class suggestion I'm not sure is needed though.

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Contributor

@veryspry veryspry left a comment

Choose a reason for hiding this comment

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

@saifsultanc I tested this and it seems to working functionally well!

I did notice a general bug with the snippet though, where upon initial load of the editor, the editor content flashes and then disappears. Including a Loom with that finding since it's easier demonstrated than explain in comment form.

https://www.loom.com/share/c341fcb1ee3e4f5cbea9d32acc3626b1

Again, the changes in the PR are working well, this is just an unrelated bug that I noticed.

Comment on lines 76 to 95
// Handle image insertion from media library
editor.addButton( 'image', {
icon: 'image',
tooltip: 'Insert Image',
onclick: function() {
var frame = wp.media({
title: 'Insert Media',
button: { text: 'Insert into HTML Field' },
multiple: false,
library: { type: 'image' }
} );

frame.on('select', function() {
var attachment = frame.state().get('selection').first().toJSON();
editor.insertContent('<img src="' + attachment.url + '" alt="' + attachment.alt + '" />');
} );

frame.open();
}
} );
Copy link
Contributor

Choose a reason for hiding this comment

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

@saifsultanc

I do dig the suggestion to escape attribute values. The additional class suggestion I'm not sure is needed though.

@saifsultanc saifsultanc merged commit 54365a5 into master May 5, 2025
0 of 3 checks passed
@saifsultanc saifsultanc deleted the saif/add/81765-add-image-upload-to-rte-html branch May 5, 2025 13:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants