|
60 | 60 | </style> |
61 | 61 |
|
62 | 62 | <script> |
| 63 | + var gwRichTextMode; |
63 | 64 | jQuery( document ).on( 'gform_load_field_settings', function( event, field ) { |
| 65 | + gwRichTextMode = field.gwRichTextMode || 'tmce'; |
| 66 | + |
64 | 67 | var id = 'field_rich_content'; |
65 | 68 | wp.editor.remove( id ); |
66 | 69 | jQuery( '#' + id ).val( field.content ); |
|
75 | 78 | quicktags: true |
76 | 79 | } ); |
77 | 80 | } ); |
| 81 | + |
78 | 82 | jQuery( document).on( 'tinymce-editor-setup', function ( event, editor ) { |
79 | 83 | var editorId = 'field_rich_content'; |
80 | 84 | if ( editor.id === editorId ) { |
|
108 | 112 | } |
109 | 113 | } ); |
110 | 114 |
|
| 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 | + |
111 | 150 | // Switch to visual/text mode. |
112 | 151 | jQuery(`#wp-${editorId}-wrap .switch-tmce, #wp-${editorId}-wrap .switch-html`).on('click', function() { |
113 | 152 | var mode = jQuery(this).hasClass('switch-tmce') ? 'tmce' : 'html'; |
114 | 153 |
|
115 | 154 | window.switchEditors.go(editorId, mode); |
| 155 | + |
| 156 | + // Save the current mode to field property. |
| 157 | + SetFieldProperty('gwRichTextMode', mode) |
116 | 158 | }); |
117 | 159 | } |
118 | 160 | } ); |
|
0 commit comments