Skip to content

Commit 7547d70

Browse files
committed
gw-rich-text-html-fields.php: Added functionality to remember the last selected Visual or HTML editor mode.
1 parent 3053ec0 commit 7547d70

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

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

+51-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,14 @@
5252
</style>
5353

5454
<script>
55+
var formId, fieldId, editorModeKey;
5556
jQuery( document ).on( 'gform_load_field_settings', function( event, field ) {
57+
formId = field.formId;
58+
fieldId = field.id;
59+
60+
// Generate a unique key for the editor mode based on formId and fieldId.
61+
editorModeKey = `gw-rich-text-html-mode-${formId}-${fieldId}`;
62+
5663
var id = 'field_rich_content';
5764
wp.editor.remove( id );
5865
jQuery( '#' + id ).val( field.content );
@@ -72,15 +79,58 @@
7279
if ( editor.id === editorId ) {
7380
editor.settings.toolbar1 = 'bold,italic,underline,bullist,numlist,alignleft,aligncenter,alignright,link';
7481

82+
// Set the initial mode based on previous user selection.
83+
var savedMode = localStorage.getItem(editorModeKey);
84+
85+
// Wait until the TinyMCE editor is initialized before switching mode.
86+
function waitForEditorToBeReady(callback) {
87+
var interval = setInterval(function () {
88+
if (typeof tinymce !== 'undefined' && tinymce.get(editorId)) {
89+
clearInterval(interval);
90+
callback();
91+
}
92+
}, 100);
93+
}
94+
95+
waitForEditorToBeReady(function () {
96+
if (savedMode === 'html') {
97+
window.switchEditors.go(editorId, 'html');
98+
} else {
99+
window.switchEditors.go(editorId, 'tmce');
100+
}
101+
});
102+
103+
// Set the content when save.
104+
window.SetFieldContentProperty = function () {
105+
var mode = jQuery('#wp-' + editorId + '-wrap').hasClass('html-active') ? 'html' : 'tmce';
106+
var content = '';
107+
108+
if (mode === 'html') {
109+
content = jQuery('#' + editorId).val();
110+
} else if (tinymce.get(editorId)) {
111+
content = tinymce.get(editorId).getContent();
112+
}
113+
114+
SetFieldProperty('content', content);
115+
};
116+
117+
// Update the content.
118+
jQuery(document).on('change', `#${editorId}`, function () {
119+
window.SetFieldContentProperty();
120+
});
121+
75122
// Switch to visual/text mode.
76123
jQuery(`#wp-${editorId}-wrap .switch-tmce, #wp-${editorId}-wrap .switch-html`).on('click', function() {
77124
var mode = jQuery(this).hasClass('switch-tmce') ? 'tmce' : 'html';
78125

79126
window.switchEditors.go(editorId, mode);
127+
128+
// Save the current mode to localStorage.
129+
localStorage.setItem(editorModeKey, mode);
80130
});
81131
}
82132
} );
83-
</script>
133+
</script>
84134

85135
<?php
86136
} );

0 commit comments

Comments
 (0)