Skip to content

Commit 5e0d06d

Browse files
committed
gw-rich-text-html-fields.php: Added improvements for Rich Text HTML Fields Snippet.
1 parent ec6b24f commit 5e0d06d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

gravity-forms/gw-rich-text-html-fields.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,10 @@
6060
</style>
6161

6262
<script>
63+
var gwRichTextMode;
6364
jQuery( document ).on( 'gform_load_field_settings', function( event, field ) {
65+
gwRichTextMode = field.gwRichTextMode || 'tmce';
66+
6467
var id = 'field_rich_content';
6568
wp.editor.remove( id );
6669
jQuery( '#' + id ).val( field.content );
@@ -75,6 +78,7 @@
7578
quicktags: true
7679
} );
7780
} );
81+
7882
jQuery( document).on( 'tinymce-editor-setup', function ( event, editor ) {
7983
var editorId = 'field_rich_content';
8084
if ( editor.id === editorId ) {
@@ -108,11 +112,49 @@
108112
}
109113
} );
110114

115+
// Wait until the TinyMCE editor is initialized before switching mode.
116+
const waitForEditorToBeReady = (callback, timeout = 5000) => {
117+
const start = Date.now();
118+
const interval = setInterval(() => {
119+
const editor = typeof tinymce !== 'undefined' && tinymce.get(editorId);
120+
if (editor) {
121+
clearInterval(interval);
122+
callback();
123+
} else if (Date.now() - start > timeout) {
124+
clearInterval(interval);
125+
}
126+
}, 100);
127+
};
128+
129+
waitForEditorToBeReady(() => window.switchEditors.go(editorId, gwRichTextMode === 'html' ? 'html' : 'tmce'));
130+
131+
// Set the content when save.
132+
window.SetFieldContentProperty = function () {
133+
var mode = jQuery('#wp-' + editorId + '-wrap').hasClass('html-active') ? 'html' : 'tmce';
134+
var content = '';
135+
136+
if (mode === 'html') {
137+
content = jQuery('#' + editorId).val();
138+
} else if (tinymce.get(editorId)) {
139+
content = tinymce.get(editorId).getContent();
140+
}
141+
142+
SetFieldProperty('content', content);
143+
};
144+
145+
// Update the content.
146+
jQuery(document).on('change', `#${editorId}`, function () {
147+
window.SetFieldContentProperty();
148+
});
149+
111150
// Switch to visual/text mode.
112151
jQuery(`#wp-${editorId}-wrap .switch-tmce, #wp-${editorId}-wrap .switch-html`).on('click', function() {
113152
var mode = jQuery(this).hasClass('switch-tmce') ? 'tmce' : 'html';
114153

115154
window.switchEditors.go(editorId, mode);
155+
156+
// Save the current mode to field property.
157+
SetFieldProperty('gwRichTextMode', mode)
116158
});
117159
}
118160
} );

0 commit comments

Comments
 (0)