Skip to content

gw-rich-text-html-fields.php: Added improvements for Rich Text HTML Fields Snippet. #1132

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

saifsultanc
Copy link
Contributor

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/2987432785/86002

Summary

Primarily inspired from #1071, with some improvements. Takes into account the recent updates to the snippet here 55c2438

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

Copy link

coderabbitai bot commented Jul 17, 2025

Walkthrough

This update introduces a mechanism to track and synchronize the TinyMCE editor mode ('visual' or 'HTML') in the Gravity Forms rich text field. It adds a global variable for editor mode, a function to save editor content based on mode, and ensures mode state is preserved and updated during user interactions.

Changes

File(s) Change Summary
gravity-forms/gw-rich-text-html-fields.php Added gwRichTextMode global variable, polling for TinyMCE readiness, mode synchronization, and content-saving logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI (Editor Tabs)
    participant JS Script
    participant TinyMCE
    participant Field Properties

    User->>UI (Editor Tabs): Switches editor mode (Visual/HTML)
    UI (Editor Tabs)->>JS Script: Detects mode change
    JS Script->>gwRichTextMode: Updates mode variable
    JS Script->>TinyMCE: Waits for editor to be ready (polling)
    JS Script->>TinyMCE: Switches editor mode
    JS Script->>Field Properties: Saves current mode to field property

    User->>TinyMCE: Edits content
    TinyMCE->>JS Script: Triggers content change event
    JS Script->>Field Properties: Calls SetFieldContentProperty to save content based on current mode
Loading

Possibly related PRs

Suggested reviewers

  • veryspry
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 5e0d06d

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

🧹 Nitpick comments (3)
gravity-forms/gw-rich-text-html-fields.php (3)

63-66: Consider using a more scoped approach to avoid global variable pollution.

The global variable gwRichTextMode could potentially conflict with other scripts. Consider using a namespace or scoping it within an IIFE to avoid global pollution.

-		var gwRichTextMode;
+		var GWRichText = GWRichText || {};
 		jQuery( document ).on( 'gform_load_field_settings', function( event, field ) {
-			gwRichTextMode = field.gwRichTextMode || 'tmce';
+			GWRichText.mode = field.gwRichTextMode || 'tmce';

115-130: Improve timeout handling in the polling mechanism.

The polling mechanism is well-implemented, but the timeout case doesn't provide any fallback behavior or error handling. Consider adding a callback or logging when the timeout occurs.

 				const waitForEditorToBeReady = (callback, timeout = 5000) => {
 					const start = Date.now();
 					const interval = setInterval(() => {
 						const editor = typeof tinymce !== 'undefined' && tinymce.get(editorId);
 						if (editor) {
 							clearInterval(interval);
 							callback();
 						} else if (Date.now() - start > timeout) {
 							clearInterval(interval);
+							console.warn('TinyMCE editor initialization timed out');
 						}
 					}, 100);
 				};

131-148: Add error handling and consider scoping the global function.

The function logic is correct, but it lacks error handling for the TinyMCE editor instance and uses global scope.

 				// Set the content when save.
-				window.SetFieldContentProperty = function () {
+				window.SetFieldContentProperty = function () {
 					var mode = jQuery('#wp-' + editorId + '-wrap').hasClass('html-active') ? 'html' : 'tmce';
 					var content = '';

 					if (mode === 'html') {
 						content = jQuery('#' + editorId).val();
-					} else if (tinymce.get(editorId)) {
+					} else {
+						var editor = tinymce.get(editorId);
+						if (editor) {
-						content = tinymce.get(editorId).getContent();
+							content = editor.getContent();
+						}
 					}

 					SetFieldProperty('content', content);
 				};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec6b24f and 5e0d06d.

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

150-158: Good improvement for mode state persistence.

The addition of saving the current mode to the field property ensures state persistence across form editor sessions. The implementation correctly identifies the clicked button and updates the field property accordingly.


129-129: Ensure consistent renaming of gwRichTextMode when adding a namespace

If you introduce a namespaced global (e.g. window.MyPlugin.richTextMode), be sure to update every reference in gravity-forms/gw-rich-text-html-fields.php:

  • Declaration:
    var gwRichTextMode;
  • Initialization from field settings:
    gwRichTextMode = field.gwRichTextMode || 'tmce';
  • Mode switch call:
    waitForEditorToBeReady(() =>
      window.switchEditors.go(editorId,
        gwRichTextMode === 'html' ? 'html' : 'tmce'
      )
    );
  • Saving back to the field property:
    SetFieldProperty('gwRichTextMode', mode)

Verify that each instance is updated to use your chosen namespace.

@spivurno
Copy link
Contributor

@saifsultanc A few issues:

  1. Code is being wrapped in tags automatically on save:
    https://www.loom.com/share/327f74651a0d4f2da0f3e45d74eda7e4

  2. Line breaks are being removed in the code editor.
    https://www.loom.com/share/d46948fae6f04518bf45a81442ebe5c8

    I believe this is an extension of the issue I reported originally where the code editor does not save values with line breaks. See the original Loom for details on that.

  3. The issue where the height of the code editor increases each time the field settings were saved is still present. See the original Loom for details.

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