Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Generate Excerpt for the Classic Editor. #491

Merged
merged 19 commits into from
Aug 17, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions includes/Classifai/Providers/OpenAI/ChatGPT.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,71 @@ public function __construct( $service ) {
public function register() {
add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_editor_assets' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
add_action( 'add_meta_boxes', [ $this, 'replace_classic_editor_excerpt' ] );
}

/**
* Replace the Classic Editor Excerpt meta box
* There are no content filters available, there's no other option here.
*/
public function replace_classic_editor_excerpt() {
$post_type = ! empty( $_GET['post_type'] ) ? sanitize_text_field( wp_unslash( $_GET['post_type'] ) ) : 'post'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

if ( post_type_supports( $post_type, 'excerpt' ) ) {
// Default meta box is registered in register_and_do_post_meta_boxes()
remove_meta_box( 'postexcerpt', null, 'normal' );
// Note: the text-domain is missing for `Excerpt` because this is set in WP core
add_meta_box( 'classifaipostexcerpt', __( 'Excerpt' ), [ $this, 'classifai_post_excerpt_meta_box' ], null, 'normal', 'core', array( '__back_compat_meta_box' => true ) );
}
}

/**
* Custom excerpt meta field
* Note: most of this is copied from post_excerpt_meta_box()
*
* @param WP_Post $post Current post object.
*/
public function classifai_post_excerpt_meta_box( $post ) {
global $pagenow;

$is_new_post = 'post-new.php' === $pagenow;
$has_excerpt = false;

// We need a post ID to look up an excerpt, a brand new post doesn't have one
if ( ! $is_new_post ) {
$has_excerpt = '' !== $post->post_excerpt;
}

$button_text = __( 'Generate excerpt', 'classifai' );
if ( $has_excerpt ) {
$button_text = __( 'Re-generate excerpt', 'classifai' );
}

?>
<label class="screen-reader-text" for="excerpt">
<?php
/* translators: Hidden accessibility text. */
_e( 'Excerpt' ); // phpcs:ignore WordPress.Security.EscapeOutput.UnsafePrintingFunction
?>
</label><textarea rows="1" cols="40" name="excerpt" id="excerpt"><?php echo esc_html( $post->post_excerpt ); // textarea_escaped ?></textarea>

<p>
<?php
printf(
/* translators: %s: Documentation URL. */
__( 'Excerpts are optional hand-crafted summaries of your content that can be used in your theme. <a href="%s">Learn more about manual excerpts</a>.' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
__( 'https://wordpress.org/documentation/article/what-is-an-excerpt-classic-editor/' ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
);
?>
</p>

<?php if ( $is_new_post ) { ?>
<button id="classifai-generate-excerpt" type="button" class="button button-primary" disabled><?php echo esc_html( $button_text ); ?></button>
<p><strong><?php esc_html_e( 'Add some content and save as a draft to enable excerpt generation.', 'classifai' ); ?></strong></p>
<?php } else { ?>
<button id="classifai-generate-excerpt" type="button" class="button button-primary"><?php echo esc_html( $button_text ); ?></button>
<?php
}
}

/**
Expand Down Expand Up @@ -146,6 +211,40 @@ public function enqueue_admin_assets( $hook_suffix = '' ) {
return;
}

$settings = $this->get_settings();
$user_roles = wp_get_current_user()->roles ?? [];
$excerpt_roles = $settings['roles'] ?? [];

if (
( ! empty( $excerpt_roles ) && empty( array_diff( $user_roles, $excerpt_roles ) ) )
&& ( isset( $settings['enable_excerpt'] ) && 1 === (int) $settings['enable_excerpt'] )
) {

$_post_id = isset( $_GET['post'] ) ? filter_var( $_GET['post'], FILTER_VALIDATE_INT ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

if ( $_post_id ) {

wp_enqueue_script(
'classifai-post-excerpt-classic-editor',
CLASSIFAI_PLUGIN_URL . 'dist/post-excerpt-classic-editor.js',
[],
CLASSIFAI_PLUGIN_VERSION,
true
);
wp_localize_script(
'classifai-post-excerpt-classic-editor',
'classifaiGenerateExcerpt',
array(
'endpointUrl' => esc_url( get_rest_url( null, "/classifai/v1/openai/generate-excerpt/{$_post_id}" ) ),
'scriptDebug' => defined( 'SCRIPT_DEBUG' ) ? SCRIPT_DEBUG : false,
'generateExcerptText' => __( 'Generate excerpt', 'classifai' ),
'regenerateExcerptText' => __( 'Re-generate excerpt', 'classifai' ),
'nonce' => wp_create_nonce( 'wp_rest' ),
)
);
}
}

wp_enqueue_style(
'classifai-language-processing-style',
CLASSIFAI_PLUGIN_URL . 'dist/language-processing.css',
Expand Down
14 changes: 0 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 58 additions & 0 deletions src/js/post-excerpt-classic-editor/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@

/* Variables */
const classifaiGenerateExcerptButtonID = 'classifai-generate-excerpt';
const classifaiGenerateExcerptButtonElement = document.getElementById(classifaiGenerateExcerptButtonID);
const classifaiGenerateExcerptTextareaID = 'excerpt';
const classifaiGenerateExcerptTextareaElement = document.getElementById(classifaiGenerateExcerptTextareaID);
let classifarGenerateExcerptDebug = false;
let classifaiGenerateExcerptText;

// Note: classifarGenerateExcerptDebug is set by the SCRIPT_DEBUG constant
// Errors are only logged to console when SCRIPT_DEBUG is defined with value: TRUE
if (classifaiGenerateExcerpt && classifaiGenerateExcerpt.scriptDebug) {
classifarGenerateExcerptDebug = classifaiGenerateExcerpt.scriptDebug;
}

/* Generate excerpt when the button is clicked */
if (null !== classifaiGenerateExcerptButtonElement) {

classifaiGenerateExcerptButtonElement.onclick = function () {
classifarGenerateExcerptDebug && console.log('Classifai Generate Excerpt Debug: Button clicked, excerpt is being generated..');
classifaiExcerptGenerate();
};
}

/* Generate excerpt from API endpoint */
function classifaiExcerptGenerate() {

// Confirm the endpoint URL is available; excerpt generation cannot function without this.
if (!classifaiGenerateExcerpt || false === classifaiGenerateExcerpt.endpointUrl) {
classifarGenerateExcerptDebug && console.log('Classifai Generate Excerpt Debug: Endpoint URL not set!');
return;
}

classifaiGenerateExcerptButtonElement.disabled = true;

fetch(classifaiGenerateExcerpt.endpointUrl, {
headers: {
'X-WP-Nonce': classifaiGenerateExcerpt.nonce
}
})
.then((response) => response.json())
.then((result) => {
classifaiGenerateExcerptText = result;

classifarGenerateExcerptDebug && console.log('Classifai Generate Excerpt Debug: Generated Text', classifaiGenerateExcerptText)

if (classifaiGenerateExcerptText) {
classifaiGenerateExcerptTextareaElement.textContent = classifaiGenerateExcerptText
classifaiGenerateExcerptButtonElement.value = classifaiGenerateExcerpt.regenerateExcerptText;
}
})
.catch((error) => {
})
.finally(() => {
classifaiGenerateExcerptButtonElement.disabled = false
});

}
Loading