PluginProbe
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot / 4.2.0
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot v4.2.0
4.9.1 4.9.0 4.8.2 4.8.1 4.8.0 4.7.0 4.6.2 4.6.1 4.6.0 4.5.6 4.5.5 4.5.4 4.5.3 4.5.2 4.5.1 4.5.0 4.4.1 4.4.0 3.3.4 3.4.0 3.4.1 3.4.2 3.5.0 3.5.1 3.5.2 All 199 releases
← All changes | includes/Core/WriteWithAI.php +1002 -692 4.7.04.2.0 View file →
@@ -1,813 +1,1123 @@
1 1 <?php
2 2
3 - namespace WPDeveloper\BetterDocs\Core;
3 +namespace WPDeveloper\BetterDocs\Core;
4 4
5 -if ( ! defined( 'ABSPATH' ) ) {
6 - exit;
7 -}
5 +use WPDeveloper\BetterDocs\Utils\Base;
6 +use WPDeveloper\BetterDocs\Core\Settings;
7 +use WPDeveloper\BetterDocs\Core\PostType;
8 8
9 +use WPDeveloper\BetterDocs\Utils\Helper;
9 10
10 - use WPDeveloper\BetterDocs\Utils\Base;
11 - use WPDeveloper\BetterDocs\Core\Settings;
12 - use WPDeveloper\BetterDocs\Core\PostType;
11 +class WriteWithAI extends Base {
13 12
14 - use WPDeveloper\BetterDocs\Utils\Helper;
15 - use WPDeveloper\BetterDocs\Utils\AIHelper;
16 - use WPDeveloper\BetterDocs\Utils\AIUsage;
17 - use WPDeveloper\BetterDocs\REST\AIEdit;
13 + public $settings;
18 14
19 - class WriteWithAI extends Base {
15 + public function __construct( Settings $settings ) {
16 + $this->settings = $settings;
17 + // Get the post ID from the URL
18 + $post_id = isset($_GET['post']) ? intval($_GET['post']) : 0; // phpcs:ignore
20 19
21 - public $settings;
20 + if (!empty($_GET['post_type'])) { // phpcs:ignore
21 + $post_type = $_GET['post_type']; // phpcs:ignore
22 + } elseif ( $post_id > 0 ) {
23 + $post_type = get_post_type( $post_id );
24 + } else {
25 + $post_type = '';
26 + }
22 27
23 - public function __construct( Settings $settings ) {
24 - $this->settings = $settings;
25 - // Get the post ID from the URL
26 - $post_id = isset( $_GET[ 'post' ] ) ? intval( $_GET[ 'post' ] ) : 0; // phpcs:ignore
28 + if ( ! empty( $this->isEnabledWriteWithAI() ) && $post_type == 'docs' ) {
29 + add_action( 'admin_footer', [ $this, 'ai_autowrite_button' ] );
30 + }
31 + add_action( 'wp_ajax_generate_openai_content', [ $this, 'generate_openai_content_callback' ] );
27 32
28 - if ( ! empty( $_GET[ 'post_type' ] ) ) { // phpcs:ignore
29 - $post_type = $_GET[ 'post_type' ]; // phpcs:ignore
30 - } elseif ( $post_id > 0 ) {
31 - $post_type = get_post_type( $post_id );
32 - } else {
33 - $post_type = '';
34 - }
33 + }
35 34
36 - if ( ! empty( $this->isEnabledWriteWithAI() ) && 'docs' == $post_type ) {
37 - add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_ai_edit_assets' ) );
38 - }
39 - // Legacy AJAX handler kept for back-compat; the redesigned modal uses the REST route.
40 - add_action( 'wp_ajax_generate_openai_content', array( $this, 'generate_openai_content_callback' ) );
41 - }
35 + public function isEnabledWriteWithAI() {
36 + $isEnableAutoWrite = $this->settings->get( 'enable_write_with_ai', true );
37 + return $isEnableAutoWrite;
38 + }
42 39
43 - public function enqueue_ai_edit_assets( $hook ) {
44 - if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
45 - return;
46 - }
40 + public function isValidAPIKey( $apiKey ) {
41 + if ( empty( $apiKey ) ) {
42 + $api_response['valid'] = false;
43 + $api_response['message'] = 'Please Insert your <a href="/admin.php?page=betterdocs-settings">OpenAI API Key</a> to use this Write with AI feature.';
47 44
48 - global $post_type;
49 - if ( 'docs' !== $post_type ) {
50 - return;
51 - }
45 + return $api_response;
46 + }
52 47
53 - $api_key = $this->get_api_key();
54 - $has_key = ! empty( $api_key );
48 + $ch = curl_init( 'https://api.openai.com/v1/engines' ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_init
49 + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
50 + curl_setopt(
51 + $ch,
52 + CURLOPT_HTTPHEADER,
53 + [ //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
54 + 'Content-Type: application/json',
55 + 'Authorization: Bearer ' . $apiKey,
56 + ]
57 + );
55 58
56 - // Write with AI — loads even without a key so the modal can show its
57 - // "add an API key" banner (matches the legacy inline form behavior).
58 - betterdocs()->assets->enqueue( 'betterdocs-write-with-ai', 'blocks/write-with-ai.js' );
59 - betterdocs()->assets->enqueue( 'betterdocs-write-with-ai-style', 'blocks/write-with-ai-style.css' );
59 + $api_response = [];
60 60
61 - wp_localize_script(
62 - 'betterdocs-write-with-ai',
63 - 'betterdocsWriteWithAI',
64 - array(
65 - 'rest_url' => esc_url_raw( rest_url( 'betterdocs/v1/write-with-ai' ) ),
66 - 'rest_nonce' => wp_create_nonce( 'wp_rest' ),
67 - 'post_id' => get_the_ID(),
68 - 'has_key' => $has_key,
69 - // Term-suggestion (Docs AI Suite) wiring reused by the Write-with-AI
70 - // preview step. Endpoint + gate mirror REST\DocsAISuite / Core\DocsAISuite.
71 - 'rest_suggest_url' => esc_url_raw( rest_url( 'betterdocs/v1/ai-suggest-terms' ) ),
72 - 'suggest_terms_enabled' => (bool) $this->settings->get( 'enable_docs_ai_suite', true ),
73 - 'model' => $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' ),
74 - 'max_token' => (int) $this->settings->get( 'ai_autowrite_max_token', 2500 ),
75 - 'settings_url' => esc_url( admin_url( 'admin.php?page=betterdocs-settings#betterdocs-ai' ) ),
76 - 'woo_active' => class_exists( 'WooCommerce' ),
77 - 'is_multilingual_active' => Helper::is_multilingual_active(),
78 - 'language_options' => Helper::get_active_languages(),
79 - 'instructions' => $this->get_instruction_choices(),
80 - // From Git is a Pro feature. Pro is detected here; Git enabled/auth
81 - // status is filled in by Pro via the filter below (default: off).
82 - 'is_pro_active' => betterdocs()->is_pro_active(),
83 - 'git' => apply_filters(
84 - 'betterdocs_write_with_ai_git',
85 - array(
86 - 'enabled' => false,
87 - 'connected' => false,
88 - 'settings_url' => admin_url( 'admin.php?page=betterdocs-settings#git-sync' ),
89 - )
90 - ),
91 - )
92 - );
61 + $response = curl_exec( $ch ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_exec
62 + $httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_getinfo
93 63
94 - // AI Edit — only meaningful with a key configured.
95 - if ( ! $has_key ) {
96 - return;
97 - }
64 + curl_close( $ch ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_close
98 65
99 - betterdocs()->assets->enqueue( 'betterdocs-ai-edit', 'blocks/ai-edit.js' );
100 - betterdocs()->assets->enqueue( 'betterdocs-ai-edit-style', 'blocks/ai-edit-style.css' );
66 + if ( $httpCode == 200 ) {
67 + $api_response['valid'] = true;
68 + $api_response['message'] = 'Valid API Key';
69 + } else {
70 + $responseData = json_decode( $response, true );
71 + // Access the message data (replace 'data' with the actual key used in the response)
72 + $messageData = $responseData['error'] ? $responseData['error'] : '';
73 + $api_response['valid'] = false;
74 + $api_response['message'] = $messageData['message'] ? $messageData['message'] : 'Invalid API Key';
75 + }
101 76
102 - wp_localize_script(
103 - 'betterdocs-ai-edit',
104 - 'betterdocsAIEdit',
105 - array(
106 - 'rest_url' => esc_url_raw( rest_url( 'betterdocs/v1/ai-edit' ) ),
107 - 'rest_nonce' => wp_create_nonce( 'wp_rest' ),
108 - 'post_id' => get_the_ID(),
109 - 'instructions' => $this->get_instruction_choices(),
110 - 'actions' => AIEdit::get_localized_actions()
111 - )
112 - );
113 - }
77 + // print_r($response);
114 78
115 - public function isEnabledWriteWithAI() {
116 - $isEnableAutoWrite = $this->settings->get( 'enable_write_with_ai', true );
117 - return $isEnableAutoWrite;
118 - }
79 + return $api_response;
80 + }
119 81
120 - public function isValidAPIKey( $apiKey ) {
121 - if ( empty( $apiKey ) ) {
122 - $api_response[ 'valid' ] = false;
123 - $api_response[ 'message' ] = 'Please Insert your <a href="/admin.php?page=betterdocs-settings#betterdocs-ai">OpenAI API Key</a> to use this Write with AI feature.';
82 + public function get_api_key() {
83 + $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
84 + return $api_key;
85 + }
124 86
125 - return $api_response;
126 - }
127 87
128 - $api_response = array();
88 + public function generate_openai_response( $prompt, $keywords ) {
89 + try {
90 + $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
91 + $max_tokens = $this->settings->get( 'ai_autowrite_max_token', 1500 );
92 + $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
129 93
130 - $response = wp_safe_remote_get(
131 - 'https://api.openai.com/v1/engines',
132 - array(
133 - 'headers' => array(
134 - 'Content-Type' => 'application/json',
135 - 'Authorization' => 'Bearer ' . $apiKey,
136 - ),
137 - 'timeout' => 15,
138 - )
139 - );
94 + $api_endpoint = 'https://api.openai.com/v1/chat/completions'; // Update the endpoint based on OpenAI API version
140 95
141 - if ( is_wp_error( $response ) ) {
142 - $api_response[ 'valid' ] = false;
143 - $api_response[ 'message' ] = $response->get_error_message();
144 - return $api_response;
145 - }
96 + $request_options = array(
97 + 'headers' => array(
98 + 'Content-Type' => 'application/json',
99 + 'Authorization' => 'Bearer ' . $api_key,
100 + ),
101 + 'body' => json_encode(
102 + array( //phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
103 + 'model' => $model, // Add the model parameter here
104 + 'messages' => array(
105 + array(
106 + 'role' => 'system',
107 + 'content' => 'You are a helpful assistant who writes documentation for users.'
108 + ),
109 + array(
110 + 'role' => 'user',
111 + 'content' => $prompt
112 + ),
113 + ),
114 + 'max_tokens' => $max_tokens,
146 115
147 - $httpCode = (int) wp_remote_retrieve_response_code( $response );
148 - $body = wp_remote_retrieve_body( $response );
116 + )
117 + ),
118 + 'timeout' => 50,
119 + );
149 120
150 - if ( 200 === $httpCode ) {
151 - $api_response[ 'valid' ] = true;
152 - $api_response[ 'message' ] = 'Valid API Key';
153 - } else {
154 - $responseData = json_decode( $body, true );
155 - $messageData = ! empty( $responseData[ 'error' ] ) ? $responseData[ 'error' ] : array();
156 - $api_response[ 'valid' ] = false;
157 - $api_response[ 'message' ] = ! empty( $messageData[ 'message' ] ) ? $messageData[ 'message' ] : 'Invalid API Key';
158 - }
121 + $response = wp_remote_post( $api_endpoint, $request_options );
159 122
160 - // print_r($response);
123 + if ( is_wp_error( $response ) ) {
124 + return 'Error: ' . $response->get_error_message();
125 + } else {
126 + $body = wp_remote_retrieve_body( $response );
161 127
162 - return $api_response;
163 - }
128 + $data = json_decode( $body, true );
164 129
165 - public function get_api_key() {
166 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
167 - return $api_key;
168 - }
130 + if ( ! empty( $data['error'] ) ) {
131 + return $data['error']['message'];
132 + }
169 133
170 - /**
171 - * The built-in "Default" instruction body.
172 - *
173 - * Single source of truth shared by {@see Settings::get_default()} (which seeds
174 - * the editable "Default" instruction set) and {@see self::get_system_prompt()}
175 - * (the fallback when no saved Default content exists).
176 - *
177 - * @return string
178 - */
179 - public static function default_instruction_content() {
180 - return <<<'PROMPT'
181 -You are a Senior Technical Writer specializing in comprehensive, high-quality documentation. Your goal is to produce documentation that scores 100/100 on clarity, completeness, and structure.
134 + return $data['choices'][0]['message']['content']; // Update this line to get the assistant's message
135 + }
136 + } catch ( Exception $error ) {
137 + return 'Error: ' . $error->getMessage();
138 + }
139 + }
182 140
183 -## Output format
184 141
185 -Return only HTML body content. Never wrap output in `<!doctype>`, `<html>`, `<head>`, `<body>`, or markdown code fences (no ```html ... ```).
186 142
187 -Use semantic, Gutenberg-friendly tags only:
188 -- Headings: `<h2>`, `<h3>`, `<h4>` (do not emit `<h1>` — it is reserved for the document title)
189 -- Paragraphs: `<p>` for prose
190 -- Lists: `<ul>`/`<ol>` with `<li>` for any list of items, steps, or bullet points — never fake a list with paragraphs or `<br>`
191 -- Links: `<a href="https://...">link text</a>` with absolute URLs
192 -- Inline emphasis: `<strong>`, `<em>`, `<code>`
193 -- Code blocks: `<pre><code>...</code></pre>` for multi-line code or commands
194 -- Quotes: `<blockquote>`
195 -- Tables: `<table>` with `<thead>`, `<tbody>`, `<tr>`, `<th>`, `<td>`
196 -- Images: `<img src="..." alt="...">`
143 + public function generate_openai_content_callback() {
144 + // Verify the nonce
145 + if (!isset($_POST['ai_nonce']) || !wp_verify_nonce($_POST['ai_nonce'], 'generate_openai_content_nonce')) { //phpcs:ignore
146 + wp_send_json_error( 'Invalid nonce' );
147 + wp_die();
148 + }
197 149
198 -Apply `<span class="highlight">key term</span>` to important topic terms inside headings and to the first occurrence of each keyword in body text. Use it sparingly — never wrap whole sentences or wrap text inside `href`, `src`, `alt`, or other attributes.
150 + $prompt = sanitize_text_field($_POST['prompt']); //phpcs:ignore
151 + // $num_of_sections = sanitize_text_field($_POST['numOfSections']);
152 + // $num_of_paragraphs = sanitize_text_field($_POST['numOfParagraphs']);
153 + $keywords = sanitize_text_field($_POST['keywords']); //phpcs:ignore
199 154
200 -Do not emit `<style>`, `<script>`, `<iframe>`, `<form>`, or inline `style=""` / `class=""` attributes (other than the `highlight` class above).
155 + $ai_instance = new WriteWithAI( $this->settings );
201 156
202 -If — and only if — the user's prompt explicitly asks for raw/custom HTML, embed code, or a non-standard structure, follow that request instead of these defaults.
203 -PROMPT;
204 - }
157 + $generated_content = $ai_instance->generate_openai_response( $prompt, $keywords );
205 158
206 - /**
207 - * The saved instruction sets, normalized to a list of { id, title, content }.
208 - *
209 - * Stored in the `write_with_ai_instructions` setting. Always returns at least
210 - * the built-in "Default" set so callers never have to special-case an empty
211 - * option (e.g. a site whose stored value predates this feature).
212 - *
213 - * @return array<int,array{id:string,title:string,content:string}>
214 - */
215 - public function get_instructions() {
216 - $stored = $this->settings->get( 'write_with_ai_instructions', array() );
159 + // Send the generated content as the AJAX response
160 + wp_send_json_success( $generated_content );
161 + wp_die();
162 + }
217 163
218 - $instructions = array();
219 - if ( is_array( $stored ) ) {
220 - foreach ( $stored as $item ) {
221 - if ( ! is_array( $item ) || empty( $item['id'] ) ) {
222 - continue;
223 - }
224 - $instructions[] = array(
225 - 'id' => sanitize_key( (string) $item['id'] ),
226 - 'title' => isset( $item['title'] ) ? (string) $item['title'] : '',
227 - 'content' => isset( $item['content'] ) ? (string) $item['content'] : '',
228 - );
229 - }
230 - }
231 164
232 - // Guarantee a Default set is always present.
233 - $has_default = false;
234 - foreach ( $instructions as $item ) {
235 - if ( 'default' === $item['id'] ) {
236 - $has_default = true;
237 - break;
238 - }
239 - }
240 - if ( ! $has_default ) {
241 - array_unshift(
242 - $instructions,
243 - array(
244 - 'id' => 'default',
245 - 'title' => __( 'Default/Core', 'betterdocs' ),
246 - 'content' => self::default_instruction_content(),
247 - )
248 - );
249 - }
250 165
251 - return $instructions;
252 - }
166 + public function ai_autowrite_button() {
253 167
254 - /**
255 - * The selectable (non-default) instruction sets exposed to the editor UI.
256 - *
257 - * Only id + title are sent to the browser; the prompt body stays server-side
258 - * and is resolved at request time by {@see self::get_instruction_messages()}.
259 - *
260 - * @return array<int,array{id:string,title:string}>
261 - */
262 - public function get_instruction_choices() {
263 - $choices = array();
264 - foreach ( $this->get_instructions() as $item ) {
265 - if ( 'default' === $item['id'] ) {
266 - continue;
267 - }
268 - if ( '' === trim( $item['content'] ) ) {
269 - continue; // skip empty sets — they'd inject nothing.
270 - }
271 - $choices[] = array(
272 - 'id' => $item['id'],
273 - 'title' => '' !== trim( $item['title'] ) ? $item['title'] : $item['id'],
274 - );
275 - }
276 - return $choices;
277 - }
168 + ?>
169 + <script>
170 + var docsTitle;
278 171
279 - /**
280 - * Resolve selected instruction ids into extra `system` messages.
281 - *
282 - * The "Default" set is intentionally excluded — it is always sent as the base
283 - * system prompt by {@see self::get_system_prompt()}. Unknown or empty ids are
284 - * silently ignored. Output order follows the requested $ids order.
285 - *
286 - * @param array $ids
287 - * @return array<int,array{role:string,content:string}>
288 - */
289 - public function get_instruction_messages( $ids ) {
290 - if ( empty( $ids ) || ! is_array( $ids ) ) {
291 - return array();
292 - }
172 + function responseMessage(message) {
173 + return `<div class="warning-message">
174 + <span class="dashicons dashicons-warning"></span>
175 + <div class="footer-message">
176 + ${message}
177 + </div>
178 + </div>`;
179 + }
293 180
294 - $by_id = array();
295 - foreach ( $this->get_instructions() as $item ) {
296 - $by_id[ $item['id'] ] = $item;
297 - }
181 + function generateArticle(e) {
298 182
299 - $messages = array();
300 - $seen = array();
301 - foreach ( $ids as $id ) {
302 - $id = sanitize_key( (string) $id );
303 - if ( 'default' === $id || isset( $seen[ $id ] ) || ! isset( $by_id[ $id ] ) ) {
304 - continue;
305 - }
306 - $content = trim( $by_id[ $id ]['content'] );
307 - if ( '' === $content ) {
308 - continue;
309 - }
310 - $seen[ $id ] = true;
311 - $messages[] = array(
312 - 'role' => 'system',
313 - 'content' => $content,
314 - );
315 - }
316 183
317 - return $messages;
318 - }
184 + const title = document.getElementById('betterdocs-ai-title').value;
185 + const keywords = document.getElementById('betterdocs-ai-keyword').value;
186 + // const sectionOptions = document.getElementById('bd-autowrtite-content-section');
187 + // const numOfSections = sectionOptions.options[sectionOptions.selectedIndex].value;
319 188
320 - /**
321 - * Coerce a list of extra messages into well-formed `system` chat messages.
322 - *
323 - * Accepts either pre-built [ 'role'=>'system', 'content'=>… ] entries (as
324 - * returned by {@see self::get_instruction_messages()}) or bare strings, and
325 - * drops anything empty. Keeps the OpenAI payload builders tolerant of either
326 - * shape so callers can pass instruction ids or ready-made messages.
327 - *
328 - * @param array $extra_system
329 - * @return array<int,array{role:string,content:string}>
330 - */
331 - protected function normalize_extra_system( $extra_system ) {
332 - if ( empty( $extra_system ) || ! is_array( $extra_system ) ) {
333 - return array();
334 - }
189 + // const paragraphOptions = document.getElementById('bd-autowrtite-content-paragraph');
190 + // const numOfParagraphs = paragraphOptions.options[paragraphOptions.selectedIndex].value;
335 191
336 - $messages = array();
337 - foreach ( $extra_system as $entry ) {
338 - if ( is_string( $entry ) ) {
339 - $content = trim( $entry );
340 - $role = 'system';
341 - } elseif ( is_array( $entry ) && isset( $entry['content'] ) ) {
342 - $content = trim( (string) $entry['content'] );
343 - $role = isset( $entry['role'] ) ? (string) $entry['role'] : 'system';
344 - } else {
345 - continue;
346 - }
192 + const contentTextArea = document.getElementById('betterdocs-ai-content');
193 + const docGenerateBtnTxt = document.querySelector('.generate-btn span');
347 194
348 - if ( '' === $content ) {
349 - continue;
350 - }
195 + // Add nonce value to the data being sent
196 + const nonce = document.querySelector('input[name="ai_nonce"]').value;
197 + const isOverwrite = document.getElementById('betterdocs-ai-checkbox').checked;
198 + const generateDocLabel = "<?php echo esc_html__( 'Generate Doc', 'betterdocs' ); ?>";
199 + const reGenerateDocLabel = "<?php echo esc_html__( 'Regenerate Doc', 'betterdocs' ); ?>";
351 200
352 - $messages[] = array(
353 - 'role' => $role,
354 - 'content' => $content,
355 - );
356 - }
357 201
358 - return $messages;
359 - }
202 + // contentTextArea.value = `Write an article about ${title} in English. The article is organized by the following exact ${numOfSections} headings. Write exact ${numOfParagraphs} number of paragraphs per heading.${keywords} Use Markdown for formatting. Add an introduction and a conclusion. Style: creative. Tone: cheerful.`;
360 203
361 - public function get_system_prompt() {
362 - // Prefer the saved (editable) "Default" instruction set; fall back to the
363 - // built-in body when it's missing or has been cleared.
364 - $prompt = self::default_instruction_content();
365 - foreach ( $this->get_instructions() as $item ) {
366 - if ( 'default' === $item['id'] && '' !== trim( $item['content'] ) ) {
367 - $prompt = $item['content'];
368 - break;
369 - }
370 - }
371 204
372 - return apply_filters( 'betterdocs_write_with_ai_system_prompt', $prompt );
373 - }
205 + // Check if the title is not empty
206 + if (title.trim() !== '' && keywords.trim() !== '') {
207 + e.preventDefault();
374 208
375 - public function get_outline_system_prompt() {
376 - $prompt = <<<'PROMPT'
377 -You are a Senior Technical Writer. Produce a documentation OUTLINE only — not the full article.
209 + if (!jQuery('#betterdocs-ai-error-message').parent().hasClass('hidden')) {
210 + jQuery('#betterdocs-ai-error-message').parent().addClass('hidden');
211 + }
378 212
379 -Return ONLY a JSON array (no prose, no markdown, no code fences). Each element is an object:
380 - { "level": "h2" | "h3", "text": "Section heading" }
213 + docGenerateBtnTxt.innerHTML = "<?php echo esc_html__( 'Generating...', 'betterdocs' ); ?>";
214 + jQuery('.generate-btn').prop('disabled', true);
381 215
382 -Rules:
383 -- 5 to 9 top-level "h2" sections that comprehensively cover the topic.
384 -- Add "h3" sub-sections only where they genuinely help; keep each one directly after its parent h2.
385 -- Headings are concise, descriptive, and free of numbering.
386 -- Do not include an h1/title and do not include any text outside the JSON array.
387 -PROMPT;
216 + jQuery.post({
217 + url: ajaxurl, // Make sure ajaxurl is defined in your script
218 + type: 'POST',
219 + data: {
220 + action: 'generate_openai_content',
221 + prompt: document.querySelector('#betterdocs-ai-content').value,
222 + // numOfSections: numOfSections,
223 + // numOfParagraphs: numOfParagraphs,
224 + keywords: keywords,
225 + ai_nonce: nonce, // Pass the nonce value
226 + },
227 + success: function(response) {
228 + // Update the content in the textarea
388 229
389 - return apply_filters( 'betterdocs_write_with_ai_outline_system_prompt', $prompt );
390 - }
230 + if (response.success && (typeof response.data === 'string')) {
231 + docGenerateBtnTxt.innerHTML = "<?php echo esc_html__( 'Generated', 'betterdocs' ); ?>";
232 + setTimeout(() => {
233 + insertContentToEditor(title, response.data, isOverwrite, keywords);
234 + docGenerateBtnTxt.innerHTML = reGenerateDocLabel;
235 + jQuery('.generate-btn').removeAttr('disabled');
391 236
392 - /**
393 - * Generate a documentation outline as a structured array of sections.
394 - *
395 - * @param string $user_prompt The composed prompt (title/keywords/instructions).
396 - * @return array { success:bool, outline?:array<int,array{level:string,text:string}>, error?:string }
397 - */
398 - public function generate_outline_response( $user_prompt, $extra_system = array() ) {
399 - $result = $this->generate_text( $user_prompt, $this->get_outline_system_prompt(), $extra_system );
237 + // console.log(jQuery('.betterdocs-ai-autowrite-form-container').data('new-doc-page'));
400 238
401 - if ( empty( $result['success'] ) ) {
402 - return array(
403 - 'success' => false,
404 - 'error' => isset( $result['error'] ) ? $result['error'] : 'OpenAI error',
405 - );
406 - }
239 + // if(jQuery('.betterdocs-ai-autowrite-form-container')?.data('new-doc-page')) {
240 + // docGenerateBtnTxt.innerHTML = reGenerateDocLabel;
241 + // }
242 + }, 2000);
243 + } else {
244 + // alert(response.data.message);
245 + jQuery('#betterdocs-ai-error-message').parent().removeClass('hidden');
246 + jQuery('#betterdocs-ai-error-message').html(responseMessage(response.data.message));
247 + docGenerateBtnTxt.innerHTML = generateDocLabel;
248 + jQuery('.generate-btn').removeAttr('disabled');
407 249
408 - $outline = $this->parse_outline( (string) $result['content'] );
250 + }
251 + },
252 + error: function(error) {
253 + console.error(error);
254 + },
255 + });
409 256
410 - if ( empty( $outline ) ) {
411 - return array(
412 - 'success' => false,
413 - 'error' => 'The AI returned an outline we could not read. Please try again.',
414 - );
415 - }
257 + }
258 + }
416 259
417 - return array(
418 - 'success' => true,
419 - 'outline' => $outline,
420 - );
421 - }
260 + // Function to update the textarea
261 + function updateTextarea() {
262 + const title = document.getElementById('betterdocs-ai-title').value;
263 + const keywords = document.getElementById('betterdocs-ai-keyword').value;
264 + const sectionOptions = document.getElementById('bd-autowrtite-content-section');
265 + let language = 'English';
422 266
423 - /**
424 - * Parse a model outline response (ideally a JSON array) into a clean list of
425 - * { level, text } sections. Tolerates code fences and stray prose.
426 - *
427 - * @param string $content
428 - * @return array<int,array{level:string,text:string}>
429 - */
430 - protected function parse_outline( $content ) {
431 - $content = trim( $content );
432 - $content = preg_replace( '/^```(?:json)?\s*/i', '', $content );
433 - $content = preg_replace( '/```\s*$/', '', $content );
267 + if (language === '') {
268 + language = 'English';
269 + }
434 270
435 - // Grab the first JSON array if the model wrapped it in prose.
436 - if ( preg_match( '/\[[\s\S]*\]/', $content, $m ) ) {
437 - $content = $m[0];
438 - }
271 + let keywordsText = keywords !== '' ? ` and incorporate the keywords: ${keywords}` : '';
439 272
440 - $decoded = json_decode( $content, true );
441 - if ( ! is_array( $decoded ) ) {
442 - return array();
443 - }
273 + const contentTextArea = document.getElementById('betterdocs-ai-content');
444 274
445 - $outline = array();
446 - foreach ( $decoded as $item ) {
447 - if ( ! is_array( $item ) || empty( $item['text'] ) ) {
448 - continue;
449 - }
450 - $level = isset( $item['level'] ) && 'h3' === strtolower( (string) $item['level'] ) ? 'h3' : 'h2';
451 - $text = sanitize_text_field( (string) $item['text'] );
452 - if ( '' === $text ) {
453 - continue;
454 - }
455 - $outline[] = array( 'level' => $level, 'text' => $text );
456 - }
275 + if (!jQuery('#betterdocs-ai-error-message').parent().hasClass('hidden')) {
276 + jQuery('#betterdocs-ai-error-message').parent().addClass('hidden');
277 + }
457 278
458 - return $outline;
459 - }
279 + contentTextArea.value = `Generate a documentation using HTML heading tags for '${title}'. Include relevant details on ${keywords} in the documentation. Ensure all content is enclosed with <p> tags and apply a <span> tag with the class 'highlight' to headings and topic tags for emphasis.`;
280 + }
460 281
461 - public function generate_openai_response( $prompt, $keywords, $max_tokens = null, $extra_system = array() ) {
462 - try {
463 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
464 - // Caller may raise the cap (e.g. a "large" doc) above the saved default.
465 - $max_tokens = null !== $max_tokens ? (int) $max_tokens : $this->settings->get( 'ai_autowrite_max_token', 2500 );
466 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
282 + function convertMarkdownToHTML(markdownContent) {
283 + // Simple Markdown to HTML conversion (you may need to enhance this based on your needs)
284 + const htmlContent = markdownContent
285 + .replace(/^# (.+)$/gm, '<h1>$1</h1>')
286 + .replace(/^## (.+)$/gm, '<h2>$1</h2>')
287 + .replace(/^### (.+)$/gm, '<h3>$1</h3>')
288 + .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
289 + .replace(/\*(.+?)\*/g, '<em>$1</em>');
467 290
468 - $api_endpoint = 'https://api.openai.com/v1/chat/completions'; // Update the endpoint based on OpenAI API version
291 + return htmlContent;
292 + }
469 293
470 - $messages = array_merge(
471 - array(
472 - array(
473 - 'role' => 'system',
474 - 'content' => $this->get_system_prompt()
475 - )
476 - ),
477 - $this->normalize_extra_system( $extra_system ),
478 - array(
479 - array(
480 - 'role' => 'user',
481 - 'content' => $prompt
482 - )
483 - )
484 - );
294 + function replaceHeadingTitle(content, title, overviewTitle) {
295 + let regex = new RegExp(title, 'g');
296 + let updateContent = content.replace(regex, overviewTitle);
297 + return updateContent;
298 + }
485 299
486 - $request_body = AIHelper::build_openai_payload(
487 - $model,
488 - $messages,
489 - $max_tokens,
490 - null,
491 - 'write_with_ai'
492 - );
300 + function removeFirstHeading(htmlString) {
301 + var newDiv = document.createElement('div');
302 + newDiv.innerHTML = htmlString;
303 + var firstHeading = newDiv.querySelector('h1');
304 + if (firstHeading) {
305 + firstHeading.parentNode.removeChild(firstHeading);
306 + }
307 + return newDiv.innerHTML;
308 + }
493 309
494 - $request_options = array(
495 - 'headers' => array(
496 - 'Content-Type' => 'application/json',
497 - 'Authorization' => 'Bearer ' . $api_key
498 - ),
499 - 'body' => json_encode( $request_body ),
500 - 'timeout' => 300
501 - );
502 310
503 - // GPT-5.5 reasoning can run well past the default limits; give PHP and
504 - // the HTTP call room to finish (still subject to server php-fpm/nginx limits).
505 - if ( function_exists( 'set_time_limit' ) ) {
506 - set_time_limit( 300 ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running AI generation needs an extended limit; still bounded by server fpm/nginx timeouts.
507 - }
311 + function wrapwithHeighlight(inputString, keywords) {
312 + let modifiedString = inputString.replace(/<(h\d)(.*?)>(.*?)<\/\1>/g, '<$1$2><span class="highlight">$3</span></$1>');
508 313
509 - $response = wp_remote_post( $api_endpoint, $request_options );
314 + const keywordArray = keywords.split(',').map(keyword => keyword.trim());
510 315
511 - if ( is_wp_error( $response ) ) {
512 - return 'Error: ' . $response->get_error_message();
513 - } else {
514 - $body = wp_remote_retrieve_body( $response );
316 + keywordArray.forEach(keyword => {
317 + modifiedString = modifiedString.replace(new RegExp(`\\b(${keyword})\\b`, 'gi'), '<span class="highlight">$1</span>');
318 + });
515 319
516 - $data = json_decode( $body, true );
320 + return modifiedString;
321 + }
517 322
518 - if ( ! empty( $data[ 'error' ] ) ) {
519 - return $data[ 'error' ][ 'message' ];
520 - }
323 + function getBodyContent(htmlString) {
324 + var match = htmlString.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
521 325
522 - return $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ]; // Update this line to get the assistant's message
523 - }
524 - } catch ( Exception $error ) {
525 - return 'Error: ' . $error->getMessage();
526 - }
527 - }
326 + // Check if match is null before accessing match[1]
327 + if (match) {
328 + console.log(match[1].replace(/<p>\s+/g, '<p>'));
329 + return match[1].replace(/<p>\s+/g, '<p>');
330 + } else {
331 + return '';
332 + }
333 + }
528 334
529 - public function generate_openai_response_ai_edit( $prompt, $extra_system = array() ) {
530 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
531 - $max_tokens = $this->settings->get( 'ai_autowrite_max_token', 2500 );
532 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
533 335
534 - $api_endpoint = 'https://api.openai.com/v1/chat/completions';
535 336
536 - $messages = array_merge(
537 - array(
538 - array(
539 - 'role' => 'system',
540 - 'content' => $this->get_system_prompt()
541 - )
542 - ),
543 - $this->normalize_extra_system( $extra_system ),
544 - array(
545 - array(
546 - 'role' => 'user',
547 - 'content' => $prompt
548 - )
549 - )
550 - );
337 + function insertContentToEditor(title, htmlContent, isOverwrite, keywords) {
551 338
552 - $payload = AIHelper::build_openai_payload(
553 - $model,
554 - $messages,
555 - $max_tokens,
556 - null,
557 - 'write_with_ai'
558 - );
339 + const {
340 + dispatch,
341 + select
342 + } = wp.data;
559 343
560 - $request_options = array(
561 - 'headers' => array(
562 - 'Content-Type' => 'application/json',
563 - 'Authorization' => 'Bearer ' . $api_key
564 - ),
565 - 'body' => wp_json_encode( $payload ),
566 - 'timeout' => 300
567 - );
344 + htmlContent = getBodyContent(htmlContent);
345 + htmlContent = removeFirstHeading(htmlContent);
346 + htmlContent = wrapwithHeighlight(htmlContent, keywords);
347 + const isPostContent = `<?php echo isset($_GET['post']) ? esc_html(get_the_content($_GET['post'])) : ''; // phpcs:ignore ?>`;
568 348
569 - // GPT-5.5 reasoning can run well past the default limits; give PHP and
570 - // the HTTP call room to finish (still subject to server php-fpm/nginx limits).
571 - if ( function_exists( 'set_time_limit' ) ) {
572 - set_time_limit( 300 ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running AI generation needs an extended limit; still bounded by server fpm/nginx timeouts.
573 - }
349 + const blocks = wp.blocks.rawHandler({
350 + HTML: htmlContent
351 + });
574 352
575 - $response = wp_remote_post( $api_endpoint, $request_options );
353 + dispatch('core/editor').editPost({
354 + title: title,
355 + });
576 356
577 - if ( is_wp_error( $response ) ) {
578 - return array(
579 - 'success' => false,
580 - 'error' => $response->get_error_message(),
581 - 'model' => $model
582 - );
583 - }
357 + const selectedBlockClientId = select('core/block-editor').getSelectedBlockClientId();
584 358
585 - $body = wp_remote_retrieve_body( $response );
586 - $data = json_decode( $body, true );
359 + const allBlocks = select('core/block-editor').getBlocks();
587 360
588 - if ( ! empty( $data[ 'error' ] ) ) {
589 - return array(
590 - 'success' => false,
591 - 'error' => isset( $data[ 'error' ][ 'message' ] ) ? $data[ 'error' ][ 'message' ] : 'OpenAI error',
592 - 'model' => $model,
593 - 'raw' => $data
594 - );
595 - }
361 + if (isOverwrite || isPostContent === '') {
596 362
597 - $content = isset( $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] ) ? $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] : '';
598 - $usage = isset( $data[ 'usage' ] ) && is_array( $data[ 'usage' ] ) ? $data[ 'usage' ] : array();
363 + allBlocks.forEach((block) => {
364 + dispatch('core/block-editor').removeBlock(block.clientId);
365 + });
366 + dispatch('core/block-editor').insertBlocks(blocks);
599 367
600 - return array(
601 - 'success' => true,
602 - 'content' => $content,
603 - 'model' => $model,
604 - 'prompt_tokens' => isset( $usage[ 'prompt_tokens' ] ) ? (int) $usage[ 'prompt_tokens' ] : null,
605 - 'completion_tokens' => isset( $usage[ 'completion_tokens' ] ) ? (int) $usage[ 'completion_tokens' ] : null,
606 - 'total_tokens' => isset( $usage[ 'total_tokens' ] ) ? (int) $usage[ 'total_tokens' ] : null,
607 - 'finish_reason' => isset( $data[ 'choices' ][ 0 ][ 'finish_reason' ] ) ? $data[ 'choices' ][ 0 ][ 'finish_reason' ] : null
608 - );
609 - }
368 + } else if (selectedBlockClientId) {
369 + const selectedIndex = select('core/block-editor').getBlockIndex(selectedBlockClientId);
370 + dispatch('core/block-editor').insertBlocks(blocks, selectedIndex + 1);
371 + } else {
372 + dispatch('core/block-editor').insertBlocks(blocks);
373 + }
610 374
611 - /**
612 - * Generic chat completion using the Write-with-AI model/token/key settings.
613 - *
614 - * Shared by lightweight, plain-text generators (glossary definitions, FAQ answers)
615 - * that need the same dynamic model as Write with AI / AI Edit but a caller-supplied
616 - * system prompt instead of the doc-authoring HTML prompt. Returns the same structured
617 - * array shape as {@see self::generate_openai_response_ai_edit()}.
618 - *
619 - * @param string $user_prompt The user message.
620 - * @param string $system_prompt Optional system message (omitted when empty).
621 - * @return array { success:bool, content?:string, error?:string, model:string, *_tokens?:int }
622 - */
623 - public function generate_text( $user_prompt, $system_prompt = '', $extra_system = array() ) {
624 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
625 - $max_tokens = $this->settings->get( 'ai_autowrite_max_token', 2500 );
626 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
375 + closeWriteWithAIForm('afterInsertContent');
376 + }
627 377
628 - $messages = array();
629 - if ( $system_prompt !== '' ) {
630 - $messages[] = array(
631 - 'role' => 'system',
632 - 'content' => $system_prompt
633 - );
634 - }
635 - foreach ( $this->normalize_extra_system( $extra_system ) as $extra ) {
636 - $messages[] = $extra;
637 - }
638 - $messages[] = array(
639 - 'role' => 'user',
640 - 'content' => $user_prompt
641 - );
378 + function closeWriteWithAIForm(after) {
379 + jQuery('.betterdocs-ai-autowrite-form-container').addClass('hidden');
380 + jQuery('#betterdocs-ai-autowrite-form-container-overlay').addClass('hidden');
381 + jQuery('.betterdocs-ai-button').addClass('regenerate-btn');
382 + }
642 383
643 - $api_endpoint = 'https://api.openai.com/v1/chat/completions';
644 384
645 - $payload = AIHelper::build_openai_payload( $model, $messages, $max_tokens, null, 'write_with_ai' );
385 + document.addEventListener('DOMContentLoaded', function() {
646 386
647 - $request_options = array(
648 - 'headers' => array(
649 - 'Content-Type' => 'application/json',
650 - 'Authorization' => 'Bearer ' . $api_key
651 - ),
652 - 'body' => wp_json_encode( $payload ),
653 - 'timeout' => 300
654 - );
387 + // Subscribe to changes in the editor state
388 + let previousDocsTitle = '';
655 389
656 - // GPT-5.5 reasoning can run well past the default limits; give PHP and
657 - // the HTTP call room to finish (still subject to server php-fpm/nginx limits).
658 - if ( function_exists( 'set_time_limit' ) ) {
659 - set_time_limit( 300 );
660 - }
390 + wp.data.subscribe(() => {
391 + // Get the updated post title
392 + // const docsTitle = wp.data.select('core/editor').getEditedPostAttribute('title');
661 393
662 - $response = wp_remote_post( $api_endpoint, $request_options );
394 + const docsTitle = wp.data.select('core/editor').getEditedPostAttribute('title');
663 395
664 - if ( is_wp_error( $response ) ) {
665 - return array(
666 - 'success' => false,
667 - 'error' => $response->get_error_message(),
668 - 'model' => $model
669 - );
670 - }
396 + // Check if the title has changed
397 + if (docsTitle !== previousDocsTitle) {
398 + let currentKeywords = jQuery('#betterdocs-ai-keyword').val();
399 + if (!currentKeywords) {
400 + currentKeywords = '{Documentation Keywords}';
401 + }
402 + const currentPrompt = `Generate documentation using HTML heading tags for '${docsTitle?docsTitle:'{Documentation title}'}'. Include relevant details on ${currentKeywords} in the documentation. Ensure all content is enclosed with <p> tags and apply a <span> tag with the class 'highlight' to headings and topic tags for emphasis.`;
403 + jQuery('#betterdocs-ai-content').val(currentPrompt);
671 404
672 - $body = wp_remote_retrieve_body( $response );
673 - $data = json_decode( $body, true );
405 + jQuery('#betterdocs-ai-title').val(docsTitle);
674 406
675 - if ( ! empty( $data[ 'error' ] ) ) {
676 - return array(
677 - 'success' => false,
678 - 'error' => isset( $data[ 'error' ][ 'message' ] ) ? $data[ 'error' ][ 'message' ] : 'OpenAI error',
679 - 'model' => $model,
680 - 'raw' => $data
681 - );
682 - }
407 + previousDocsTitle = docsTitle;
408 + }
683 409
684 - $content = isset( $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] ) ? $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] : '';
685 - $usage = isset( $data[ 'usage' ] ) && is_array( $data[ 'usage' ] ) ? $data[ 'usage' ] : array();
686 410
687 - return array(
688 - 'success' => true,
689 - 'content' => $content,
690 - 'model' => $model,
691 - 'prompt_tokens' => isset( $usage[ 'prompt_tokens' ] ) ? (int) $usage[ 'prompt_tokens' ] : null,
692 - 'completion_tokens' => isset( $usage[ 'completion_tokens' ] ) ? (int) $usage[ 'completion_tokens' ] : null,
693 - 'total_tokens' => isset( $usage[ 'total_tokens' ] ) ? (int) $usage[ 'total_tokens' ] : null,
694 - 'finish_reason' => isset( $data[ 'choices' ][ 0 ][ 'finish_reason' ] ) ? $data[ 'choices' ][ 0 ][ 'finish_reason' ] : null
695 - );
696 - }
411 + });
412 + });
697 413
698 - /**
699 - * Generate an OpenAI chat completion with a caller-supplied system + user
700 - * prompt. Mirrors generate_openai_response_ai_edit() (same key/model/token
701 - * floor/timeout handling and return shape) but does NOT force the
702 - * documentation-writer system prompt, so callers such as the Docs AI Suite
703 - * (taxonomy suggestions, excerpts) can supply task-appropriate instructions.
704 - *
705 - * @param string $system_prompt System instruction for the model.
706 - * @param string $user_prompt User message / content payload.
707 - * @param float|null $temperature Optional sampling temperature (ignored for gpt-5*).
708 - * @return array{success:bool,content?:string,error?:string,model:string,...}
709 - */
710 - public function generate_openai_response_raw( $system_prompt, $user_prompt, $temperature = null ) {
711 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
712 - $max_tokens = $this->settings->get( 'ai_autowrite_max_token', 2500 );
713 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
714 414
715 - $api_endpoint = 'https://api.openai.com/v1/chat/completions';
415 + // This example assumes that this code is executed when your script is loaded.
416 + // You may want to place it within the appropriate context in your application.
716 417
717 - $payload = AIHelper::build_openai_payload(
718 - $model,
719 - array(
720 - array(
721 - 'role' => 'system',
722 - 'content' => $system_prompt
723 - ),
724 - array(
725 - 'role' => 'user',
726 - 'content' => $user_prompt
727 - )
728 - ),
729 - $max_tokens,
730 - $temperature,
731 - 'write_with_ai'
732 - );
733 418
734 - $request_options = array(
735 - 'headers' => array(
736 - 'Content-Type' => 'application/json',
737 - 'Authorization' => 'Bearer ' . $api_key
738 - ),
739 - 'body' => wp_json_encode( $payload ),
740 - 'timeout' => 300
741 - );
419 + function writeWithAIForm() {
742 420
743 - if ( function_exists( 'set_time_limit' ) ) {
744 - set_time_limit( 300 );
745 - }
421 + let title = `<?php echo isset($_GET['post']) ? esc_html(get_the_title($_GET['post'])) : ''; // phpcs:ignore ?>`;
422 + if (docsTitle) {
423 + title = docsTitle;
424 + }
746 425
747 - $response = wp_remote_post( $api_endpoint, $request_options );
426 + const promtTitle = `<?php echo isset($_GET['post']) ? esc_html(get_the_title($_GET['post'])) : '{Documentation Title}'; // phpcs:ignore ?>`;
427 + const titlePlaceholder = "<?php echo esc_attr__( 'Enter a descriptive title for your documentation.', 'betterdocs' ); ?>";
428 + const keywords = "<?php echo esc_attr( '{Documentation Keywords}' ); ?>";
429 + const keywordsPlaceholder = "<?php echo esc_attr__( 'Add keywords to generate precise & relevant documentation (comma-separated).', 'betterdocs' ); ?>";
430 + const language = "<?php echo esc_attr( 'English' ); ?>";
431 + const titleLabel = "<?php echo esc_html__( 'Documentation Title:', 'betterdocs' ); ?>";
432 + const keywordLabel = "<?php echo esc_html__( 'Keywords:', 'betterdocs' ); ?>";
433 + const secLabel = "<?php echo esc_html__( '# of Sections:', 'betterdocs' ); ?>";
434 + const paraLabel = "<?php echo esc_html__( '# of Paragraph Per Section: ', 'betterdocs' ); ?>";
435 + const langLabel = "<?php echo esc_html__( 'Language:', 'betterdocs' ); ?>";
436 + const promtLabel = "<?php echo esc_html__( 'Prompt:', 'betterdocs' ); ?>";
437 + const promtBtnLabel = "<?php echo esc_html__( 'Generate Prompt', 'betterdocs' ); ?>";
438 + let promtArticleLabel = "<?php echo esc_html__( 'Generate Doc', 'betterdocs' ); ?>";
439 + const checkboxLabel = "<?php echo esc_html__( 'Overwrite your existing Doc:', 'betterdocs' ); ?>";
440 + const nonce = "<?php echo esc_attr( wp_create_nonce( 'generate_openai_content_nonce' ) ); ?>";
748 441
749 - if ( is_wp_error( $response ) ) {
750 - return array(
751 - 'success' => false,
752 - 'error' => $response->get_error_message(),
753 - 'model' => $model
754 - );
755 - }
442 + <?php
443 + $is_valid = $this->get_api_key();
444 + $disable_field = 'disabled-input-field';
445 + if ( $this->get_api_key() ) {
446 + $disable_field = '';
447 + }
448 + ?>
756 449
757 - $body = wp_remote_retrieve_body( $response );
758 - $data = json_decode( $body, true );
450 + let hiddenClass = 'hidden';
451 + let newDocPageAtt = 'data-new-doc-page="true"';
452 + const isPostContent = `<?php echo isset($_GET['post']) ? esc_html(get_the_content($_GET['post'])) : ''; // phpcs:ignore ?>`;
759 453
760 - if ( ! empty( $data[ 'error' ] ) ) {
761 - return array(
762 - 'success' => false,
763 - 'error' => isset( $data[ 'error' ][ 'message' ] ) ? $data[ 'error' ][ 'message' ] : 'OpenAI error',
764 - 'model' => $model,
765 - 'raw' => $data
766 - );
767 - }
454 + if (isPostContent !== '') {
455 + hiddenClass = '';
456 + newDocPageAtt = '';
457 + }
768 458
769 - $content = isset( $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] ) ? $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] : '';
770 - $usage = isset( $data[ 'usage' ] ) && is_array( $data[ 'usage' ] ) ? $data[ 'usage' ] : array();
771 459
772 - return array(
773 - 'success' => true,
774 - 'content' => $content,
775 - 'model' => $model,
776 - 'prompt_tokens' => isset( $usage[ 'prompt_tokens' ] ) ? (int) $usage[ 'prompt_tokens' ] : null,
777 - 'completion_tokens' => isset( $usage[ 'completion_tokens' ] ) ? (int) $usage[ 'completion_tokens' ] : null,
778 - 'total_tokens' => isset( $usage[ 'total_tokens' ] ) ? (int) $usage[ 'total_tokens' ] : null,
779 - 'finish_reason' => isset( $data[ 'choices' ][ 0 ][ 'finish_reason' ] ) ? $data[ 'choices' ][ 0 ][ 'finish_reason' ] : null
780 - );
781 - }
460 + // const prompt = `Make a knowledge base article with html heading tags about [${title}] in [${language}]. Here is some topic to describe the article: [${keywords}]. and wrap the content with p tag also add a span tag with a class named 'highlight' to all the heading and topic tags in the article.`;
782 461
783 - public function generate_openai_content_callback() {
784 - // Verify the nonce
785 - $ai_nonce = isset( $_POST['ai_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ai_nonce'] ) ) : '';
786 - if ( ! wp_verify_nonce( $ai_nonce, 'generate_openai_content_nonce' ) ) {
787 - wp_send_json_error( 'Invalid nonce' );
788 - wp_die();
789 - }
462 + // const prompt = `Create a details knowledge base article in [${language}] about [${title}] with html heading tags. Here is some topic to describe the article: [${keywords}]. And wrap the content with p tag also add a span tag with a class named 'highlight' to all the heading and topic tags in the article.`;
790 463
791 - if ( ! current_user_can( 'edit_posts' ) ) {
792 - wp_send_json_error( 'Insufficient permissions' );
793 - wp_die();
794 - }
464 + const prompt = `Generate a documentation using HTML heading tags for '${promtTitle}'. Include relevant details on ${keywords} in the documentation. Ensure all content is enclosed with <p> tags and apply a <span> tag with the class 'highlight' to headings and topic tags for emphasis.`;
795 465
796 - $prompt = isset( $_POST['prompt'] ) ? sanitize_text_field( wp_unslash( $_POST['prompt'] ) ) : '';
797 - $keywords = isset( $_POST['keywords'] ) ? sanitize_text_field( wp_unslash( $_POST['keywords'] ) ) : '';
466 + const aiIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="21" height="20" viewBox="0 0 21 20" fill="none">
467 + <g clip-path="url(#clip0_2460_1729)">
468 + <path d="M10.3956 18.8608L6.10991 19.2322L6.48134 14.9465L15.3956 6.08936C15.5287 5.95329 15.6876 5.84518 15.863 5.77137C16.0384 5.69756 16.2268 5.65954 16.4171 5.65954C16.6074 5.65954 16.7957 5.69756 16.9711 5.77137C17.1466 5.84518 17.3054 5.95329 17.4385 6.08936L19.2528 7.91793C19.3865 8.05083 19.4926 8.20886 19.565 8.38293C19.6375 8.55701 19.6747 8.74368 19.6747 8.93221C19.6747 9.12075 19.6375 9.30742 19.565 9.48149C19.4926 9.65557 19.3865 9.8136 19.2528 9.9465L10.3956 18.8608ZM1.7042 5.67507C1.20277 5.58793 1.20277 4.86793 1.7042 4.78079C2.59203 4.62626 3.41374 4.21085 4.06456 3.58751C4.71538 2.96417 5.16583 2.16113 5.35848 1.28079L5.38848 1.14221C5.49705 0.647929 6.20277 0.643643 6.31705 1.13936L6.35277 1.29936C6.55248 2.17579 7.0067 2.97367 7.65837 3.59281C8.31005 4.21195 9.13013 4.62475 10.0156 4.77936C10.5199 4.86507 10.5199 5.58936 10.0156 5.67793C9.13005 5.83218 8.3098 6.24465 7.65787 6.86354C7.00594 7.48243 6.5514 8.28014 6.35134 9.1565L6.3142 9.31793C6.20134 9.81221 5.49563 9.80936 5.38705 9.31364L5.35848 9.17507C5.16564 8.29433 4.71476 7.49102 4.06339 6.86764C3.41202 6.24426 2.58969 5.82908 1.70134 5.67507H1.7042Z" stroke="white" stroke-width="1.42857" stroke-linecap="round" stroke-linejoin="round"/>
469 + </g>
470 + <defs>
471 + <clipPath id="clip0_2460_1729">
472 + <rect width="20" height="20" fill="white" transform="translate(0.5)"/>
473 + </clipPath>
474 + </defs>
475 + </svg>`;
798 476
799 - $ai_instance = new WriteWithAI( $this->settings );
800 477
801 - $generated_content = $ai_instance->generate_openai_response( $prompt, $keywords );
802 478
803 - // Count a successful generation (skip obvious upstream errors).
804 - if ( is_string( $generated_content ) && $generated_content !== '' && strpos( $generated_content, 'Error:' ) !== 0 ) {
805 - $post_id = isset( $_POST[ 'post_id' ] ) ? intval( $_POST[ 'post_id' ] ) : 0; //phpcs:ignore
806 - AIUsage::record( 'write_with_ai', $post_id );
807 - }
479 + return `
480 + <div class="betterdocs-ai-autowrite-form-container hidden" ${newDocPageAtt}>
481 + <div class="betterdocs-ai-autowrite-form-content">
482 + <div class="betterdocs-ai-autowrite-top-part">
483 + <div class="autowrite-heading">
484 + <span class="autowrite-icon">
485 + <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none">
486 + <g clip-path="url(#clip0_2453_20882)">
487 + <path d="M15.8322 30.1765L8.97508 30.7708L9.56936 23.9136L23.8322 9.74219C24.0451 9.52448 24.2993 9.3515 24.58 9.23341C24.8606 9.11531 25.162 9.05447 25.4665 9.05447C25.771 9.05447 26.0724 9.11531 26.3531 9.23341C26.6337 9.3515 26.8879 9.52448 27.1008 9.74219L30.0037 12.6679C30.2176 12.8805 30.3874 13.1334 30.5033 13.4119C30.6192 13.6904 30.6788 13.9891 30.6788 14.2908C30.6788 14.5924 30.6192 14.8911 30.5033 15.1696C30.3874 15.4481 30.2176 15.701 30.0037 15.9136L15.8322 30.1765ZM1.92593 9.07933C1.12365 8.9399 1.12365 7.7879 1.92593 7.64848C3.34647 7.40124 4.6612 6.73658 5.70251 5.73923C6.74382 4.74188 7.46455 3.45703 7.77279 2.04848L7.82079 1.82676C7.99451 1.03591 9.12365 1.02905 9.30651 1.82219L9.36365 2.07819C9.68319 3.48048 10.4099 4.75709 11.4526 5.74772C12.4953 6.73834 13.8074 7.39881 15.2242 7.64619C16.0311 7.78333 16.0311 8.94219 15.2242 9.0839C13.8073 9.33071 12.4949 9.99066 11.4518 10.9809C10.4087 11.9711 9.68146 13.2474 9.36136 14.6496L9.30193 14.9079C9.12136 15.6988 7.99222 15.6942 7.81851 14.901L7.77279 14.6793C7.46424 13.2702 6.74284 11.9849 5.70064 10.9874C4.65845 9.99003 3.34273 9.32574 1.92136 9.07933H1.92593Z" stroke="#E31B54" stroke-width="2.28571" stroke-linecap="round" stroke-linejoin="round"/>
488 + </g>
489 + <defs>
490 + <clipPath id="clip0_2453_20882">
491 + <rect width="32" height="32" fill="white"/>
492 + </clipPath>
493 + </defs>
494 + </svg>
495 + </span>
496 + <h1><?php echo esc_html__( 'Write Documentation with BetterDocs AI', 'betterdocs' ); ?></h1>
808 497
809 - // Send the generated content as the AJAX response
810 - wp_send_json_success( $generated_content );
811 - wp_die();
812 - }
498 + </div>
499 + <div class="autowrite-subheadding">
500 + <p><?php echo esc_html__( 'Generate documentation effortlessly with BetterDocs AI. Simply input your doc title, keywords, prompt and let the system automatically generate comprehensive documentation tailored to your needs.', 'betterdocs' ); ?></p>
501 + </div>
502 +
503 + <?php if ( empty( $this->get_api_key() ) ) : ?>
504 + <div id="betterdocs-ai-message">
505 + <div class="warning-message">
506 + <span class="dashicons dashicons-warning"></span>
507 + <div>
508 + <?php echo wp_kses_post( 'Please Insert your <a target="_blank" href="' . esc_url( admin_url( 'admin.php?page=betterdocs-settings&tab=tab-ai-autowrite' ) ) . '">OpenAI API Key</a> to use this Write with AI feature.', 'betterdocs' ); ?>
509 + </div>
510 + </div>
511 +
512 + </div>
513 + <?php endif; ?>
514 +
515 + <div class="form-group hidden">
516 + <div id="betterdocs-ai-error-message"></div>
517 + </div>
518 +
519 + </div>
520 + <form id="betterdocs-ai-form" class="<?php echo esc_attr( $disable_field ); ?>">
521 + <div class="form-inner-content">
522 + <div class="form-group">
523 + <label for="betterdocs-ai-title">${titleLabel}</label>
524 + <input type="text" placeholder="${titlePlaceholder}" id="betterdocs-ai-title" name="betterdocs-ai-title" required value="${title}">
525 + </div>
526 +
527 + <div class="form-group">
528 + <label for="betterdocs-ai-keyword">${keywordLabel}</label>
529 + <input type="text" placeholder="${keywordsPlaceholder}" id="betterdocs-ai-keyword" name="betterdocs-ai-keyword" required>
530 + </div>
531 +
532 + <div class="form-group prompt-field">
533 + <label for="betterdocs-ai-content">${promtLabel}</label>
534 + <textarea id="betterdocs-ai-content" name="betterdocs-ai-content" rows="6" required>${prompt}</textarea>
535 + <p class="input-description"><?php echo esc_html__( 'Ensure you include a clear and detailed prompt to receive the desired output. Follow the guidelines provided for the best results.', 'betterdocs' ); ?></p>
536 + </div>
537 + <div class="betterdocs-ai-checkbox-field ${hiddenClass}">
538 + <div class="form-group">
539 + <div class="checkbox-field-label">
540 + <label for="betterdocs-ai-checkbox">${checkboxLabel}</label>
541 + <p class="input-description"><?php echo esc_html__( 'Overwrite the existing doc with the AI Generated Content. If Disabled, new AI Generated content will be added in the section you are currently editing.', 'betterdocs' ); ?></p>
542 + </div>
543 +
544 + <div class="checkbox-input-field">
545 + <input type="checkbox" id="betterdocs-ai-checkbox" name="betterdocs-ai-checkbox" data-overwrite="false">
546 + <label for="betterdocs-ai-checkbox" class="toggle-label"></label>
547 + </div>
548 + </div>
549 + </div>
550 +
551 + <input type="hidden" name="ai_nonce" value="${nonce}" />
552 + </div>
553 + <div class="generate-button-container">
554 + <button type="submit" class="generate-btn" onclick="generateArticle(event)">
555 + ${aiIcon} <span>${promtArticleLabel}</span>
556 + </button>
557 + </div>
558 + </form>
559 + </div>
560 +
561 + <div class="bd-close-button" onclick="closeWriteWithAIForm('afterClosedClicked')">✕</div>
562 + </div>
563 +
564 + <div id="betterdocs-ai-autowrite-form-container-overlay" class="hidden"></div>
565 + `;
566 + }
567 +
568 + jQuery(document).on('click', '.regenerate-btn', function() {
569 + jQuery('.betterdocs-ai-autowrite-form-container').removeClass('hidden');
570 + jQuery('#betterdocs-ai-autowrite-form-container-overlay').removeClass('hidden');
571 + });
572 +
573 + jQuery(document).ready(function($) {
574 + // Check if we are in the Edit Post screen
575 +
576 + if ($('.block-editor-page').length > 0) {
577 +
578 + const bdAIButton = $(`<div class="betterdocs-ai-button-container">
579 + <button class="betterdocs-ai-button">
580 + <img src="<?php echo esc_url( BETTERDOCS_ABSURL . 'assets/admin/images/betterdocs-icon-white.png' ); ?>" alt="<?php echo esc_attr__( 'betterdocs icon', 'betterdocs' ); ?>" />
581 + <span><?php echo esc_html__( 'Write with AI', 'betterdocs' ); ?></span>
582 + </button>
583 + </div>`);
584 +
585 +
586 + const closeBtn = $('bd-close-button');
587 +
588 + const formHtml = writeWithAIForm();
589 + $(formHtml).addClass('hidden');
590 +
591 + $(document).on('click', '.betterdocs-ai-button', function() {
592 + $('.betterdocs-ai-autowrite-form-container').removeClass('hidden');
593 + $('#betterdocs-ai-autowrite-form-container-overlay').removeClass('hidden');
594 + });
595 +
596 + // $(document).on('click', '.betterdocs-ai-button', function() {
597 + if ($('.betterdocs-ai-autowrite-form-container').length < 1) {
598 + $('body').append(formHtml);
599 +
600 + // Add event listeners to input elements
601 + document.getElementById('betterdocs-ai-title').addEventListener('input', updateTextarea);
602 + document.getElementById('betterdocs-ai-keyword').addEventListener('input', updateTextarea);
603 + // document.getElementById('bd-autowrtite-content-section').addEventListener('change', updateTextarea);
604 + // document.getElementById('bd-autowrtite-content-paragraph').addEventListener('change', updateTextarea);
605 + // document.getElementById('betterdocs-ai-language').addEventListener('input', updateTextarea);
606 + }
607 + // });
608 + const btn = document.createElement('button');
609 + wp.data.subscribe(function() {
610 + setTimeout(() => {
611 + if ($('.edit-post-header__settings').length > 0) {
612 + $('.edit-post-header__settings').prepend(bdAIButton);
613 + } else if ($('.editor-header__settings').length > 0) {
614 + $('.editor-header__settings').prepend(bdAIButton);
615 + }
616 +
617 + }, 1);
618 + });
619 + }
620 +
621 + $(document).on('click', '#betterdocs-ai-autowrite-form-container-overlay', function() {
622 + closeWriteWithAIForm();
623 + });
624 + });
625 + </script>
626 +
627 + <style>
628 + .hidden {
629 + display: none !important;
630 + }
631 +
632 + .disabled-input-field input,
633 + .disabled-input-field textarea,
634 + .disabled-input-field button,
635 + .disabled-input-field label {
636 + pointer-events: none;
637 + opacity: 0.6;
638 + }
639 +
640 + .disabled-input-field label {
641 + opacity: 1;
642 + }
643 +
644 + .betterdocs-ai-button-container {
645 + margin-left: 10px;
646 + white-space: nowrap;
647 + max-width: 145px;
648 + }
649 +
650 + .autowrite-icon {
651 + display: flex;
652 + align-items: center;
653 + width: 55px;
654 + height: 55px;
655 + background: #FFE4E8;
656 + justify-content: center;
657 + border-radius: 50px;
658 + }
659 +
660 + .autowrite-icon svg {
661 + width: 28px;
662 + height: 28px;
663 + }
664 +
665 + .autowrite-heading {
666 + display: flex;
667 + gap: 10px;
668 + align-items: center;
669 + }
670 +
671 + .autowrite-heading h1 {
672 + color: #1D2939;
673 + font-family: 'IBM Plex Sans', sans-serif;
674 + font-size: 24px;
675 + font-style: normal;
676 + font-weight: 500;
677 + line-height: normal;
678 + margin: 0;
679 + }
680 +
681 + .autowrite-heading p,
682 + form#betterdocs-ai-form p {
683 + margin: 0;
684 + margin-bottom: 24px;
685 + }
686 +
687 + .autowrite-subheadding p {
688 + font-family: 'IBM Plex Sans', sans-serif;
689 + font-size: 14px;
690 + }
691 +
692 + .prompt-field .input-description {
693 + margin: 0 !important;
694 + }
695 +
696 + .autowrite-heading p {
697 + color: #475467;
698 + font-family: 'IBM Plex Sans', sans-serif;
699 + font-size: 16px;
700 + font-style: normal;
701 + font-weight: 400;
702 + }
703 +
704 + .betterdocs-ai-button {
705 + background: #00B884;
706 + border: 1px solid transparent;
707 + color: #fff;
708 + box-shadow: none;
709 + font-size: 12px;
710 + margin-right: 8px;
711 + padding: 0px 15px;
712 + cursor: pointer;
713 + border-radius: 3px;
714 + height: 38px;
715 + display: flex;
716 + align-items: center;
717 + justify-content: space-between;
718 + gap: 10px;
719 + width: 135px;
720 + }
721 +
722 + .betterdocs-ai-button img {
723 + width: 20px;
724 + height: 20px;
725 + }
726 +
727 + .betterdocs-ai-autowrite-form-container {
728 + position: fixed;
729 + top: 50%;
730 + left: 50%;
731 + transform: translate(-50%, -50%);
732 + z-index: 100001;
733 + width: 650px;
734 + margin: 0 auto;
735 + background-color: #fff;
736 + border-radius: 5px;
737 + font-family: 'IBM Plex Sans', sans-serif;
738 + /* max-height: 600px; */
739 + max-height: 750px;
740 + max-width: 100%;
741 + }
742 +
743 + .betterdocs-ai-autowrite-form-content {
744 + background-color: #fff;
745 + padding: 20px 0px;
746 + border-radius: 5px;
747 + padding-bottom: 0;
748 + overflow: auto;
749 + /* max-height: 700px; */
750 + height: 100%;
751 +
752 + }
753 +
754 + .betterdocs-ai-autowrite-top-part {
755 + /* padding-bottom: 20px; */
756 + border-bottom: 1px solid #ddd;
757 + /* margin-bottom: 20px; */
758 + padding: 0 40px;
759 + }
760 +
761 + #betterdocs-ai-form {
762 + display: flex;
763 + flex-direction: column;
764 + /* height: 100%; */
765 + overflow: hidden;
766 + }
767 +
768 + .form-inner-content {
769 + overflow: auto;
770 + height: 100%;
771 + max-height: 435px;
772 + /* max-height: 330px; */
773 + padding: 0 40px;
774 + }
775 +
776 + .form-inner-content>.form-group {
777 + margin-top: 20px;
778 + }
779 +
780 +
781 + #betterdocs-ai-autowrite-form-container-overlay {
782 + position: fixed;
783 + top: 0;
784 + right: 0;
785 + bottom: 0;
786 + left: 0;
787 + background-color: rgba(0, 0, 0, .7);
788 + z-index: 100000;
789 + }
790 +
791 +
792 +
793 + #betterdocs-ai-form {
794 + display: flex;
795 + flex-direction: column;
796 + }
797 +
798 + #betterdocs-ai-form .form-group {
799 + margin-bottom: 24px;
800 + }
801 +
802 + #betterdocs-ai-form .bd-aiform-flex {
803 + display: flex;
804 + justify-content: space-between;
805 + }
806 +
807 + #betterdocs-ai-form label {
808 + font-weight: 600;
809 + margin-bottom: 5px;
810 + display: block;
811 + font-size: 14px;
812 + line-height: 20px;
813 + }
814 +
815 + select#bd-autowrtite-content-section,
816 + #bd-autowrtite-content-paragraph,
817 + #betterdocs-ai-language {
818 + width: 150px !important;
819 + height: 40px;
820 + }
821 +
822 + #betterdocs-ai-form input[type="text"],
823 + #betterdocs-ai-form textarea {
824 + width: 100%;
825 + padding: 8px;
826 + box-sizing: border-box;
827 + border: 1px solid #D0D5DD;
828 + border-radius: 4px;
829 + color: #667085;
830 + font-weight: 400;
831 + }
832 +
833 + /* Override autofill text color */
834 + #betterdocs-ai-form input:-webkit-autofill {
835 + -webkit-text-fill-color: #667085 !important;
836 + }
837 +
838 + #betterdocs-ai-form input::placeholder {
839 + color: #acb2bf;
840 + }
841 +
842 + #betterdocs-ai-form textarea {
843 + color: #667085;
844 + }
845 +
846 + #betterdocs-ai-form input:focus,
847 + #betterdocs-ai-form textarea:focus {
848 + box-shadow: none;
849 + }
850 +
851 + #betterdocs-ai-form textarea:focus {
852 + color: inherit;
853 + box-shadow: none;
854 +
855 + }
856 +
857 +
858 + .generate-button-container {
859 + position: sticky;
860 + bottom: 0px;
861 + width: 100%;
862 + margin-left: 0;
863 + z-index: 999999 !important;
864 + padding: 20px 0;
865 + display: flex;
866 + justify-content: end;
867 + border-top: 1px solid #ddd;
868 + background: white;
869 + border-bottom-right-radius: 5px;
870 + border-bottom-left-radius: 5px;
871 + }
872 +
873 + .generate-button-container button {
874 + display: flex;
875 + gap: 8px;
876 + align-items: center;
877 + justify-content: center;
878 + opacity: 1 !important;
879 + margin-right: 40px;
880 + }
881 +
882 + .input-description {
883 + font-size: 14px;
884 + color: #667085;
885 + }
886 +
887 + .betterdocs-ai-checkbox-field .form-group {
888 + display: flex;
889 + align-items: start;
890 + /* gap: 200px; */
891 + justify-content: space-between;
892 + }
893 +
894 + .betterdocs-ai-checkbox-field input {
895 + width: 20px;
896 + height: 20px;
897 + }
898 +
899 + /* Add this CSS to your existing stylesheet or create a new one */
900 +
901 + .betterdocs-ai-checkbox-field {
902 + position: relative;
903 + font-size: 16px;
904 + /* Adjust font size as needed */
905 + }
906 +
907 + .betterdocs-ai-checkbox-field input[type=checkbox]:checked::before {
908 + padding: 2px;
909 + }
910 +
911 + .betterdocs-ai-checkbox-field input[type=checkbox] {
912 + border: 1px solid #00b884;
913 + }
914 +
915 + .betterdocs-ai-checkbox-field input[type=checkbox]:checked::before {
916 + content: '\2713';
917 + color: #00b884;
918 + }
919 +
920 + /* Change the default checkbox color */
921 + .betterdocs-ai-checkbox-field input[type="checkbox"]:hover {
922 + -webkit-appearance: none;
923 + /* WebKit/Blink Browsers */
924 + -moz-appearance: none;
925 + /* Firefox */
926 + appearance: none;
927 + border: 1px solid #00b884;
928 + /* Set the height of the checkbox */
929 + /* Optional: Round the corners */
930 + outline: none;
931 + /* Remove the default outline */
932 + }
933 +
934 + /* Style the checked state */
935 + .betterdocs-ai-checkbox-field input[type="checkbox"]:checked {
936 + /* Set the background color when checked */
937 + border: 1px solid #00b884;
938 + /* Set the border color when checked */
939 + }
940 +
941 + .checkbox-field-label {
942 + width: calc(100% - 150px);
943 + }
944 +
945 + .checkbox-field-label p {
946 + margin: 0 !important;
947 + }
948 +
949 + .checkbox-input-field {
950 + width: 300px;
951 + text-align: right;
952 + }
953 +
954 + .checkbox-input-field {
955 + position: relative;
956 + display: inline-block;
957 + width: 60px;
958 + height: 34px;
959 + }
960 +
961 + .checkbox-input-field input {
962 + display: none;
963 + }
964 +
965 + .toggle-label {
966 + position: absolute;
967 + cursor: pointer;
968 + top: 0;
969 + left: 0;
970 + right: 0;
971 + bottom: 0;
972 + background-color: #ccc;
973 + border-radius: 34px;
974 + transition: background-color 0.3s;
975 + scale: .9;
976 + width: 52px;
977 + height: 26px;
978 + }
979 +
980 +
981 + .checkbox-input-field input:checked+.toggle-label {
982 + background-color: #00b884;
983 + }
984 +
985 + .toggle-label:after {
986 + content: "";
987 + position: absolute;
988 + height: 22px;
989 + width: 22px;
990 + left: 2px;
991 + bottom: 2px;
992 + background-color: white;
993 + border-radius: 50%;
994 + transition: transform 0.3s;
995 + }
996 +
997 + .checkbox-input-field input:checked+.toggle-label:after {
998 + transform: translateX(26px);
999 + }
1000 +
1001 + .generate-btn,
1002 + .prompt-btn,
1003 + .keep-btn {
1004 + background-color: #00b884;
1005 + color: #fff;
1006 + border: none;
1007 + padding: 10px 15px;
1008 + text-align: center;
1009 + text-decoration: none;
1010 + display: inline-block;
1011 + font-size: 16px;
1012 + cursor: pointer;
1013 + border-radius: 4px;
1014 + }
1015 +
1016 + .generate-btn[disabled] {
1017 + cursor: unset;
1018 + }
1019 +
1020 + .bd-close-button {
1021 + cursor: pointer;
1022 + font-size: 18px;
1023 + font-weight: bold;
1024 + float: right;
1025 + position: absolute;
1026 + top: -16px;
1027 + border-radius: 50%;
1028 + background: #ffffff;
1029 + width: 40px;
1030 + height: 40px;
1031 + display: flex;
1032 + align-items: center;
1033 + justify-content: center;
1034 + color: #281617;
1035 + right: -42px;
1036 + }
1037 +
1038 + div#betterdocs-ai-error-message,
1039 + #betterdocs-ai-message {
1040 + font-size: 14px;
1041 + font-family: 'IBM Plex Sans', sans-serif;
1042 + color: #667085;
1043 + margin-bottom: 20px;
1044 + }
1045 +
1046 + div#betterdocs-ai-error-message a,
1047 + #betterdocs-ai-message a {
1048 + text-decoration: none;
1049 + font-weight: 600;
1050 + }
1051 +
1052 + div#betterdocs-ai-error-message a:focus,
1053 + #betterdocs-ai-message a:focus {
1054 + outline: none;
1055 + box-shadow: none;
1056 + color: #2271b1;
1057 + }
1058 +
1059 + #betterdocs-ai-message span {
1060 + color: #d63638;
1061 + }
1062 +
1063 + .warning-message {
1064 + display: flex;
1065 + align-items: center;
1066 + gap: 10px;
1067 + background: #fbebed;
1068 + padding: 12px;
1069 + border-radius: 5px;
1070 + font-size: 14px;
1071 + line-height: 1.4em;
1072 + border-left: 4px solid #d63638;
1073 + }
1074 +
1075 + .warning-message svg {
1076 + width: 20px;
1077 + height: 20px;
1078 + }
1079 +
1080 + .warning-message span {
1081 + color: #d63638;
1082 + }
1083 +
1084 + .warning-message .footer-message {
1085 + width: calc(100% - 20px);
1086 + }
1087 +
1088 + @media only screen and (max-width: 991px) {
1089 + .betterdocs-ai-autowrite-form-container {
1090 + left: 0;
1091 + right: 0;
1092 + transform: translate(0%, -50%);
1093 + }
1094 +
1095 + .betterdocs-ai-autowrite-form-content {
1096 + overflow-x: auto;
1097 + }
1098 + }
1099 +
1100 + @media only screen and (max-width: 740px) {
1101 +
1102 + /* .bd-close-button {
1103 + right: px;
1104 + top: 1px;
1105 + border-radius: 5px;
1106 + width: 12px;
1107 + height: 12px;
1108 + color: #ffffff;
1109 + background: #00b884;
1110 + } */
1111 + .bd-close-button {
1112 + right: 0px;
1113 + top: 0px;
1114 + width: 12px;
1115 + height: 12px;
1116 + font-size: 14px;
1117 + }
1118 +
1119 + }
1120 + </style>
1121 + <?php
1122 + }
813 1123 }