Deploy 1ae831e from main
This commit is contained in:
@@ -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