ckgpt-1.0.0-alpha1/js/plugins/ckgpt/plugin.js
js/plugins/ckgpt/plugin.js
(function ($, Drupal, drupalSettings, CKEDITOR) {
CKEDITOR.plugins.add('ckgpt', {
icons: 'ckgpt',
init: function (editor) {
editor.addCommand('ckGpt', {
exec: function (editor) {
const selected_text = editor.getSelection().getSelectedText();
if (selected_text.length > 0) {
// Get the API key from config.
const apiKey = editor.config.openaiApiKey;
// Disable the editor and show "Processing..." message.
editor.setReadOnly(true);
const processing_message = $('<div>Processing...</div>');
processing_message.insertAfter(editor.element.$);
// Make a call to the ChatGPT API to get corrected text.
$.ajax({
type: 'POST',
url: 'https://api.openai.com/v1/completions',
headers: {
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json',
},
data: JSON.stringify({
"model": "text-davinci-003",
'prompt': selected_text,
'max_tokens': 800,
'temperature': 0.5,
}),
success: function (response) {
// Remove the "Processing..." message and re-enable the editor.
processing_message.remove();
editor.setReadOnly(false);
// Update the editor with the corrected text.
editor.insertText(response.choices[0].text);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(errorThrown);
processing_message.remove();
editor.setReadOnly(true);
},
});
}
},
});
editor.ui.addButton('CkeditorGpt', {
label: 'ChatGPT the selected text',
command: 'ckGpt',
icon: Drupal.url.toAbsolute('/' + editor.config.modulePath + '/js/plugins/ckgpt/icons/ckgpt.png'),
});
},
});
})(jQuery, Drupal, drupalSettings, CKEDITOR);
