feat: remove AI thumbnails, rewrite frontend with React (v1.3.0)
Remove all AI thumbnail generation infrastructure (too expensive, poor results) and rewrite the public-facing article feed as a React SPA mounted via WordPress shortcode. Changes: - Remove thumbnail generation, OG scraping, and image download code from fetcher, LLM, and admin classes - Replace server-rendered PHP templates with React component (PeptideNewsFeed.jsx) using WordPress-bundled React/ReactDOM - Add Babel build pipeline for JSX transpilation - Update REST API to serve ai_summary instead of thumbnail fields - Redesign public CSS: clean card layout, loading skeletons, dark mode, responsive, no thumbnail imagery - Remove dead admin settings (llm_image_model, thumbnail_fallback) - Fix call_openrouter() visibility for Content Filter cross-class use - Bump version to 1.3.0 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -211,7 +211,7 @@ class Peptide_News_Admin {
|
||||
$this->add_setting( 'openrouter_api_key', __( 'OpenRouter API Key', 'peptide-news' ), 'render_openrouter_key_field', 'peptide_news_llm_section' );
|
||||
$this->add_setting( 'llm_keywords_model', __( 'Keywords Model', 'peptide-news' ), 'render_llm_keywords_model_field', 'peptide_news_llm_section' );
|
||||
$this->add_setting( 'llm_summary_model', __( 'Summary Model', 'peptide-news' ), 'render_llm_summary_model_field', 'peptide_news_llm_section' );
|
||||
$this->add_setting( 'llm_image_model', __( 'Image Generation Model', 'peptide-news' ), 'render_llm_image_model_field', 'peptide_news_llm_section' );
|
||||
|
||||
$this->add_setting( 'llm_max_articles', __( 'Max Articles per Cycle', 'peptide-news' ), 'render_llm_max_articles_field', 'peptide_news_llm_section' );
|
||||
}
|
||||
|
||||
@@ -265,9 +265,7 @@ class Peptide_News_Admin {
|
||||
'openrouter_api_key' => 'sanitize_text_field',
|
||||
'llm_keywords_model' => array( $this, 'sanitize_model_id' ),
|
||||
'llm_summary_model' => array( $this, 'sanitize_model_id' ),
|
||||
'llm_image_model' => array( $this, 'sanitize_model_id' ),
|
||||
'llm_max_articles' => 'absint',
|
||||
'thumbnail_fallback' => 'esc_url_raw',
|
||||
);
|
||||
|
||||
return isset( $callbacks[ $key ] ) ? $callbacks[ $key ] : 'sanitize_text_field';
|
||||
@@ -532,15 +530,6 @@ class Peptide_News_Admin {
|
||||
echo '<p class="description">' . esc_html__( 'OpenRouter model ID for article summarization (e.g., google/gemini-2.0-flash-001, anthropic/claude-3.5-sonnet).', 'peptide-news' ) . '</p>';
|
||||
}
|
||||
|
||||
public function render_llm_image_model_field() {
|
||||
$value = get_option( 'peptide_news_llm_image_model', '' );
|
||||
printf(
|
||||
'<input type="text" name="peptide_news_llm_image_model" value="%s" class="regular-text" />',
|
||||
esc_attr( $value )
|
||||
);
|
||||
echo '<p class="description">' . esc_html__( 'OpenRouter model ID for AI thumbnail generation (e.g., openai/dall-e-3, stabilityai/stable-diffusion-xl). Leave blank to disable AI thumbnails.', 'peptide-news' ) . '</p>';
|
||||
}
|
||||
|
||||
public function render_llm_max_articles_field() {
|
||||
$value = get_option( 'peptide_news_llm_max_articles', 10 );
|
||||
printf(
|
||||
@@ -579,13 +568,6 @@ class Peptide_News_Admin {
|
||||
echo '</button>';
|
||||
echo '<span id="peptide-backfill-result" style="margin-left:10px;"></span>';
|
||||
|
||||
// Backfill Thumbnails button.
|
||||
echo '<div style="margin-top:8px;">';
|
||||
echo '<button type="button" id="peptide-backfill-thumbnails" class="button button-secondary">';
|
||||
echo esc_html__( 'Fix Article Thumbnails', 'peptide-news' );
|
||||
echo '</button>';
|
||||
echo '<span id="peptide-thumb-result" style="margin-left:10px;"></span>';
|
||||
echo '</div>';
|
||||
?>
|
||||
<script>
|
||||
(function($) {
|
||||
@@ -609,33 +591,6 @@ class Peptide_News_Admin {
|
||||
});
|
||||
});
|
||||
|
||||
$('#peptide-backfill-thumbnails').on('click', function() {
|
||||
var $btn = $(this), $result = $('#peptide-thumb-result');
|
||||
$btn.prop('disabled', true).text('<?php echo esc_js( __( 'Scraping...', 'peptide-news' ) ); ?>');
|
||||
$result.text('This may take a minute...');
|
||||
$.post(peptideNewsAdmin.ajax_url, {
|
||||
action: 'peptide_news_backfill_thumbnails',
|
||||
nonce: peptideNewsAdmin.admin_nonce
|
||||
}, function(response) {
|
||||
$btn.prop('disabled', false).text('<?php echo esc_js( __( 'Fix Article Thumbnails', 'peptide-news' ) ); ?>');
|
||||
if (response.success) {
|
||||
var d = response.data;
|
||||
var parts = [];
|
||||
if (d.scraped > 0) { parts.push(d.scraped + ' scraped'); }
|
||||
if (d.generated > 0) { parts.push(d.generated + ' AI-generated'); }
|
||||
if (d.failed > 0) { parts.push(d.failed + ' remaining'); }
|
||||
var msg = (d.scraped + d.generated) + ' of ' + d.total + ' thumbnails resolved';
|
||||
if (parts.length) { msg += ' (' + parts.join(', ') + ')'; }
|
||||
$result.text(msg);
|
||||
if (d.samples && d.samples.length) { console.log('Thumbnail backfill:', JSON.stringify(d.samples, null, 2)); }
|
||||
} else {
|
||||
$result.text('Error: ' + (response.data || 'Unknown error'));
|
||||
}
|
||||
}).fail(function() {
|
||||
$btn.prop('disabled', false).text('<?php echo esc_js( __( 'Fix Article Thumbnails', 'peptide-news' ) ); ?>');
|
||||
$result.text('Request failed.');
|
||||
});
|
||||
});
|
||||
})(jQuery);
|
||||
</script>
|
||||
<?php
|
||||
|
||||
@@ -33,19 +33,18 @@ $total_pages = ceil( $total / $per_page );
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:4%">ID</th>
|
||||
<th style="width:20%"><?php esc_html_e( 'Title', 'peptide-news' ); ?></th>
|
||||
<th style="width:8%"><?php esc_html_e( 'Source', 'peptide-news' ); ?></th>
|
||||
<th style="width:28%"><?php esc_html_e( 'Title', 'peptide-news' ); ?></th>
|
||||
<th style="width:10%"><?php esc_html_e( 'Source', 'peptide-news' ); ?></th>
|
||||
<th style="width:15%"><?php esc_html_e( 'AI Keywords', 'peptide-news' ); ?></th>
|
||||
<th style="width:20%"><?php esc_html_e( 'AI Summary', 'peptide-news' ); ?></th>
|
||||
<th style="width:23%"><?php esc_html_e( 'AI Summary', 'peptide-news' ); ?></th>
|
||||
<th style="width:8%"><?php esc_html_e( 'Published', 'peptide-news' ); ?></th>
|
||||
<th style="width:8%"><?php esc_html_e( 'Fetched', 'peptide-news' ); ?></th>
|
||||
<th style="width:5%"><?php esc_html_e( 'Thumb', 'peptide-news' ); ?></th>
|
||||
<th style="width:4%"><?php esc_html_e( 'Active', 'peptide-news' ); ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if ( empty( $articles ) ) : ?>
|
||||
<tr><td colspan="9"><?php esc_html_e( 'No articles found. Run a fetch first.', 'peptide-news' ); ?></td></tr>
|
||||
<tr><td colspan="8"><?php esc_html_e( 'No articles found. Run a fetch first.', 'peptide-news' ); ?></td></tr>
|
||||
<?php else : ?>
|
||||
<?php foreach ( $articles as $article ) : ?>
|
||||
<tr>
|
||||
@@ -72,21 +71,6 @@ $total_pages = ceil( $total / $per_page );
|
||||
</td>
|
||||
<td><?php echo esc_html( wp_date( 'M j, Y', strtotime( $article->published_at ) ) ); ?></td>
|
||||
<td><?php echo esc_html( wp_date( 'M j, Y', strtotime( $article->fetched_at ) ) ); ?></td>
|
||||
<td>
|
||||
<?php
|
||||
$thumb_src = '';
|
||||
if ( ! empty( $article->thumbnail_url ) && '_no_image' !== $article->thumbnail_url ) {
|
||||
$thumb_src = $article->thumbnail_url;
|
||||
} elseif ( ! empty( $article->thumbnail_local ) ) {
|
||||
$upload_dir = wp_upload_dir();
|
||||
$thumb_src = $upload_dir['baseurl'] . '/' . $article->thumbnail_local;
|
||||
}
|
||||
if ( $thumb_src ) : ?>
|
||||
<img src="<?php echo esc_url( $thumb_src ); ?>" alt="" style="width:50px;height:50px;object-fit:cover;border-radius:4px;" />
|
||||
<?php else : ?>
|
||||
<span class="dashicons dashicons-format-image" style="color:#ccc;font-size:24px;"></span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?php echo $article->is_active ? '<span style="color:green;">✓</span>' : '<span style="color:#ccc;">✗</span>'; ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
|
||||
@@ -89,23 +89,15 @@ class Peptide_News_Fetcher {
|
||||
'new_stored' => $stored,
|
||||
) );
|
||||
|
||||
// Scrape OG images for articles missing thumbnails.
|
||||
$og_scraped = $this->scrape_missing_thumbnails();
|
||||
|
||||
// Run AI analysis on newly fetched articles (keywords + summary).
|
||||
if ( class_exists( 'Peptide_News_LLM' ) && Peptide_News_LLM::is_enabled() ) {
|
||||
$llm_batch_size = absint( get_option( 'peptide_news_llm_max_articles', 10 ) );
|
||||
$llm_processed = Peptide_News_LLM::process_unanalyzed( $llm_batch_size );
|
||||
|
||||
// Generate AI thumbnails for articles still missing images.
|
||||
$ai_thumbs = Peptide_News_LLM::generate_missing_thumbnails( $llm_batch_size );
|
||||
|
||||
// Append LLM stats to the fetch log.
|
||||
$fetch_log = get_option( 'peptide_news_last_fetch' );
|
||||
if ( is_array( $fetch_log ) ) {
|
||||
$fetch_log['ai_processed'] = $llm_processed;
|
||||
$fetch_log['og_scraped'] = $og_scraped;
|
||||
$fetch_log['ai_thumbnails'] = $ai_thumbs;
|
||||
$fetch_log['ai_processed'] = $llm_processed;
|
||||
update_option( 'peptide_news_last_fetch', $fetch_log );
|
||||
}
|
||||
}
|
||||
@@ -143,19 +135,6 @@ class Peptide_News_Fetcher {
|
||||
$items = $feed->get_items( 0, $max_items );
|
||||
|
||||
foreach ( $items as $item ) {
|
||||
$thumbnail = '';
|
||||
|
||||
// Try enclosure first.
|
||||
$enclosure = $item->get_enclosure();
|
||||
if ( $enclosure && $enclosure->get_link() ) {
|
||||
$thumbnail = $enclosure->get_link();
|
||||
}
|
||||
|
||||
// Try media:thumbnail or media:content.
|
||||
if ( empty( $thumbnail ) ) {
|
||||
$thumbnail = $this->extract_image_from_content( $item->get_content() );
|
||||
}
|
||||
|
||||
$pub_date = $item->get_date( 'Y-m-d H:i:s' );
|
||||
if ( empty( $pub_date ) ) {
|
||||
$pub_date = current_time( 'mysql' );
|
||||
@@ -171,7 +150,7 @@ class Peptide_News_Fetcher {
|
||||
'excerpt' => wp_trim_words( wp_strip_all_tags( $item->get_description() ), 40 ),
|
||||
'content' => wp_kses_post( $item->get_content() ),
|
||||
'author' => sanitize_text_field( $item->get_author() ? $item->get_author()->get_name() : '' ),
|
||||
'thumbnail_url' => esc_url_raw( $thumbnail ),
|
||||
'thumbnail_url' => '',
|
||||
'published_at' => $pub_date,
|
||||
'categories' => $this->extract_categories( $item ),
|
||||
'tags' => '',
|
||||
@@ -230,7 +209,7 @@ class Peptide_News_Fetcher {
|
||||
'excerpt' => wp_trim_words( sanitize_text_field( $item['description'] ?? '' ), 40 ),
|
||||
'content' => wp_kses_post( $item['content'] ?? '' ),
|
||||
'author' => sanitize_text_field( $item['author'] ?? '' ),
|
||||
'thumbnail_url' => esc_url_raw( $item['urlToImage'] ?? '' ),
|
||||
'thumbnail_url' => '',
|
||||
'published_at' => $pub_date,
|
||||
'categories' => '',
|
||||
'tags' => '',
|
||||
@@ -303,270 +282,6 @@ class Peptide_News_Fetcher {
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrape Open Graph images for articles that have no thumbnail.
|
||||
*
|
||||
* Fetches the article URL and extracts og:image, twitter:image,
|
||||
* or other meta image tags.
|
||||
*
|
||||
* @return int Number of articles updated with scraped thumbnails.
|
||||
*/
|
||||
private function scrape_missing_thumbnails() {
|
||||
global $wpdb;
|
||||
|
||||
$table = $wpdb->prefix . 'peptide_news_articles';
|
||||
$articles = $wpdb->get_results(
|
||||
"SELECT id, source, source_url, title
|
||||
FROM {$table}
|
||||
WHERE is_active = 1
|
||||
AND ( thumbnail_url = '' OR thumbnail_url IS NULL )
|
||||
ORDER BY fetched_at DESC
|
||||
LIMIT 20"
|
||||
);
|
||||
|
||||
if ( empty( $articles ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$aggregators = array( 'news.google.com', 'news.yahoo.com', 'msn.com' );
|
||||
$updated = 0;
|
||||
|
||||
foreach ( $articles as $article ) {
|
||||
$domain = $this->extract_domain( $article->source_url );
|
||||
|
||||
// Skip aggregator URLs — they can't be scraped for OG images.
|
||||
// These will be handled by AI image generation instead.
|
||||
if ( in_array( $domain, $aggregators, true ) ) {
|
||||
$wpdb->update(
|
||||
$table,
|
||||
array( 'thumbnail_url' => '_no_image' ),
|
||||
array( 'id' => $article->id ),
|
||||
array( '%s' ),
|
||||
array( '%d' )
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Direct OG scrape for non-aggregator URLs.
|
||||
$image_url = $this->scrape_og_image( $article->source_url );
|
||||
|
||||
if ( ! empty( $image_url ) ) {
|
||||
$local_path = $this->download_thumbnail( $image_url, $article->id, $article->title );
|
||||
|
||||
$update_data = array( 'thumbnail_url' => $image_url );
|
||||
if ( $local_path ) {
|
||||
$update_data['thumbnail_local'] = $local_path;
|
||||
}
|
||||
|
||||
$wpdb->update( $table, $update_data, array( 'id' => $article->id ) );
|
||||
$updated++;
|
||||
} else {
|
||||
$wpdb->update(
|
||||
$table,
|
||||
array( 'thumbnail_url' => '_no_image' ),
|
||||
array( 'id' => $article->id ),
|
||||
array( '%s' ),
|
||||
array( '%d' )
|
||||
);
|
||||
}
|
||||
|
||||
usleep( 300000 );
|
||||
}
|
||||
|
||||
if ( $updated > 0 ) {
|
||||
$this->clear_article_cache();
|
||||
}
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrape Open Graph / meta image tags from a URL.
|
||||
*
|
||||
* @param string $url The article URL to scrape.
|
||||
* @return string Image URL or empty string.
|
||||
*/
|
||||
private function scrape_og_image( $url ) {
|
||||
if ( empty( $url ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$response = wp_remote_get( $url, array(
|
||||
'timeout' => 15,
|
||||
'user-agent' => 'Mozilla/5.0 (compatible; PeptideNewsBot/1.0)',
|
||||
'headers' => array(
|
||||
'Accept' => 'text/html',
|
||||
),
|
||||
// Only fetch the first ~200KB for efficiency.
|
||||
'stream' => false,
|
||||
'limit_response_size' => 200000,
|
||||
) );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$this->log_error( 'OG scrape failed for ' . $url . ': ' . $response->get_error_message() );
|
||||
return '';
|
||||
}
|
||||
|
||||
$status = wp_remote_retrieve_response_code( $response );
|
||||
if ( $status < 200 || $status >= 400 ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$html = wp_remote_retrieve_body( $response );
|
||||
|
||||
if ( empty( $html ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Try meta tags in priority order.
|
||||
$patterns = array(
|
||||
// Open Graph image.
|
||||
'/<meta[^>]+property=["\']og:image["\'][^>]+content=["\']([^"\']+)["\']/is',
|
||||
'/<meta[^>]+content=["\']([^"\']+)["\'][^>]+property=["\']og:image["\']/is',
|
||||
// Twitter card image.
|
||||
'/<meta[^>]+name=["\']twitter:image["\'][^>]+content=["\']([^"\']+)["\']/is',
|
||||
'/<meta[^>]+content=["\']([^"\']+)["\'][^>]+name=["\']twitter:image["\']/is',
|
||||
// Schema.org image.
|
||||
'/<meta[^>]+itemprop=["\']image["\'][^>]+content=["\']([^"\']+)["\']/is',
|
||||
);
|
||||
|
||||
foreach ( $patterns as $pattern ) {
|
||||
if ( preg_match( $pattern, $html, $matches ) ) {
|
||||
$image_url = trim( $matches[1] );
|
||||
|
||||
// Validate it looks like an image URL.
|
||||
if ( $this->is_valid_image_url( $image_url ) ) {
|
||||
return esc_url_raw( $image_url );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a URL appears to be a valid image.
|
||||
*
|
||||
* @param string $url
|
||||
* @return bool
|
||||
*/
|
||||
private function is_valid_image_url( $url ) {
|
||||
if ( empty( $url ) || strlen( $url ) < 10 ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Must start with http(s).
|
||||
if ( ! preg_match( '/^https?:\/\//i', $url ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Reject obvious non-image URLs (tracking pixels, spacers, etc.)
|
||||
$blocklist = array( '1x1', 'pixel', 'spacer', 'blank', 'transparent', 'data:image' );
|
||||
$url_lower = strtolower( $url );
|
||||
foreach ( $blocklist as $blocked ) {
|
||||
if ( strpos( $url_lower, $blocked ) !== false ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download an image and store it in the WP uploads directory.
|
||||
*
|
||||
* @param string $image_url External image URL.
|
||||
* @param int $article_id Article ID for unique naming.
|
||||
* @param string $title Article title for alt text / file naming.
|
||||
* @return string|false Local relative path on success, false on failure.
|
||||
*/
|
||||
private function download_thumbnail( $image_url, $article_id, $title = '' ) {
|
||||
// SSRF prevention: validate URL before fetching.
|
||||
if ( ! wp_http_validate_url( $image_url ) ) {
|
||||
$this->log_error( 'Invalid image URL (SSRF protection) for article ' . $article_id . ': ' . $image_url );
|
||||
return false;
|
||||
}
|
||||
|
||||
$upload_dir = wp_upload_dir();
|
||||
$target_dir = $upload_dir['basedir'] . '/peptide-news-thumbs';
|
||||
|
||||
// Create directory if it doesn't exist.
|
||||
if ( ! file_exists( $target_dir ) ) {
|
||||
wp_mkdir_p( $target_dir );
|
||||
}
|
||||
|
||||
$max_file_size = 5 * 1024 * 1024; // 5 MB.
|
||||
|
||||
$response = wp_remote_get( $image_url, array(
|
||||
'timeout' => 20,
|
||||
'user-agent' => 'Mozilla/5.0 (compatible; PeptideNewsBot/1.0)',
|
||||
'limit_response_size' => $max_file_size,
|
||||
) );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$this->log_error( 'Thumbnail download failed for article ' . $article_id . ': ' . $response->get_error_message() );
|
||||
return false;
|
||||
}
|
||||
|
||||
$body = wp_remote_retrieve_body( $response );
|
||||
if ( empty( $body ) || strlen( $body ) < 1000 || strlen( $body ) > $max_file_size ) {
|
||||
// Too small to be a real image, or exceeds size limit.
|
||||
return false;
|
||||
}
|
||||
|
||||
$content_type = wp_remote_retrieve_header( $response, 'content-type' );
|
||||
$extension = $this->get_extension_from_content_type( $content_type );
|
||||
|
||||
if ( ! $extension ) {
|
||||
// Try to detect from the image data.
|
||||
$finfo = new finfo( FILEINFO_MIME_TYPE );
|
||||
$mime = $finfo->buffer( $body );
|
||||
$extension = $this->get_extension_from_content_type( $mime );
|
||||
}
|
||||
|
||||
if ( ! $extension ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$filename = 'pn-thumb-' . $article_id . '.' . $extension;
|
||||
$filepath = $target_dir . '/' . $filename;
|
||||
|
||||
// Write the file.
|
||||
$result = file_put_contents( $filepath, $body );
|
||||
|
||||
if ( false === $result ) {
|
||||
$this->log_error( 'Failed to write thumbnail file: ' . $filepath );
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set secure file permissions.
|
||||
chmod( $filepath, 0644 );
|
||||
|
||||
// Return the relative path from uploads base.
|
||||
return 'peptide-news-thumbs/' . $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map content type to file extension.
|
||||
*
|
||||
* @param string $content_type
|
||||
* @return string|false
|
||||
*/
|
||||
private function get_extension_from_content_type( $content_type ) {
|
||||
$map = array(
|
||||
'image/jpeg' => 'jpg',
|
||||
'image/jpg' => 'jpg',
|
||||
'image/png' => 'png',
|
||||
'image/gif' => 'gif',
|
||||
'image/webp' => 'webp',
|
||||
'image/svg+xml' => 'svg',
|
||||
);
|
||||
|
||||
$content_type = strtolower( trim( explode( ';', $content_type )[0] ) );
|
||||
|
||||
return isset( $map[ $content_type ] ) ? $map[ $content_type ] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all article transient caches.
|
||||
*/
|
||||
@@ -583,29 +298,6 @@ class Peptide_News_Fetcher {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to extract an image URL from HTML content.
|
||||
*
|
||||
* @param string $content
|
||||
* @return string
|
||||
*/
|
||||
private function extract_image_from_content( $content ) {
|
||||
if ( empty( $content ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ( preg_match( '/<img[^>]+src=["\']([^"\']+)["\']/', $content, $matches ) ) {
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
// Check for media:content or media:thumbnail.
|
||||
if ( preg_match( '/url=["\']([^"\']+)["\']/', $content, $matches ) ) {
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract categories from a SimplePie item.
|
||||
*
|
||||
@@ -736,127 +428,6 @@ class Peptide_News_Fetcher {
|
||||
return ! empty( $final_url ) ? $final_url : false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Backfill thumbnails for existing articles that have none.
|
||||
*
|
||||
* Attempts OG scraping for non-aggregator URLs, then uses AI image
|
||||
* generation for any remaining articles without thumbnails.
|
||||
*
|
||||
* @return array Summary with counts and diagnostic samples.
|
||||
*/
|
||||
public function backfill_article_thumbnails() {
|
||||
global $wpdb;
|
||||
|
||||
$table = $wpdb->prefix . 'peptide_news_articles';
|
||||
$aggregators = array( 'news.google.com', 'news.yahoo.com', 'msn.com' );
|
||||
|
||||
// Reset sentinels so we retry everything.
|
||||
$wpdb->query(
|
||||
"UPDATE {$table}
|
||||
SET thumbnail_url = ''
|
||||
WHERE thumbnail_url = '_no_image'
|
||||
AND is_active = 1"
|
||||
);
|
||||
|
||||
$articles = $wpdb->get_results(
|
||||
"SELECT id, source, source_url, title, excerpt, ai_summary, tags, categories
|
||||
FROM {$table}
|
||||
WHERE is_active = 1
|
||||
AND ( thumbnail_url = '' OR thumbnail_url IS NULL )
|
||||
AND ( thumbnail_local = '' OR thumbnail_local IS NULL )
|
||||
ORDER BY fetched_at DESC
|
||||
LIMIT 20"
|
||||
);
|
||||
|
||||
$result = array(
|
||||
'total' => count( $articles ),
|
||||
'scraped' => 0,
|
||||
'generated' => 0,
|
||||
'failed' => 0,
|
||||
'samples' => array(),
|
||||
);
|
||||
|
||||
if ( empty( $articles ) ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Phase 1: OG scrape non-aggregator URLs.
|
||||
foreach ( $articles as $article ) {
|
||||
$domain = $this->extract_domain( $article->source_url );
|
||||
if ( in_array( $domain, $aggregators, true ) ) {
|
||||
continue; // Skip — will be handled by AI generation.
|
||||
}
|
||||
|
||||
$image_url = $this->scrape_og_image( $article->source_url );
|
||||
if ( ! empty( $image_url ) ) {
|
||||
$local_path = $this->download_thumbnail( $image_url, $article->id, $article->title );
|
||||
$update_data = array( 'thumbnail_url' => $image_url );
|
||||
if ( $local_path ) {
|
||||
$update_data['thumbnail_local'] = $local_path;
|
||||
}
|
||||
$wpdb->update( $table, $update_data, array( 'id' => $article->id ) );
|
||||
$result['scraped']++;
|
||||
|
||||
if ( count( $result['samples'] ) < 5 ) {
|
||||
$result['samples'][] = array(
|
||||
'id' => $article->id,
|
||||
'title' => mb_substr( $article->title, 0, 60 ),
|
||||
'method' => 'og_scrape',
|
||||
'status' => 'ok',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
usleep( 300000 );
|
||||
}
|
||||
|
||||
// Phase 2: AI generation for articles still missing thumbnails.
|
||||
if ( class_exists( 'Peptide_News_LLM' ) && Peptide_News_LLM::is_enabled() ) {
|
||||
$ai_generated = Peptide_News_LLM::generate_missing_thumbnails( 20 );
|
||||
$result['generated'] = $ai_generated;
|
||||
}
|
||||
|
||||
// Count remaining failures.
|
||||
$still_missing = $wpdb->get_var(
|
||||
"SELECT COUNT(*)
|
||||
FROM {$table}
|
||||
WHERE is_active = 1
|
||||
AND ( thumbnail_url = '' OR thumbnail_url IS NULL )
|
||||
AND ( thumbnail_local = '' OR thumbnail_local IS NULL )"
|
||||
);
|
||||
$result['failed'] = (int) $still_missing;
|
||||
|
||||
// Mark remaining as '_no_image' so cron doesn't retry every cycle.
|
||||
$wpdb->query(
|
||||
"UPDATE {$table}
|
||||
SET thumbnail_url = '_no_image'
|
||||
WHERE is_active = 1
|
||||
AND ( thumbnail_url = '' OR thumbnail_url IS NULL )
|
||||
AND ( thumbnail_local = '' OR thumbnail_local IS NULL )"
|
||||
);
|
||||
|
||||
if ( $result['scraped'] > 0 || $result['generated'] > 0 ) {
|
||||
$this->clear_article_cache();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler for the thumbnail backfill action.
|
||||
*/
|
||||
public function ajax_backfill_thumbnails() {
|
||||
check_ajax_referer( 'peptide_news_admin', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( 'Unauthorized', 403 );
|
||||
}
|
||||
|
||||
$result = $this->backfill_article_thumbnails();
|
||||
wp_send_json_success( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Backfill source names for existing articles that show an aggregator domain.
|
||||
*
|
||||
|
||||
@@ -233,7 +233,7 @@ class Peptide_News_LLM {
|
||||
* @param string $prompt
|
||||
* @return string|WP_Error The response text or an error.
|
||||
*/
|
||||
private static function call_openrouter( $api_key, $model, $prompt ) {
|
||||
public static function call_openrouter( $api_key, $model, $prompt ) {
|
||||
$body = array(
|
||||
'model' => $model,
|
||||
'messages' => array(
|
||||
@@ -370,258 +370,6 @@ class Peptide_News_LLM {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate AI thumbnails for articles that still have no image
|
||||
* after OG scraping. Uses an image generation model via OpenRouter.
|
||||
*
|
||||
* @param int $batch_size Max articles to process per run.
|
||||
* @return int Number of thumbnails generated.
|
||||
*/
|
||||
public static function generate_missing_thumbnails( $batch_size = 10 ) {
|
||||
if ( ! self::is_enabled() ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$image_model = get_option( 'peptide_news_llm_image_model', '' );
|
||||
if ( empty( $image_model ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'peptide_news_articles';
|
||||
|
||||
// Find active articles with no usable thumbnail (including _no_image sentinel).
|
||||
$articles = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, title, excerpt, ai_summary, tags, categories
|
||||
FROM {$table}
|
||||
WHERE is_active = 1
|
||||
AND ( thumbnail_url = '' OR thumbnail_url IS NULL OR thumbnail_url = '_no_image' )
|
||||
AND ( thumbnail_local = '' OR thumbnail_local IS NULL )
|
||||
ORDER BY fetched_at DESC
|
||||
LIMIT %d",
|
||||
$batch_size
|
||||
) );
|
||||
|
||||
if ( empty( $articles ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$api_key = get_option( 'peptide_news_openrouter_api_key', '' );
|
||||
$generated = 0;
|
||||
|
||||
foreach ( $articles as $article ) {
|
||||
$image_data = self::generate_article_thumbnail( $api_key, $image_model, $article );
|
||||
|
||||
if ( $image_data ) {
|
||||
// Save the image locally.
|
||||
$local_path = self::save_generated_image( $image_data, $article->id );
|
||||
|
||||
if ( $local_path ) {
|
||||
$wpdb->update(
|
||||
$table,
|
||||
array( 'thumbnail_local' => $local_path ),
|
||||
array( 'id' => $article->id ),
|
||||
array( '%s' ),
|
||||
array( '%d' )
|
||||
);
|
||||
$generated++;
|
||||
}
|
||||
}
|
||||
|
||||
// Respect rate limits.
|
||||
usleep( 1000000 ); // 1 second between generations.
|
||||
}
|
||||
|
||||
if ( $generated > 0 ) {
|
||||
self::clear_article_cache();
|
||||
}
|
||||
|
||||
return $generated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a thumbnail image for a single article via OpenRouter.
|
||||
*
|
||||
* @param string $api_key
|
||||
* @param string $model Image generation model ID.
|
||||
* @param object $article Database row.
|
||||
* @return string|false Base64-encoded image data, or false.
|
||||
*/
|
||||
private static function generate_article_thumbnail( $api_key, $model, $article ) {
|
||||
$prompt = self::build_image_prompt( $article );
|
||||
|
||||
$body = array(
|
||||
'model' => $model,
|
||||
'messages' => array(
|
||||
array(
|
||||
'role' => 'user',
|
||||
'content' => $prompt,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
$response = wp_remote_post( self::API_URL, array(
|
||||
'timeout' => 60,
|
||||
'headers' => array(
|
||||
'Authorization' => 'Bearer ' . $api_key,
|
||||
'Content-Type' => 'application/json',
|
||||
'HTTP-Referer' => home_url(),
|
||||
'X-Title' => 'Peptide News Aggregator',
|
||||
),
|
||||
'body' => wp_json_encode( $body ),
|
||||
) );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
self::log_error( 'Image generation failed for article ' . $article->id . ': ' . $response->get_error_message() );
|
||||
return false;
|
||||
}
|
||||
|
||||
$status = wp_remote_retrieve_response_code( $response );
|
||||
$data = json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
|
||||
if ( $status < 200 || $status >= 300 ) {
|
||||
$error = isset( $data['error']['message'] ) ? $data['error']['message'] : 'HTTP ' . $status;
|
||||
self::log_error( 'Image generation HTTP error for article ' . $article->id . ': ' . $error );
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extract the image data from the response.
|
||||
// OpenRouter image models may return base64 data in various formats.
|
||||
if ( ! empty( $data['choices'][0]['message']['content'] ) ) {
|
||||
$content = $data['choices'][0]['message']['content'];
|
||||
|
||||
// If content is an array (multimodal), look for image parts.
|
||||
if ( is_array( $content ) ) {
|
||||
foreach ( $content as $part ) {
|
||||
if ( isset( $part['type'] ) && 'image_url' === $part['type']
|
||||
&& isset( $part['image_url'] ) && is_array( $part['image_url'] )
|
||||
&& isset( $part['image_url']['url'] ) && is_string( $part['image_url']['url'] ) ) {
|
||||
$url = $part['image_url']['url'];
|
||||
if ( strpos( $url, 'data:image' ) === 0 ) {
|
||||
// Extract base64 from data URL.
|
||||
$base64 = preg_replace( '/^data:image\/\w+;base64,/', '', $url );
|
||||
$decoded = base64_decode( $base64, true );
|
||||
if ( false === $decoded ) {
|
||||
self::log_error( 'Invalid base64 image data for article.' );
|
||||
return false;
|
||||
}
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If it's a URL string, download it (with SSRF protection).
|
||||
if ( is_string( $content ) && preg_match( '/^https?:\/\//', $content ) ) {
|
||||
$content_url = trim( $content );
|
||||
if ( ! wp_http_validate_url( $content_url ) ) {
|
||||
self::log_error( 'Invalid image URL (SSRF protection) for article ' . $article->id );
|
||||
return false;
|
||||
}
|
||||
$img_response = wp_remote_get( $content_url, array(
|
||||
'timeout' => 30,
|
||||
'limit_response_size' => 5 * 1024 * 1024,
|
||||
) );
|
||||
if ( ! is_wp_error( $img_response ) ) {
|
||||
return wp_remote_retrieve_body( $img_response );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for data array format (DALL-E style).
|
||||
if ( ! empty( $data['data'][0]['b64_json'] ) ) {
|
||||
$decoded = base64_decode( $data['data'][0]['b64_json'], true );
|
||||
if ( false === $decoded ) {
|
||||
self::log_error( 'Invalid base64 in DALL-E response for article ' . $article->id );
|
||||
return false;
|
||||
}
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
if ( ! empty( $data['data'][0]['url'] ) ) {
|
||||
$dalle_url = $data['data'][0]['url'];
|
||||
if ( wp_http_validate_url( $dalle_url ) ) {
|
||||
$img_response = wp_remote_get( $dalle_url, array(
|
||||
'timeout' => 30,
|
||||
'limit_response_size' => 5 * 1024 * 1024,
|
||||
) );
|
||||
if ( ! is_wp_error( $img_response ) ) {
|
||||
return wp_remote_retrieve_body( $img_response );
|
||||
}
|
||||
} else {
|
||||
self::log_error( 'Invalid DALL-E image URL (SSRF protection) for article ' . $article->id );
|
||||
}
|
||||
}
|
||||
|
||||
self::log_error( 'Could not extract image data from response for article ' . $article->id );
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the prompt for AI image generation.
|
||||
*
|
||||
* @param object $article
|
||||
* @return string
|
||||
*/
|
||||
private static function build_image_prompt( $article ) {
|
||||
$summary = ! empty( $article->ai_summary ) ? $article->ai_summary : $article->excerpt;
|
||||
$tags = ! empty( $article->tags ) ? $article->tags : ( $article->categories ?? '' );
|
||||
|
||||
return "Generate a professional, science-themed thumbnail image for a peptide research news article. "
|
||||
. "The image should be modern, clean, and suitable for a news website card layout (16:9 aspect ratio). "
|
||||
. "Use a scientific aesthetic: molecular structures, laboratory elements, or abstract biotech visuals. "
|
||||
. "Do NOT include any text or words in the image.\n\n"
|
||||
. "Article title: " . $article->title . "\n"
|
||||
. ( ! empty( $summary ) ? "Summary: " . mb_substr( $summary, 0, 200 ) . "\n" : '' )
|
||||
. ( ! empty( $tags ) ? "Keywords: " . $tags . "\n" : '' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a generated image to the WP uploads directory.
|
||||
*
|
||||
* @param string $image_data Raw image binary data.
|
||||
* @param int $article_id
|
||||
* @return string|false Relative path from uploads base, or false.
|
||||
*/
|
||||
private static function save_generated_image( $image_data, $article_id ) {
|
||||
if ( empty( $image_data ) || strlen( $image_data ) < 1000 ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$upload_dir = wp_upload_dir();
|
||||
$target_dir = $upload_dir['basedir'] . '/peptide-news-thumbs';
|
||||
|
||||
if ( ! file_exists( $target_dir ) ) {
|
||||
wp_mkdir_p( $target_dir );
|
||||
}
|
||||
|
||||
// Detect image type from data.
|
||||
$finfo = new finfo( FILEINFO_MIME_TYPE );
|
||||
$mime = $finfo->buffer( $image_data );
|
||||
$ext_map = array(
|
||||
'image/png' => 'png',
|
||||
'image/jpeg' => 'jpg',
|
||||
'image/webp' => 'webp',
|
||||
'image/gif' => 'gif',
|
||||
);
|
||||
$extension = isset( $ext_map[ $mime ] ) ? $ext_map[ $mime ] : 'png';
|
||||
|
||||
$filename = 'pn-ai-' . $article_id . '.' . $extension;
|
||||
$filepath = $target_dir . '/' . $filename;
|
||||
|
||||
$result = file_put_contents( $filepath, $image_data );
|
||||
|
||||
if ( false === $result ) {
|
||||
self::log_error( 'Failed to save generated thumbnail: ' . $filepath );
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set secure file permissions.
|
||||
chmod( $filepath, 0644 );
|
||||
|
||||
return 'peptide-news-thumbs/' . $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all article transient caches.
|
||||
*/
|
||||
|
||||
@@ -133,8 +133,8 @@ class Peptide_News_Rest_API {
|
||||
$table = $wpdb->prefix . 'peptide_news_articles';
|
||||
|
||||
$articles = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, source, source_url, title, excerpt, author, thumbnail_url,
|
||||
thumbnail_local, published_at, categories, tags
|
||||
"SELECT id, source, source_url, title, excerpt, ai_summary, author,
|
||||
published_at, categories, tags
|
||||
FROM {$table}
|
||||
WHERE is_active = 1
|
||||
ORDER BY published_at DESC
|
||||
|
||||
@@ -81,7 +81,6 @@ class Peptide_News {
|
||||
$this->loader->add_action( 'peptide_news_cron_fetch', $fetcher, 'fetch_all_sources' );
|
||||
$this->loader->add_filter( 'cron_schedules', $fetcher, 'add_custom_cron_schedules' );
|
||||
$this->loader->add_action( 'wp_ajax_peptide_news_backfill_sources', $fetcher, 'ajax_backfill_sources' );
|
||||
$this->loader->add_action( 'wp_ajax_peptide_news_backfill_thumbnails', $fetcher, 'ajax_backfill_thumbnails' );
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
1096
package-lock.json
generated
Normal file
1096
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
package.json
Normal file
28
package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "repo",
|
||||
"version": "1.0.0",
|
||||
"description": "A WordPress plugin that aggregates and displays the latest peptide research news from multiple sources, with built-in click analytics and trend reporting.",
|
||||
"main": "index.js",
|
||||
"directories": {
|
||||
"test": "tests"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://peptiderepo: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@github.com/peptiderepo/peptide-news-plugin.git"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"bugs": {
|
||||
"url": "https://github.com/peptiderepo/peptide-news-plugin/issues"
|
||||
},
|
||||
"homepage": "https://github.com/peptiderepo/peptide-news-plugin#readme",
|
||||
"devDependencies": {
|
||||
"@babel/cli": "^7.28.6",
|
||||
"@babel/core": "^7.29.0",
|
||||
"@babel/preset-react": "^7.28.5"
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
* Plugin Name: Peptide News Aggregator
|
||||
* Plugin URI: https://github.com/peptiderepo/peptide-news-plugin
|
||||
* Description: Aggregates and displays the latest peptide research news from multiple sources with click analytics and trend reporting.
|
||||
* Version: 1.2.2
|
||||
* Version: 1.3.0
|
||||
* Author: Peptide News Team
|
||||
* Author URI: https://github.com/peptiderepo
|
||||
* License: GPL-2.0+
|
||||
@@ -22,7 +22,7 @@ if ( ! defined( 'WPINC' ) ) {
|
||||
/**
|
||||
* Current plugin version — follows SemVer.
|
||||
*/
|
||||
define( 'PEPTIDE_NEWS_VERSION', '1.2.2' );
|
||||
define( 'PEPTIDE_NEWS_VERSION', '1.3.0' );
|
||||
define( 'PEPTIDE_NEWS_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
|
||||
define( 'PEPTIDE_NEWS_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
|
||||
define( 'PEPTIDE_NEWS_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
/**
|
||||
* Public-facing functionality.
|
||||
*
|
||||
* Registers the [peptide_news] shortcode, the sidebar widget,
|
||||
* and handles AJAX click tracking.
|
||||
* Registers the [peptide_news] shortcode which renders a React-powered
|
||||
* news feed, the sidebar widget, and handles AJAX click tracking.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @since 2.0.0 Rewritten to use React frontend.
|
||||
*/
|
||||
class Peptide_News_Public {
|
||||
|
||||
@@ -35,21 +36,19 @@ class Peptide_News_Public {
|
||||
|
||||
/**
|
||||
* Register front-end JS (enqueued on demand by the shortcode/widget).
|
||||
*
|
||||
* Loads React (from WordPress core), the feed component, and
|
||||
* passes configuration via wp_localize_script.
|
||||
*/
|
||||
public function enqueue_scripts() {
|
||||
// React feed component (depends on WP-bundled React).
|
||||
wp_register_script(
|
||||
$this->plugin_name,
|
||||
PEPTIDE_NEWS_PLUGIN_URL . 'public/js/public-script.js',
|
||||
array( 'jquery' ),
|
||||
$this->plugin_name . '-feed',
|
||||
PEPTIDE_NEWS_PLUGIN_URL . 'public/js/peptide-news-feed.js',
|
||||
array( 'react', 'react-dom' ),
|
||||
$this->version,
|
||||
true
|
||||
);
|
||||
|
||||
wp_localize_script( $this->plugin_name, 'peptideNewsPublic', array(
|
||||
'ajax_url' => admin_url( 'admin-ajax.php' ),
|
||||
'nonce' => wp_create_nonce( 'peptide_news_track' ),
|
||||
'session_id' => $this->get_or_create_session_id(),
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,111 +68,35 @@ class Peptide_News_Public {
|
||||
/**
|
||||
* Render the [peptide_news] shortcode.
|
||||
*
|
||||
* Outputs a mount-point div for the React feed component and
|
||||
* enqueues all required assets. Configuration is passed to JS
|
||||
* via a localized script object.
|
||||
*
|
||||
* @param array $atts Shortcode attributes.
|
||||
* @return string HTML output.
|
||||
*/
|
||||
public function render_shortcode( $atts ) {
|
||||
$atts = shortcode_atts( array(
|
||||
'count' => get_option( 'peptide_news_articles_count', 10 ),
|
||||
'layout' => 'list', // card | compact | list
|
||||
'count' => get_option( 'peptide_news_articles_count', 10 ),
|
||||
), $atts, 'peptide_news' );
|
||||
|
||||
$articles = $this->get_articles( absint( $atts['count'] ) );
|
||||
|
||||
if ( empty( $articles ) ) {
|
||||
return '<div class="pn-no-articles"><p>' . esc_html__( 'No peptide news articles available yet. Check back soon!', 'peptide-news' ) . '</p></div>';
|
||||
}
|
||||
$count = absint( $atts['count'] );
|
||||
|
||||
// Enqueue assets only when the shortcode is actually rendered.
|
||||
wp_enqueue_style( $this->plugin_name );
|
||||
wp_enqueue_script( $this->plugin_name );
|
||||
wp_enqueue_script( $this->plugin_name . '-feed' );
|
||||
|
||||
$fallback_thumb = get_option( 'peptide_news_thumbnail_fallback', '' );
|
||||
$layout = sanitize_key( $atts['layout'] );
|
||||
// Pass configuration to the React component.
|
||||
wp_localize_script( $this->plugin_name . '-feed', 'peptideNewsFeed', array(
|
||||
'restUrl' => esc_url_raw( rest_url( 'peptide-news/v1/' ) ),
|
||||
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
|
||||
'nonce' => wp_create_nonce( 'peptide_news_track' ),
|
||||
'sessionId' => $this->get_or_create_session_id(),
|
||||
'count' => $count,
|
||||
) );
|
||||
|
||||
ob_start();
|
||||
?>
|
||||
<div class="pn-news-feed pn-layout-<?php echo esc_attr( $layout ); ?>">
|
||||
<?php foreach ( $articles as $article ) :
|
||||
$thumb = '';
|
||||
if ( ! empty( $article->thumbnail_url ) && '_no_image' !== $article->thumbnail_url ) {
|
||||
$thumb = $article->thumbnail_url;
|
||||
} elseif ( ! empty( $article->thumbnail_local ) ) {
|
||||
$upload_dir = wp_upload_dir();
|
||||
$thumb = $upload_dir['baseurl'] . '/' . $article->thumbnail_local;
|
||||
}
|
||||
if ( empty( $thumb ) ) {
|
||||
$thumb = $fallback_thumb;
|
||||
}
|
||||
$date = wp_date( 'M j, Y', strtotime( $article->published_at ) );
|
||||
?>
|
||||
<article class="pn-article" data-article-id="<?php echo esc_attr( $article->id ); ?>">
|
||||
<?php if ( ! empty( $thumb ) ) : ?>
|
||||
<div class="pn-article-thumb">
|
||||
<a href="<?php echo esc_url( $article->source_url ); ?>"
|
||||
class="pn-track-click"
|
||||
data-article-id="<?php echo esc_attr( $article->id ); ?>"
|
||||
target="_blank" rel="noopener noreferrer">
|
||||
<img src="<?php echo esc_url( $thumb ); ?>"
|
||||
alt="<?php echo esc_attr( $article->title ); ?>"
|
||||
loading="lazy" />
|
||||
</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="pn-article-content">
|
||||
<div class="pn-article-meta">
|
||||
<span class="pn-source"><?php echo esc_html( $article->source ); ?></span>
|
||||
<span class="pn-separator">·</span>
|
||||
<time class="pn-date" datetime="<?php echo esc_attr( $article->published_at ); ?>">
|
||||
<?php echo esc_html( $date ); ?>
|
||||
</time>
|
||||
</div>
|
||||
|
||||
<h3 class="pn-article-title">
|
||||
<a href="<?php echo esc_url( $article->source_url ); ?>"
|
||||
class="pn-track-click"
|
||||
data-article-id="<?php echo esc_attr( $article->id ); ?>"
|
||||
target="_blank" rel="noopener noreferrer">
|
||||
<?php echo esc_html( $article->title ); ?>
|
||||
</a>
|
||||
</h3>
|
||||
|
||||
<?php
|
||||
// Prefer AI summary over raw excerpt.
|
||||
$display_text = ! empty( $article->ai_summary ) ? $article->ai_summary : ( $article->excerpt ?? '' );
|
||||
if ( ! empty( $display_text ) ) : ?>
|
||||
<p class="pn-article-excerpt">
|
||||
<?php echo esc_html( $display_text ); ?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ( ! empty( $article->author ) ) : ?>
|
||||
<span class="pn-author">
|
||||
<?php echo esc_html( $article->author ); ?>
|
||||
</span>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php
|
||||
// Show AI-extracted keyword tags if available, fall back to categories.
|
||||
$tag_source = ! empty( $article->tags ) ? $article->tags : ( $article->categories ?? '' );
|
||||
if ( ! empty( $tag_source ) ) : ?>
|
||||
<div class="pn-tags">
|
||||
<?php
|
||||
$tag_items = array_map( 'trim', explode( ',', $tag_source ) );
|
||||
foreach ( array_slice( $tag_items, 0, 5 ) as $tag_item ) :
|
||||
if ( empty( $tag_item ) ) continue;
|
||||
?>
|
||||
<span class="pn-tag"><?php echo esc_html( $tag_item ); ?></span>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</article>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
// React mount point — the component renders into this div.
|
||||
return '<div data-peptide-news-feed></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,48 +137,9 @@ class Peptide_News_Public {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active articles from the database.
|
||||
*
|
||||
* @param int $count Number of articles.
|
||||
* @return array
|
||||
*/
|
||||
private function get_articles( $count ) {
|
||||
global $wpdb;
|
||||
|
||||
$table = $wpdb->prefix . 'peptide_news_articles';
|
||||
|
||||
// Use transient cache to avoid DB hits on every page load.
|
||||
$cache_key = 'peptide_news_articles_' . $count;
|
||||
$cached = get_transient( $cache_key );
|
||||
|
||||
if ( false !== $cached ) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$articles = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, source, source_url, title, excerpt, ai_summary, author, thumbnail_url,
|
||||
thumbnail_local, published_at, categories, tags
|
||||
FROM {$table}
|
||||
WHERE is_active = 1
|
||||
ORDER BY published_at DESC
|
||||
LIMIT %d",
|
||||
$count
|
||||
) );
|
||||
|
||||
// Cache for 5 minutes.
|
||||
set_transient( $cache_key, $articles, 5 * MINUTE_IN_SECONDS );
|
||||
|
||||
return $articles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate or retrieve a session ID for visitor tracking.
|
||||
*
|
||||
* Sets the cookie in PHP if it doesn't exist so the value
|
||||
* is consistent between the server-side localized script data
|
||||
* and the client-side cookie.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function get_or_create_session_id() {
|
||||
@@ -265,7 +149,6 @@ class Peptide_News_Public {
|
||||
|
||||
$session_id = wp_generate_uuid4();
|
||||
|
||||
// Set a 30-minute session cookie (matches JS-side behaviour).
|
||||
if ( ! headers_sent() ) {
|
||||
setcookie(
|
||||
'pn_session_id',
|
||||
@@ -274,7 +157,7 @@ class Peptide_News_Public {
|
||||
'expires' => time() + 1800,
|
||||
'path' => '/',
|
||||
'secure' => is_ssl(),
|
||||
'httponly' => false, // JS needs read access for sendBeacon.
|
||||
'httponly' => false,
|
||||
'samesite' => 'Lax',
|
||||
)
|
||||
);
|
||||
@@ -313,7 +196,7 @@ class Peptide_News_Widget extends WP_Widget {
|
||||
}
|
||||
|
||||
$public = new Peptide_News_Public( 'peptide-news', PEPTIDE_NEWS_VERSION );
|
||||
echo $public->render_shortcode( array( 'count' => $count, 'layout' => 'compact' ) );
|
||||
echo $public->render_shortcode( array( 'count' => $count ) );
|
||||
|
||||
echo $args['after_widget'];
|
||||
}
|
||||
|
||||
@@ -1,114 +1,79 @@
|
||||
/**
|
||||
* Peptide News Aggregator – Public Styles
|
||||
* Peptide News Feed — Public Styles
|
||||
*
|
||||
* Styles for the front-end display of peptide news articles.
|
||||
* Clean, modern news feed layout without thumbnails.
|
||||
* Focuses on readability and content hierarchy.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @since 1.2.2 Rewritten for list layout with thumbnail left / text right.
|
||||
* @since 2.0.0
|
||||
*/
|
||||
|
||||
/* ── Feed container ────────────────────────────────────────────── */
|
||||
.pn-news-feed {
|
||||
max-width: 760px;
|
||||
margin: 0 auto;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
|
||||
color: #1a1a2e;
|
||||
line-height: 1.6;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* ── Articles list ─────────────────────────────────────────────── */
|
||||
.pn-articles-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
|
||||
}
|
||||
|
||||
.pn-no-articles p {
|
||||
text-align: center;
|
||||
color: #666;
|
||||
padding: 2rem 1rem;
|
||||
font-size: 0.9375rem;
|
||||
}
|
||||
|
||||
/* ── Individual article row ────────────────────────────────────── */
|
||||
/* ── Individual article ────────────────────────────────────────── */
|
||||
.pn-article {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: flex-start;
|
||||
gap: 1.25rem;
|
||||
padding: 1.25rem 0;
|
||||
border-bottom: 1px solid #e8e8e8;
|
||||
padding: 1.5rem 0;
|
||||
border-bottom: 1px solid #e8eaed;
|
||||
transition: background-color 0.15s ease;
|
||||
}
|
||||
|
||||
.pn-article:first-child {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.pn-article:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.pn-article:hover {
|
||||
background-color: #fafbfc;
|
||||
}
|
||||
|
||||
/* ── Thumbnail (left column, fixed width) ──────────────────────── */
|
||||
.pn-article-thumb {
|
||||
flex: 0 0 160px;
|
||||
width: 160px;
|
||||
min-height: 100px;
|
||||
overflow: hidden;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.pn-article-thumb a {
|
||||
display: block;
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
.pn-article-thumb img {
|
||||
width: 100%;
|
||||
height: 110px;
|
||||
object-fit: cover;
|
||||
border-radius: 6px;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.pn-article:hover .pn-article-thumb img {
|
||||
transform: scale(1.03);
|
||||
}
|
||||
|
||||
/* ── Content (right column, flexible) ──────────────────────────── */
|
||||
.pn-article-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ── Meta line (source · date) ─────────────────────────────────── */
|
||||
.pn-article-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
font-size: 0.8rem;
|
||||
color: #777;
|
||||
margin-bottom: 0.35rem;
|
||||
margin-bottom: 0.375rem;
|
||||
font-size: 0.8125rem;
|
||||
color: #6b7280;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.pn-source {
|
||||
font-weight: 600;
|
||||
color: #555;
|
||||
color: #4b5563;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.025em;
|
||||
font-size: 0.7rem;
|
||||
letter-spacing: 0.03em;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.pn-separator {
|
||||
color: #ccc;
|
||||
color: #d1d5db;
|
||||
}
|
||||
|
||||
.pn-date {
|
||||
color: #888;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
/* ── Title ─────────────────────────────────────────────────────── */
|
||||
.pn-article-title {
|
||||
font-size: 1.05rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
margin: 0 0 0.4rem;
|
||||
color: #1a1a2e;
|
||||
margin: 0 0 0.5rem;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.pn-article-title a {
|
||||
@@ -118,23 +83,23 @@
|
||||
}
|
||||
|
||||
.pn-article-title a:hover {
|
||||
color: #0073aa;
|
||||
color: #2563eb;
|
||||
}
|
||||
|
||||
.pn-article-title a:focus,
|
||||
.pn-article-thumb a:focus {
|
||||
outline: 2px solid #0073aa;
|
||||
.pn-article-title a:focus-visible {
|
||||
outline: 2px solid #2563eb;
|
||||
outline-offset: 2px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
/* ── Excerpt / AI summary ──────────────────────────────────────── */
|
||||
.pn-article-excerpt {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.6;
|
||||
color: #555;
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.65;
|
||||
color: #4b5563;
|
||||
margin: 0 0 0.625rem;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -142,9 +107,9 @@
|
||||
/* ── Author ────────────────────────────────────────────────────── */
|
||||
.pn-author {
|
||||
display: inline-block;
|
||||
font-size: 0.775rem;
|
||||
color: #888;
|
||||
margin-bottom: 0.35rem;
|
||||
font-size: 0.8125rem;
|
||||
color: #9ca3af;
|
||||
margin-bottom: 0.375rem;
|
||||
}
|
||||
|
||||
.pn-author::before {
|
||||
@@ -156,60 +121,266 @@
|
||||
.pn-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
margin-top: 0.25rem;
|
||||
gap: 0.375rem;
|
||||
margin-top: 0.375rem;
|
||||
}
|
||||
|
||||
.pn-tag {
|
||||
display: inline-block;
|
||||
font-size: 0.7rem;
|
||||
background: #f0f4f8;
|
||||
color: #4a6fa5;
|
||||
padding: 0.15rem 0.55rem;
|
||||
border-radius: 12px;
|
||||
font-size: 0.6875rem;
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
padding: 0.1875rem 0.625rem;
|
||||
border-radius: 100px;
|
||||
line-height: 1.5;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
/* ── Compact layout override (for widgets) ─────────────────────── */
|
||||
.pn-layout-compact .pn-article {
|
||||
gap: 0.85rem;
|
||||
padding: 0.75rem 0;
|
||||
/* ── Loading skeleton ──────────────────────────────────────────── */
|
||||
.pn-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.pn-layout-compact .pn-article-thumb {
|
||||
flex: 0 0 80px;
|
||||
width: 80px;
|
||||
min-height: 56px;
|
||||
.pn-skeleton-card {
|
||||
padding: 1.5rem 0;
|
||||
border-bottom: 1px solid #e8eaed;
|
||||
}
|
||||
|
||||
.pn-layout-compact .pn-article-thumb img {
|
||||
height: 56px;
|
||||
.pn-skeleton-card:first-child {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.pn-layout-compact .pn-article-title {
|
||||
font-size: 0.9rem;
|
||||
.pn-skeleton-line {
|
||||
background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
|
||||
background-size: 200% 100%;
|
||||
animation: pn-shimmer 1.5s ease-in-out infinite;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.pn-layout-compact .pn-article-excerpt,
|
||||
.pn-layout-compact .pn-author,
|
||||
.pn-layout-compact .pn-tags {
|
||||
display: none;
|
||||
.pn-skeleton-meta {
|
||||
width: 140px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
/* ── Responsive: stack on small screens ────────────────────────── */
|
||||
.pn-skeleton-title {
|
||||
width: 85%;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.pn-skeleton-excerpt {
|
||||
width: 100%;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.pn-skeleton-excerpt-short {
|
||||
width: 60%;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.pn-skeleton-tags {
|
||||
display: flex;
|
||||
gap: 0.375rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.pn-skeleton-tag {
|
||||
width: 64px;
|
||||
height: 22px;
|
||||
border-radius: 100px;
|
||||
background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
|
||||
background-size: 200% 100%;
|
||||
animation: pn-shimmer 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pn-shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
/* ── Error state ───────────────────────────────────────────────── */
|
||||
.pn-error {
|
||||
text-align: center;
|
||||
padding: 2.5rem 1rem;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.pn-error p {
|
||||
font-size: 0.9375rem;
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
.pn-retry-btn {
|
||||
display: inline-block;
|
||||
padding: 0.5rem 1.25rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #2563eb;
|
||||
background: #eff6ff;
|
||||
border: 1px solid #bfdbfe;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.pn-retry-btn:hover {
|
||||
background: #dbeafe;
|
||||
border-color: #93c5fd;
|
||||
}
|
||||
|
||||
.pn-retry-btn:focus-visible {
|
||||
outline: 2px solid #2563eb;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ── Empty state ───────────────────────────────────────────────── */
|
||||
.pn-empty {
|
||||
text-align: center;
|
||||
padding: 2.5rem 1rem;
|
||||
}
|
||||
|
||||
.pn-empty p {
|
||||
font-size: 0.9375rem;
|
||||
color: #6b7280;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ── Pagination ────────────────────────────────────────────────── */
|
||||
.pn-pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
padding: 1.5rem 0 0.5rem;
|
||||
margin-top: 0.5rem;
|
||||
border-top: 1px solid #e8eaed;
|
||||
}
|
||||
|
||||
.pn-page-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #374151;
|
||||
background: #fff;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.pn-page-btn:hover:not(:disabled) {
|
||||
background: #f9fafb;
|
||||
border-color: #9ca3af;
|
||||
}
|
||||
|
||||
.pn-page-btn:disabled {
|
||||
color: #d1d5db;
|
||||
border-color: #e5e7eb;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.pn-page-btn:focus-visible {
|
||||
outline: 2px solid #2563eb;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.pn-page-info {
|
||||
font-size: 0.8125rem;
|
||||
color: #6b7280;
|
||||
min-width: 100px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ── Responsive ────────────────────────────────────────────────── */
|
||||
@media (max-width: 600px) {
|
||||
.pn-article {
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
.pn-article-title {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.pn-article-thumb {
|
||||
flex: none;
|
||||
width: 100%;
|
||||
.pn-article-excerpt {
|
||||
font-size: 0.875rem;
|
||||
-webkit-line-clamp: 2;
|
||||
}
|
||||
|
||||
.pn-article-thumb img {
|
||||
height: 180px;
|
||||
.pn-pagination {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.pn-page-btn {
|
||||
padding: 0.375rem 0.75rem;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Dark mode support via prefers-color-scheme ────────────────── */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.pn-news-feed {
|
||||
color: #e5e7eb;
|
||||
}
|
||||
|
||||
.pn-article {
|
||||
border-bottom-color: #374151;
|
||||
}
|
||||
|
||||
.pn-article-title {
|
||||
color: #f3f4f6;
|
||||
}
|
||||
|
||||
.pn-article-title a:hover {
|
||||
color: #60a5fa;
|
||||
}
|
||||
|
||||
.pn-source {
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.pn-article-excerpt {
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.pn-tag {
|
||||
background: #1e3a5f;
|
||||
color: #93c5fd;
|
||||
}
|
||||
|
||||
.pn-skeleton-line,
|
||||
.pn-skeleton-tag {
|
||||
background: linear-gradient(90deg, #1f2937 25%, #374151 50%, #1f2937 75%);
|
||||
background-size: 200% 100%;
|
||||
}
|
||||
|
||||
.pn-page-btn {
|
||||
color: #e5e7eb;
|
||||
background: #1f2937;
|
||||
border-color: #4b5563;
|
||||
}
|
||||
|
||||
.pn-page-btn:hover:not(:disabled) {
|
||||
background: #374151;
|
||||
}
|
||||
|
||||
.pn-page-btn:disabled {
|
||||
color: #4b5563;
|
||||
border-color: #374151;
|
||||
}
|
||||
|
||||
.pn-retry-btn {
|
||||
color: #60a5fa;
|
||||
background: #1e3a5f;
|
||||
border-color: #1d4ed8;
|
||||
}
|
||||
|
||||
.pn-pagination {
|
||||
border-top-color: #374151;
|
||||
}
|
||||
|
||||
.pn-skeleton-card {
|
||||
border-bottom-color: #374151;
|
||||
}
|
||||
}
|
||||
|
||||
367
public/js/peptide-news-feed.js
Normal file
367
public/js/peptide-news-feed.js
Normal file
@@ -0,0 +1,367 @@
|
||||
/**
|
||||
* Peptide News Feed — React Frontend
|
||||
*
|
||||
* A clean, accessible news feed component that displays peptide research
|
||||
* articles with title, summary, source, date, and keyword tags.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
const {
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
useRef,
|
||||
memo
|
||||
} = React;
|
||||
|
||||
/* ── Constants ──────────────────────────────────────────────────────── */
|
||||
|
||||
const ARTICLES_PER_PAGE = 10;
|
||||
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
/* ── Utilities ──────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Format an ISO date string to a human-readable form.
|
||||
*
|
||||
* @param {string} dateStr ISO date string.
|
||||
* @returns {string} Formatted date (e.g., "Apr 5, 2026").
|
||||
*/
|
||||
function formatDate(dateStr) {
|
||||
if (!dateStr) return '';
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d.getTime())) return dateStr;
|
||||
return d.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric'
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate a human-readable relative time string.
|
||||
*
|
||||
* @param {string} dateStr ISO date string.
|
||||
* @returns {string} Relative time (e.g., "2 hours ago").
|
||||
*/
|
||||
function timeAgo(dateStr) {
|
||||
if (!dateStr) return '';
|
||||
const now = Date.now();
|
||||
const then = new Date(dateStr).getTime();
|
||||
if (isNaN(then)) return '';
|
||||
const diffMs = now - then;
|
||||
const diffMin = Math.floor(diffMs / 60000);
|
||||
if (diffMin < 1) return 'Just now';
|
||||
if (diffMin < 60) return `${diffMin}m ago`;
|
||||
const diffHr = Math.floor(diffMin / 60);
|
||||
if (diffHr < 24) return `${diffHr}h ago`;
|
||||
const diffDay = Math.floor(diffHr / 24);
|
||||
if (diffDay < 7) return `${diffDay}d ago`;
|
||||
return formatDate(dateStr);
|
||||
}
|
||||
|
||||
/* ── Simple in-memory cache ─────────────────────────────────────────── */
|
||||
|
||||
const apiCache = new Map();
|
||||
function getCached(key) {
|
||||
const entry = apiCache.get(key);
|
||||
if (!entry) return null;
|
||||
if (Date.now() - entry.ts > CACHE_TTL_MS) {
|
||||
apiCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
return entry.data;
|
||||
}
|
||||
function setCache(key, data) {
|
||||
apiCache.set(key, {
|
||||
data,
|
||||
ts: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
/* ── API Layer ──────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Fetch articles from the WP REST API with caching.
|
||||
*
|
||||
* @param {string} restUrl Base REST URL.
|
||||
* @param {number} page Page number.
|
||||
* @param {number} count Articles per page.
|
||||
* @param {AbortSignal} signal Abort signal for cleanup.
|
||||
* @returns {Promise<Object>} Response data.
|
||||
*/
|
||||
async function fetchArticles(restUrl, page, count, signal) {
|
||||
const cacheKey = `${restUrl}:${page}:${count}`;
|
||||
const cached = getCached(cacheKey);
|
||||
if (cached) return cached;
|
||||
const url = `${restUrl}articles?count=${count}&page=${page}`;
|
||||
const resp = await fetch(url, {
|
||||
signal
|
||||
});
|
||||
if (!resp.ok) {
|
||||
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
|
||||
}
|
||||
const data = await resp.json();
|
||||
setCache(cacheKey, data);
|
||||
return data;
|
||||
}
|
||||
|
||||
/* ── Click Tracking ─────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Track an outbound click via sendBeacon or fallback XHR.
|
||||
*
|
||||
* @param {number} articleId
|
||||
*/
|
||||
function trackClick(articleId) {
|
||||
const config = window.peptideNewsFeed || {};
|
||||
if (!config.ajaxUrl || !config.nonce) return;
|
||||
const formData = new FormData();
|
||||
formData.append('action', 'peptide_news_track_click');
|
||||
formData.append('nonce', config.nonce);
|
||||
formData.append('article_id', articleId);
|
||||
formData.append('referrer', document.referrer || '');
|
||||
formData.append('page_url', window.location.href);
|
||||
formData.append('session_id', config.sessionId || '');
|
||||
if (navigator.sendBeacon) {
|
||||
navigator.sendBeacon(config.ajaxUrl, formData);
|
||||
} else {
|
||||
fetch(config.ajaxUrl, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Components ─────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Single keyword tag pill.
|
||||
*/
|
||||
const Tag = memo(function Tag({
|
||||
label
|
||||
}) {
|
||||
return /*#__PURE__*/React.createElement("span", {
|
||||
className: "pn-tag"
|
||||
}, label);
|
||||
});
|
||||
|
||||
/**
|
||||
* Single article card.
|
||||
*/
|
||||
const ArticleCard = memo(function ArticleCard({
|
||||
article
|
||||
}) {
|
||||
const summary = article.ai_summary || article.excerpt || '';
|
||||
const tagSource = article.tags || article.categories || '';
|
||||
const tags = tagSource ? tagSource.split(',').map(t => t.trim()).filter(Boolean).slice(0, 5) : [];
|
||||
const handleClick = useCallback(() => {
|
||||
trackClick(article.id);
|
||||
}, [article.id]);
|
||||
return /*#__PURE__*/React.createElement("article", {
|
||||
className: "pn-article",
|
||||
role: "article"
|
||||
}, /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-article-meta"
|
||||
}, /*#__PURE__*/React.createElement("span", {
|
||||
className: "pn-source"
|
||||
}, article.source), /*#__PURE__*/React.createElement("span", {
|
||||
className: "pn-separator",
|
||||
"aria-hidden": "true"
|
||||
}, "\xB7"), /*#__PURE__*/React.createElement("time", {
|
||||
className: "pn-date",
|
||||
dateTime: article.published_at,
|
||||
title: formatDate(article.published_at)
|
||||
}, timeAgo(article.published_at))), /*#__PURE__*/React.createElement("h3", {
|
||||
className: "pn-article-title"
|
||||
}, /*#__PURE__*/React.createElement("a", {
|
||||
href: article.source_url,
|
||||
onClick: handleClick,
|
||||
target: "_blank",
|
||||
rel: "noopener noreferrer"
|
||||
}, article.title)), summary && /*#__PURE__*/React.createElement("p", {
|
||||
className: "pn-article-excerpt"
|
||||
}, summary), article.author && /*#__PURE__*/React.createElement("span", {
|
||||
className: "pn-author"
|
||||
}, article.author), tags.length > 0 && /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-tags",
|
||||
role: "list",
|
||||
"aria-label": "Keywords"
|
||||
}, tags.map(tag => /*#__PURE__*/React.createElement(Tag, {
|
||||
key: tag,
|
||||
label: tag
|
||||
}))));
|
||||
});
|
||||
|
||||
/**
|
||||
* Loading skeleton placeholder.
|
||||
*/
|
||||
function LoadingSkeleton({
|
||||
count = 3
|
||||
}) {
|
||||
return /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-loading",
|
||||
"aria-busy": "true",
|
||||
"aria-label": "Loading articles"
|
||||
}, Array.from({
|
||||
length: count
|
||||
}, (_, i) => /*#__PURE__*/React.createElement("div", {
|
||||
key: i,
|
||||
className: "pn-skeleton-card"
|
||||
}, /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-line pn-skeleton-meta"
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-line pn-skeleton-title"
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-line pn-skeleton-excerpt"
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-line pn-skeleton-excerpt-short"
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-tags"
|
||||
}, /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-tag"
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-tag"
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-skeleton-tag"
|
||||
})))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Error state with retry.
|
||||
*/
|
||||
function ErrorMessage({
|
||||
message,
|
||||
onRetry
|
||||
}) {
|
||||
return /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-error",
|
||||
role: "alert"
|
||||
}, /*#__PURE__*/React.createElement("p", null, "Unable to load articles. ", message), /*#__PURE__*/React.createElement("button", {
|
||||
className: "pn-retry-btn",
|
||||
onClick: onRetry,
|
||||
type: "button"
|
||||
}, "Try Again"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Empty state.
|
||||
*/
|
||||
function EmptyState() {
|
||||
return /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-empty"
|
||||
}, /*#__PURE__*/React.createElement("p", null, "No peptide news articles available yet. Check back soon!"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Pagination controls.
|
||||
*/
|
||||
const Pagination = memo(function Pagination({
|
||||
page,
|
||||
totalPages,
|
||||
onPageChange
|
||||
}) {
|
||||
if (totalPages <= 1) return null;
|
||||
return /*#__PURE__*/React.createElement("nav", {
|
||||
className: "pn-pagination",
|
||||
"aria-label": "Article pages"
|
||||
}, /*#__PURE__*/React.createElement("button", {
|
||||
className: "pn-page-btn",
|
||||
onClick: () => onPageChange(page - 1),
|
||||
disabled: page <= 1,
|
||||
"aria-label": "Previous page",
|
||||
type: "button"
|
||||
}, "\u2190 Newer"), /*#__PURE__*/React.createElement("span", {
|
||||
className: "pn-page-info",
|
||||
"aria-current": "page"
|
||||
}, "Page ", page, " of ", totalPages), /*#__PURE__*/React.createElement("button", {
|
||||
className: "pn-page-btn",
|
||||
onClick: () => onPageChange(page + 1),
|
||||
disabled: page >= totalPages,
|
||||
"aria-label": "Next page",
|
||||
type: "button"
|
||||
}, "Older \u2192"));
|
||||
});
|
||||
|
||||
/* ── Main Feed Component ────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* PeptideNewsFeed — root component.
|
||||
*
|
||||
* Reads configuration from window.peptideNewsFeed which is
|
||||
* localized by the PHP shortcode renderer.
|
||||
*/
|
||||
function PeptideNewsFeed() {
|
||||
const config = window.peptideNewsFeed || {};
|
||||
const restUrl = config.restUrl || '/wp-json/peptide-news/v1/';
|
||||
const perPage = config.count || ARTICLES_PER_PAGE;
|
||||
const [articles, setArticles] = useState([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const feedRef = useRef(null);
|
||||
const loadArticles = useCallback(async (pageNum, signal) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await fetchArticles(restUrl, pageNum, perPage, signal);
|
||||
setArticles(data.articles || []);
|
||||
setTotalPages(data.total_pages || 1);
|
||||
} catch (err) {
|
||||
if (err.name !== 'AbortError') {
|
||||
setError(err.message || 'Something went wrong.');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [restUrl, perPage]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
loadArticles(page, controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [page, loadArticles]);
|
||||
const handlePageChange = useCallback(newPage => {
|
||||
setPage(newPage);
|
||||
// Scroll feed container into view on pagination.
|
||||
if (feedRef.current) {
|
||||
feedRef.current.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start'
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
const handleRetry = useCallback(() => {
|
||||
loadArticles(page);
|
||||
}, [page, loadArticles]);
|
||||
return /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-news-feed",
|
||||
ref: feedRef
|
||||
}, loading && /*#__PURE__*/React.createElement(LoadingSkeleton, {
|
||||
count: Math.min(perPage, 5)
|
||||
}), !loading && error && /*#__PURE__*/React.createElement(ErrorMessage, {
|
||||
message: error,
|
||||
onRetry: handleRetry
|
||||
}), !loading && !error && articles.length === 0 && /*#__PURE__*/React.createElement(EmptyState, null), !loading && !error && articles.length > 0 && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
|
||||
className: "pn-articles-list",
|
||||
role: "feed",
|
||||
"aria-label": "Peptide news articles"
|
||||
}, articles.map(article => /*#__PURE__*/React.createElement(ArticleCard, {
|
||||
key: article.id,
|
||||
article: article
|
||||
}))), /*#__PURE__*/React.createElement(Pagination, {
|
||||
page: page,
|
||||
totalPages: totalPages,
|
||||
onPageChange: handlePageChange
|
||||
})));
|
||||
}
|
||||
|
||||
/* ── Mount ──────────────────────────────────────────────────────────── */
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const containers = document.querySelectorAll('[data-peptide-news-feed]');
|
||||
containers.forEach(function (el) {
|
||||
const root = ReactDOM.createRoot(el);
|
||||
root.render(React.createElement(PeptideNewsFeed));
|
||||
});
|
||||
});
|
||||
@@ -1,83 +1,9 @@
|
||||
/**
|
||||
* Peptide News — Public Click Tracker
|
||||
* Peptide News — Legacy Click Tracker (deprecated)
|
||||
*
|
||||
* Tracks outbound clicks on article links via AJAX and
|
||||
* manages visitor session cookies.
|
||||
* Click tracking is now handled by the React feed component.
|
||||
* This file is kept as an empty placeholder for backward compatibility.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @deprecated 2.0.0 Use peptide-news-feed.js instead.
|
||||
*/
|
||||
(function ($) {
|
||||
'use strict';
|
||||
|
||||
// Set session cookie if it doesn't exist.
|
||||
function initSession() {
|
||||
if (!getCookie('pn_session_id')) {
|
||||
var sessionId = peptideNewsPublic.session_id || generateUUID();
|
||||
setCookie('pn_session_id', sessionId, 30); // 30-minute cookie
|
||||
}
|
||||
}
|
||||
|
||||
function getCookie(name) {
|
||||
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
|
||||
return match ? decodeURIComponent(match[2]) : null;
|
||||
}
|
||||
|
||||
function setCookie(name, value, minutes) {
|
||||
var d = new Date();
|
||||
d.setTime(d.getTime() + minutes * 60 * 1000);
|
||||
var cookie = name + '=' + encodeURIComponent(value) +
|
||||
';expires=' + d.toUTCString() +
|
||||
';path=/;SameSite=Lax';
|
||||
if (window.location.protocol === 'https:') {
|
||||
cookie += ';Secure';
|
||||
}
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
function generateUUID() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
||||
var r = (Math.random() * 16) | 0;
|
||||
var v = c === 'x' ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
// Track click via AJAX (fire-and-forget with beacon fallback).
|
||||
function trackClick(articleId) {
|
||||
var data = {
|
||||
action: 'peptide_news_track_click',
|
||||
nonce: peptideNewsPublic.nonce,
|
||||
article_id: articleId,
|
||||
referrer: document.referrer || '',
|
||||
page_url: window.location.href,
|
||||
session_id: getCookie('pn_session_id') || '',
|
||||
};
|
||||
|
||||
// Try sendBeacon first (non-blocking, survives page navigation).
|
||||
if (navigator.sendBeacon) {
|
||||
var formData = new FormData();
|
||||
Object.keys(data).forEach(function (key) {
|
||||
formData.append(key, data[key]);
|
||||
});
|
||||
navigator.sendBeacon(peptideNewsPublic.ajax_url, formData);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to AJAX.
|
||||
$.post(peptideNewsPublic.ajax_url, data);
|
||||
}
|
||||
|
||||
$(document).ready(function () {
|
||||
initSession();
|
||||
|
||||
// Delegate click events on tracked links.
|
||||
$(document).on('click', '.pn-track-click', function () {
|
||||
var articleId = $(this).data('article-id');
|
||||
if (articleId) {
|
||||
trackClick(articleId);
|
||||
}
|
||||
// Don't prevent default — let the link open normally.
|
||||
});
|
||||
});
|
||||
|
||||
})(jQuery);
|
||||
|
||||
374
public/react-app/PeptideNewsFeed.jsx
Normal file
374
public/react-app/PeptideNewsFeed.jsx
Normal file
@@ -0,0 +1,374 @@
|
||||
/**
|
||||
* Peptide News Feed — React Frontend
|
||||
*
|
||||
* A clean, accessible news feed component that displays peptide research
|
||||
* articles with title, summary, source, date, and keyword tags.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
const { useState, useEffect, useCallback, useRef, memo } = React;
|
||||
|
||||
/* ── Constants ──────────────────────────────────────────────────────── */
|
||||
|
||||
const ARTICLES_PER_PAGE = 10;
|
||||
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
/* ── Utilities ──────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Format an ISO date string to a human-readable form.
|
||||
*
|
||||
* @param {string} dateStr ISO date string.
|
||||
* @returns {string} Formatted date (e.g., "Apr 5, 2026").
|
||||
*/
|
||||
function formatDate(dateStr) {
|
||||
if (!dateStr) return '';
|
||||
const d = new Date(dateStr);
|
||||
if (isNaN(d.getTime())) return dateStr;
|
||||
return d.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate a human-readable relative time string.
|
||||
*
|
||||
* @param {string} dateStr ISO date string.
|
||||
* @returns {string} Relative time (e.g., "2 hours ago").
|
||||
*/
|
||||
function timeAgo(dateStr) {
|
||||
if (!dateStr) return '';
|
||||
const now = Date.now();
|
||||
const then = new Date(dateStr).getTime();
|
||||
if (isNaN(then)) return '';
|
||||
const diffMs = now - then;
|
||||
const diffMin = Math.floor(diffMs / 60000);
|
||||
if (diffMin < 1) return 'Just now';
|
||||
if (diffMin < 60) return `${diffMin}m ago`;
|
||||
const diffHr = Math.floor(diffMin / 60);
|
||||
if (diffHr < 24) return `${diffHr}h ago`;
|
||||
const diffDay = Math.floor(diffHr / 24);
|
||||
if (diffDay < 7) return `${diffDay}d ago`;
|
||||
return formatDate(dateStr);
|
||||
}
|
||||
|
||||
/* ── Simple in-memory cache ─────────────────────────────────────────── */
|
||||
|
||||
const apiCache = new Map();
|
||||
|
||||
function getCached(key) {
|
||||
const entry = apiCache.get(key);
|
||||
if (!entry) return null;
|
||||
if (Date.now() - entry.ts > CACHE_TTL_MS) {
|
||||
apiCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
return entry.data;
|
||||
}
|
||||
|
||||
function setCache(key, data) {
|
||||
apiCache.set(key, { data, ts: Date.now() });
|
||||
}
|
||||
|
||||
/* ── API Layer ──────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Fetch articles from the WP REST API with caching.
|
||||
*
|
||||
* @param {string} restUrl Base REST URL.
|
||||
* @param {number} page Page number.
|
||||
* @param {number} count Articles per page.
|
||||
* @param {AbortSignal} signal Abort signal for cleanup.
|
||||
* @returns {Promise<Object>} Response data.
|
||||
*/
|
||||
async function fetchArticles(restUrl, page, count, signal) {
|
||||
const cacheKey = `${restUrl}:${page}:${count}`;
|
||||
const cached = getCached(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
const url = `${restUrl}articles?count=${count}&page=${page}`;
|
||||
const resp = await fetch(url, { signal });
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
setCache(cacheKey, data);
|
||||
return data;
|
||||
}
|
||||
|
||||
/* ── Click Tracking ─────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Track an outbound click via sendBeacon or fallback XHR.
|
||||
*
|
||||
* @param {number} articleId
|
||||
*/
|
||||
function trackClick(articleId) {
|
||||
const config = window.peptideNewsFeed || {};
|
||||
if (!config.ajaxUrl || !config.nonce) return;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('action', 'peptide_news_track_click');
|
||||
formData.append('nonce', config.nonce);
|
||||
formData.append('article_id', articleId);
|
||||
formData.append('referrer', document.referrer || '');
|
||||
formData.append('page_url', window.location.href);
|
||||
formData.append('session_id', config.sessionId || '');
|
||||
|
||||
if (navigator.sendBeacon) {
|
||||
navigator.sendBeacon(config.ajaxUrl, formData);
|
||||
} else {
|
||||
fetch(config.ajaxUrl, { method: 'POST', body: formData }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Components ─────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Single keyword tag pill.
|
||||
*/
|
||||
const Tag = memo(function Tag({ label }) {
|
||||
return <span className="pn-tag">{label}</span>;
|
||||
});
|
||||
|
||||
/**
|
||||
* Single article card.
|
||||
*/
|
||||
const ArticleCard = memo(function ArticleCard({ article }) {
|
||||
const summary = article.ai_summary || article.excerpt || '';
|
||||
const tagSource = article.tags || article.categories || '';
|
||||
const tags = tagSource
|
||||
? tagSource.split(',').map((t) => t.trim()).filter(Boolean).slice(0, 5)
|
||||
: [];
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
trackClick(article.id);
|
||||
}, [article.id]);
|
||||
|
||||
return (
|
||||
<article className="pn-article" role="article">
|
||||
<div className="pn-article-meta">
|
||||
<span className="pn-source">{article.source}</span>
|
||||
<span className="pn-separator" aria-hidden="true">·</span>
|
||||
<time
|
||||
className="pn-date"
|
||||
dateTime={article.published_at}
|
||||
title={formatDate(article.published_at)}
|
||||
>
|
||||
{timeAgo(article.published_at)}
|
||||
</time>
|
||||
</div>
|
||||
|
||||
<h3 className="pn-article-title">
|
||||
<a
|
||||
href={article.source_url}
|
||||
onClick={handleClick}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{article.title}
|
||||
</a>
|
||||
</h3>
|
||||
|
||||
{summary && (
|
||||
<p className="pn-article-excerpt">{summary}</p>
|
||||
)}
|
||||
|
||||
{article.author && (
|
||||
<span className="pn-author">{article.author}</span>
|
||||
)}
|
||||
|
||||
{tags.length > 0 && (
|
||||
<div className="pn-tags" role="list" aria-label="Keywords">
|
||||
{tags.map((tag) => (
|
||||
<Tag key={tag} label={tag} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Loading skeleton placeholder.
|
||||
*/
|
||||
function LoadingSkeleton({ count = 3 }) {
|
||||
return (
|
||||
<div className="pn-loading" aria-busy="true" aria-label="Loading articles">
|
||||
{Array.from({ length: count }, (_, i) => (
|
||||
<div key={i} className="pn-skeleton-card">
|
||||
<div className="pn-skeleton-line pn-skeleton-meta" />
|
||||
<div className="pn-skeleton-line pn-skeleton-title" />
|
||||
<div className="pn-skeleton-line pn-skeleton-excerpt" />
|
||||
<div className="pn-skeleton-line pn-skeleton-excerpt-short" />
|
||||
<div className="pn-skeleton-tags">
|
||||
<div className="pn-skeleton-tag" />
|
||||
<div className="pn-skeleton-tag" />
|
||||
<div className="pn-skeleton-tag" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Error state with retry.
|
||||
*/
|
||||
function ErrorMessage({ message, onRetry }) {
|
||||
return (
|
||||
<div className="pn-error" role="alert">
|
||||
<p>Unable to load articles. {message}</p>
|
||||
<button className="pn-retry-btn" onClick={onRetry} type="button">
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Empty state.
|
||||
*/
|
||||
function EmptyState() {
|
||||
return (
|
||||
<div className="pn-empty">
|
||||
<p>No peptide news articles available yet. Check back soon!</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pagination controls.
|
||||
*/
|
||||
const Pagination = memo(function Pagination({ page, totalPages, onPageChange }) {
|
||||
if (totalPages <= 1) return null;
|
||||
|
||||
return (
|
||||
<nav className="pn-pagination" aria-label="Article pages">
|
||||
<button
|
||||
className="pn-page-btn"
|
||||
onClick={() => onPageChange(page - 1)}
|
||||
disabled={page <= 1}
|
||||
aria-label="Previous page"
|
||||
type="button"
|
||||
>
|
||||
← Newer
|
||||
</button>
|
||||
|
||||
<span className="pn-page-info" aria-current="page">
|
||||
Page {page} of {totalPages}
|
||||
</span>
|
||||
|
||||
<button
|
||||
className="pn-page-btn"
|
||||
onClick={() => onPageChange(page + 1)}
|
||||
disabled={page >= totalPages}
|
||||
aria-label="Next page"
|
||||
type="button"
|
||||
>
|
||||
Older →
|
||||
</button>
|
||||
</nav>
|
||||
);
|
||||
});
|
||||
|
||||
/* ── Main Feed Component ────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* PeptideNewsFeed — root component.
|
||||
*
|
||||
* Reads configuration from window.peptideNewsFeed which is
|
||||
* localized by the PHP shortcode renderer.
|
||||
*/
|
||||
function PeptideNewsFeed() {
|
||||
const config = window.peptideNewsFeed || {};
|
||||
const restUrl = config.restUrl || '/wp-json/peptide-news/v1/';
|
||||
const perPage = config.count || ARTICLES_PER_PAGE;
|
||||
|
||||
const [articles, setArticles] = useState([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const feedRef = useRef(null);
|
||||
|
||||
const loadArticles = useCallback(
|
||||
async (pageNum, signal) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await fetchArticles(restUrl, pageNum, perPage, signal);
|
||||
setArticles(data.articles || []);
|
||||
setTotalPages(data.total_pages || 1);
|
||||
} catch (err) {
|
||||
if (err.name !== 'AbortError') {
|
||||
setError(err.message || 'Something went wrong.');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[restUrl, perPage]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
loadArticles(page, controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [page, loadArticles]);
|
||||
|
||||
const handlePageChange = useCallback((newPage) => {
|
||||
setPage(newPage);
|
||||
// Scroll feed container into view on pagination.
|
||||
if (feedRef.current) {
|
||||
feedRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRetry = useCallback(() => {
|
||||
loadArticles(page);
|
||||
}, [page, loadArticles]);
|
||||
|
||||
return (
|
||||
<div className="pn-news-feed" ref={feedRef}>
|
||||
{loading && <LoadingSkeleton count={Math.min(perPage, 5)} />}
|
||||
|
||||
{!loading && error && (
|
||||
<ErrorMessage message={error} onRetry={handleRetry} />
|
||||
)}
|
||||
|
||||
{!loading && !error && articles.length === 0 && <EmptyState />}
|
||||
|
||||
{!loading && !error && articles.length > 0 && (
|
||||
<>
|
||||
<div className="pn-articles-list" role="feed" aria-label="Peptide news articles">
|
||||
{articles.map((article) => (
|
||||
<ArticleCard key={article.id} article={article} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Pagination
|
||||
page={page}
|
||||
totalPages={totalPages}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Mount ──────────────────────────────────────────────────────────── */
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const containers = document.querySelectorAll('[data-peptide-news-feed]');
|
||||
containers.forEach(function (el) {
|
||||
const root = ReactDOM.createRoot(el);
|
||||
root.render(React.createElement(PeptideNewsFeed));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user