feat(widgets): multi-tab posts lazy REST load

SSR first tab; other tabs fetch /widgets/tab-posts on switch
via widget-set.js (zibll tab_post depth).
This commit is contained in:
kate522 committed 2026-07-20 20:50:57 +08:00
1 parent 46c5fec180
commit c52651f647
2 files changed
+137 -131

No files matched your search

+34
View File
@@ -17,6 +17,39 @@
var tabs = widget.querySelectorAll('.widget-tab-posts__tab'); var tabs = widget.querySelectorAll('.widget-tab-posts__tab');
var panels = widget.querySelectorAll('.widget-tab-posts__panel'); var panels = widget.querySelectorAll('.widget-tab-posts__panel');
if (!tabs.length || !panels.length) return; if (!tabs.length || !panels.length) return;
var rest = widget.getAttribute('data-rest') || '';
var defaultCount = widget.getAttribute('data-count') || '5';
function loadPanel(panel, tab) {
if (!panel || panel.getAttribute('data-loaded') === '1' || !rest) return;
var orderby = tab.getAttribute('data-orderby') || 'date';
var cat = tab.getAttribute('data-cat') || '0';
var tabCount = tab.getAttribute('data-tab-count') || '0';
var qs = new URLSearchParams({
count: defaultCount,
orderby: orderby,
cat: cat,
tab_count: tabCount,
});
var url = rest + (rest.indexOf('?') > -1 ? '&' : '?') + qs.toString();
panel.classList.add('is-ajax-loading');
var headers = { Accept: 'application/json' };
if (window.aksrtData && aksrtData.restNonce) {
headers['X-WP-Nonce'] = aksrtData.restNonce;
}
fetch(url, { credentials: 'same-origin', headers: headers })
.then(function (r) { return r.json(); })
.then(function (j) {
var d = (j && j.data) || j || {};
var html = d.html || '';
panel.innerHTML = html || '<p class="widget-empty">暂无文章</p>';
panel.setAttribute('data-loaded', '1');
panel.classList.remove('is-ajax-loading');
})
.catch(function () {
panel.classList.remove('is-ajax-loading');
});
}
tabs.forEach(function (tab) { tabs.forEach(function (tab) {
tab.addEventListener('click', function () { tab.addEventListener('click', function () {
@@ -33,6 +66,7 @@
panel.classList.toggle('active', active); panel.classList.toggle('active', active);
if (active) { if (active) {
panel.removeAttribute('hidden'); panel.removeAttribute('hidden');
loadPanel(panel, tab);
} else { } else {
panel.setAttribute('hidden', ''); panel.setAttribute('hidden', '');
} }
+103 -131
View File
@@ -1,5 +1,7 @@
<?php <?php
/** /**
* Multi-tab posts (zibll zib_widget_ui_tab_post + lazy REST).
*
* @package AKSRT * @package AKSRT
*/ */
@@ -14,20 +16,17 @@ class TabPostsWidget extends \WP_Widget {
'aksrt_tab_posts', 'aksrt_tab_posts',
esc_html__('AKSRT 多栏目文章', 'aksrt'), esc_html__('AKSRT 多栏目文章', 'aksrt'),
[ [
'description' => esc_html__('Tab 切换显示不同分类的文章列表', 'aksrt'), 'description' => esc_html__('Tab 切换显示不同分类/排序的文章(懒加载)。', 'aksrt'),
'customize_selective_refresh' => true, 'customize_selective_refresh' => true,
] ]
); );
} }
/** /**
* Normalize tabs from legacy comma-separated string or structured array. * @param mixed $tabs
* * @return list<array{title:string,category_id:int,orderby:string,count:int,enabled:bool}>
* @param mixed $tabs Raw tabs data.
* @return array Normalized structured tabs.
*/ */
private function normalize_tabs($tabs): array { public static function normalize_tabs_static($tabs): array {
// Legacy comma-separated format
if (is_string($tabs) && $tabs !== '') { if (is_string($tabs) && $tabs !== '') {
$legacy_keys = array_map('trim', explode(',', $tabs)); $legacy_keys = array_map('trim', explode(',', $tabs));
$legacy_defs = [ $legacy_defs = [
@@ -59,17 +58,19 @@ class TabPostsWidget extends \WP_Widget {
} }
return $result; return $result;
} }
// Structured array format
if (is_array($tabs)) { if (is_array($tabs)) {
$allowed_orderby = ['date', 'modified', 'views', 'likes', 'comments', 'favorites', 'downloads', 'rand']; $allowed = ['date', 'modified', 'views', 'likes', 'comments', 'favorites', 'downloads', 'rand'];
$result = []; $result = [];
foreach ($tabs as $tab) { foreach ($tabs as $tab) {
if (!is_array($tab)) continue; if (!is_array($tab)) {
continue;
}
$orderby = sanitize_key($tab['orderby'] ?? 'date'); $orderby = sanitize_key($tab['orderby'] ?? 'date');
if (!in_array($orderby, $allowed_orderby, true)) $orderby = 'date'; if (!in_array($orderby, $allowed, true)) {
$orderby = 'date';
}
$result[] = [ $result[] = [
'title' => sanitize_text_field($tab['title'] ?? ''), 'title' => sanitize_text_field((string) ($tab['title'] ?? '')),
'category_id' => absint($tab['category_id'] ?? 0), 'category_id' => absint($tab['category_id'] ?? 0),
'orderby' => $orderby, 'orderby' => $orderby,
'count' => max(0, min(20, (int) ($tab['count'] ?? 0))), 'count' => max(0, min(20, (int) ($tab['count'] ?? 0))),
@@ -78,144 +79,120 @@ class TabPostsWidget extends \WP_Widget {
} }
return $result; return $result;
} }
return []; return [];
} }
private function normalize_tabs($tabs): array {
return self::normalize_tabs_static($tabs);
}
/** /**
* Build \WP_Query args for a tab's orderby. * Build query for a tab → reuse main posts payload renderer.
*
* @param array $tab
* @param int $default_count
* @return array
*/ */
private function build_tab_query_args(array $tab, int $default_count): array { public static function tab_to_main_instance(array $tab, int $default_count): array {
$count = $tab['count'] > 0 ? $tab['count'] : $default_count; $count = !empty($tab['count']) ? (int) $tab['count'] : $default_count;
$args = [ return [
'post_type' => 'post', 'count' => max(1, min(30, $count)),
'post_status' => 'publish', 'orderby' => sanitize_key((string) ($tab['orderby'] ?? 'date')),
'posts_per_page' => $count, 'cat' => absint($tab['category_id'] ?? 0),
'ignore_sticky_posts' => true, 'style' => 'mini',
'no_found_rows' => true, 'show_thumb' => 1,
'show_meta' => 1,
'show_number'=> 0,
'paginate' => 'none',
]; ];
if ($tab['category_id'] > 0) {
$args['cat'] = $tab['category_id'];
} }
switch ($tab['orderby']) { /**
case 'views': * REST helper: render one tab list HTML.
$args['meta_key'] = 'aksrt_post_views'; */
$args['orderby'] = 'meta_value_num'; public static function render_tab_html(array $tab, int $default_count): string {
$args['order'] = 'DESC'; $inst = self::tab_to_main_instance($tab, $default_count);
break; if (class_exists('\AKSRT\Widgets\WidgetMainPosts')) {
case 'likes': $payload = WidgetMainPosts::query_payload($inst, 1);
$args['meta_key'] = '_aksrt_like_count'; return (string) ($payload['html'] ?? '');
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
break;
case 'favorites':
$args['meta_key'] = '_aksrt_favorite_count';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
break;
case 'downloads':
$args['meta_key'] = '_aksrt_res_download_count';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
break;
case 'comments':
$args['orderby'] = 'comment_count';
$args['order'] = 'DESC';
break;
case 'rand':
$args['orderby'] = 'rand';
break;
case 'modified':
$args['orderby'] = 'modified';
$args['order'] = 'DESC';
break;
case 'date':
default:
$args['orderby'] = 'date';
$args['order'] = 'DESC';
break;
} }
return '';
return $args;
} }
public function widget($args, $instance): void { public function widget($args, $instance): void {
echo $args['before_widget']; echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
$title = apply_filters('widget_title', $instance['title'] ?? '', $instance, $this->id_base); $title = apply_filters('widget_title', (string) ($instance['title'] ?? ''), $instance, $this->id_base);
$count = absint($instance['count'] ?? 5); $count = absint($instance['count'] ?? 5);
$tabs = $this->normalize_tabs($instance['tabs'] ?? 'latest,comments,random'); $tabs = $this->normalize_tabs($instance['tabs'] ?? 'latest,comments,random');
$tabs = array_values(array_filter($tabs, static fn($t) => !empty($t['enabled'])));
// Filter enabled tabs if (!$tabs) {
$tabs = array_filter($tabs, fn($t) => !empty($t['enabled'])); echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
if (empty($tabs)) {
echo $args['after_widget'];
return; return;
} }
if ($title) { if ($title !== '') {
echo $args['before_title'] . esc_html($title) . $args['after_title']; echo $args['before_title'] . esc_html($title) . $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
} }
$widget_id = $this->id; $widget_id = $this->id;
$rest = rest_url('aksrt/v1/widgets/tab-posts');
$use_shared = function_exists('aksrt_render_mini_list'); $use_shared = function_exists('aksrt_render_mini_list');
?> ?>
<div class="widget-tab-posts" id="<?php echo esc_attr($widget_id); ?>-tabs"> <div class="widget-tab-posts" id="<?php echo esc_attr($widget_id); ?>-tabs"
<!-- Tab 导航 --> data-aksrt-tab-posts
data-rest="<?php echo esc_url($rest); ?>"
data-count="<?php echo esc_attr((string) $count); ?>">
<ul class="widget-tab-posts__nav" role="tablist"> <ul class="widget-tab-posts__nav" role="tablist">
<?php $first = true; foreach ($tabs as $i => $tab) : <?php $first = true; foreach ($tabs as $i => $tab) :
$tab_key = 'tab-' . $i; $tab_key = 'tab-' . $i;
$tab_title = $tab['title'] !== '' ? $tab['title'] : __('Tab ' . ($i + 1), 'aksrt'); $tab_title = $tab['title'] !== '' ? $tab['title'] : sprintf(__('Tab %d', 'aksrt'), $i + 1);
?> ?>
<li role="presentation"> <li role="presentation">
<button type="button" role="tab" <button type="button" role="tab"
class="widget-tab-posts__tab<?php echo $first ? ' active' : ''; ?>" class="widget-tab-posts__tab<?php echo $first ? ' active' : ''; ?>"
data-tab="<?php echo esc_attr($tab_key); ?>" data-tab="<?php echo esc_attr($tab_key); ?>"
data-index="<?php echo (int) $i; ?>"
data-orderby="<?php echo esc_attr($tab['orderby']); ?>"
data-cat="<?php echo (int) $tab['category_id']; ?>"
data-tab-count="<?php echo (int) $tab['count']; ?>"
aria-selected="<?php echo $first ? 'true' : 'false'; ?>" aria-selected="<?php echo $first ? 'true' : 'false'; ?>"
><?php echo esc_html($tab_title); ?></button> ><?php echo esc_html($tab_title); ?></button>
</li> </li>
<?php $first = false; endforeach; ?> <?php $first = false; endforeach; ?>
</ul> </ul>
<!-- Tab 内容 -->
<?php $first = true; foreach ($tabs as $i => $tab) : <?php $first = true; foreach ($tabs as $i => $tab) :
$tab_key = 'tab-' . $i; $tab_key = 'tab-' . $i;
$q = new \WP_Query($this->build_tab_query_args($tab, $count));
?> ?>
<div class="widget-tab-posts__panel<?php echo $first ? ' active' : ''; ?>" data-tab-panel="<?php echo esc_attr($tab_key); ?>" role="tabpanel"<?php echo $first ? '' : ' hidden'; ?>> <div class="widget-tab-posts__panel<?php echo $first ? ' active' : ''; ?>"
<?php if ($q->have_posts()) : ?> data-tab-panel="<?php echo esc_attr($tab_key); ?>"
<?php if ($use_shared) : ?> data-loaded="<?php echo $first ? '1' : '0'; ?>"
<div class="widget-tab-posts__list widget-tab-posts__list--mini"> role="tabpanel"<?php echo $first ? '' : ' hidden'; ?>>
<?php aksrt_render_mini_list($q, ['context' => 'sidebar', 'show_thumb' => true, 'show_meta' => true], true); ?> <?php if ($first) :
</div> $html = self::render_tab_html($tab, $count);
<?php else : ?> if ($html !== '') {
<ul class="widget-tab-posts__list"> echo '<div class="widget-tab-posts__list widget-tab-posts__list--mini aksrt-main-posts style-mini">' . $html . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
<?php while ($q->have_posts()) : $q->the_post(); ?> } else {
<li class="widget-tab-posts__item"> // Fallback to old mini list path.
<?php if (has_post_thumbnail()) : ?> $q = new \WP_Query(WidgetMainPosts::build_query_args(self::tab_to_main_instance($tab, $count), 1));
<a href="<?php the_permalink(); ?>" class="widget-tab-posts__thumb"> if ($q->have_posts() && $use_shared) {
<?php the_post_thumbnail('thumbnail', ['loading' => function_exists('aksrt_is_lazyload_enabled') && aksrt_is_lazyload_enabled('widget') ? 'lazy' : false, 'class' => 'fit-cover']); ?> echo '<div class="widget-tab-posts__list widget-tab-posts__list--mini">';
</a> aksrt_render_mini_list($q, ['context' => 'sidebar', 'show_thumb' => true, 'show_meta' => true], true);
<?php endif; ?> echo '</div>';
<div class="widget-tab-posts__info"> } else {
<a href="<?php the_permalink(); ?>" class="widget-tab-posts__title"><?php the_title(); ?></a> echo function_exists('aksrt_get_widget_null') ? aksrt_get_widget_null(__('暂无文章', 'aksrt')) : '<p class="widget-empty">' . esc_html__('暂无文章', 'aksrt') . '</p>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
<span class="widget-tab-posts__meta"><?php echo esc_html(human_time_diff(get_the_time('U'), current_time('timestamp')) . __('前', 'aksrt')); ?></span> }
</div> wp_reset_postdata();
</li> }
<?php endwhile; ?> else : ?>
</ul> <div class="post_ajax_loader" data-aksrt-ajax-loader></div>
<?php endif; ?>
<?php else : ?>
<?php echo function_exists('aksrt_get_widget_null') ? aksrt_get_widget_null(__('暂无文章', 'aksrt')) : '<p class="widget-empty">' . esc_html__('暂无文章', 'aksrt') . '</p>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php wp_reset_postdata(); $first = false; endforeach; ?> <?php $first = false; endforeach; ?>
</div> </div>
<?php <?php
echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo $args['after_widget'];
} }
public function form($instance): void { public function form($instance): void {
@@ -234,20 +211,18 @@ class TabPostsWidget extends \WP_Widget {
]; ];
?> ?>
<p> <p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('标题(可选):', 'aksrt'); ?></label> <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('标题(可选):', 'aksrt'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>"> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr((string) $title); ?>">
</p> </p>
<p> <p>
<label for="<?php echo $this->get_field_id('count'); ?>"><?php esc_html_e('默认每个 Tab 显示数量:', 'aksrt'); ?></label> <label for="<?php echo esc_attr($this->get_field_id('count')); ?>"><?php esc_html_e('默认每个 Tab 显示数量:', 'aksrt'); ?></label>
<input class="tiny-text" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" type="number" min="1" max="20" value="<?php echo $count; ?>"> <input class="tiny-text" id="<?php echo esc_attr($this->get_field_id('count')); ?>" name="<?php echo esc_attr($this->get_field_name('count')); ?>" type="number" min="1" max="20" value="<?php echo (int) $count; ?>">
</p> </p>
<hr style="margin:12px 0;"> <hr style="margin:12px 0;">
<p style="font-weight:600;margin-bottom:8px;"><?php esc_html_e('Tab 配置', 'aksrt'); ?></p> <p style="font-weight:600;margin-bottom:8px;"><?php esc_html_e('Tab 配置', 'aksrt'); ?></p>
<?php <?php
// Render each tab as a mini-form
$max_tabs = 8; $max_tabs = 8;
$tabs = array_slice($tabs, 0, $max_tabs); $tabs = array_slice($tabs, 0, $max_tabs);
// Ensure at least 3 slots
while (count($tabs) < 3) { while (count($tabs) < 3) {
$tabs[] = ['title' => '', 'category_id' => 0, 'orderby' => 'date', 'count' => 0, 'enabled' => false]; $tabs[] = ['title' => '', 'category_id' => 0, 'orderby' => 'date', 'count' => 0, 'enabled' => false];
} }
@@ -255,19 +230,19 @@ class TabPostsWidget extends \WP_Widget {
?> ?>
<div style="border:1px solid #ddd;padding:8px;margin-bottom:8px;border-radius:4px;background:#fafafa;"> <div style="border:1px solid #ddd;padding:8px;margin-bottom:8px;border-radius:4px;background:#fafafa;">
<p style="margin:0 0 6px;"> <p style="margin:0 0 6px;">
<label><input type="checkbox" name="<?php echo $this->get_field_name("tabs[{$i}][enabled]"); ?>" value="1" <?php checked(!empty($tab['enabled'])); ?>> <?php printf(esc_html__('Tab %d 启用', 'aksrt'), $i + 1); ?></label> <label><input type="checkbox" name="<?php echo esc_attr($this->get_field_name("tabs[{$i}][enabled]")); ?>" value="1" <?php checked(!empty($tab['enabled'])); ?>> <?php printf(esc_html__('Tab %d 启用', 'aksrt'), $i + 1); ?></label>
</p> </p>
<p style="margin:0 0 6px;"> <p style="margin:0 0 6px;">
<label><?php esc_html_e('标题:', 'aksrt'); ?></label> <label><?php esc_html_e('标题:', 'aksrt'); ?></label>
<input class="widefat" type="text" name="<?php echo $this->get_field_name("tabs[{$i}][title]"); ?>" value="<?php echo esc_attr($tab['title']); ?>" placeholder="<?php esc_attr_e('留空则使用分类名', 'aksrt'); ?>"> <input class="widefat" type="text" name="<?php echo esc_attr($this->get_field_name("tabs[{$i}][title]")); ?>" value="<?php echo esc_attr($tab['title']); ?>" placeholder="<?php esc_attr_e('留空则使用分类名', 'aksrt'); ?>">
</p> </p>
<p style="margin:0 0 6px;"> <p style="margin:0 0 6px;">
<label><?php esc_html_e('分类 ID:', 'aksrt'); ?></label> <label><?php esc_html_e('分类 ID:', 'aksrt'); ?></label>
<input class="tiny-text" type="number" min="0" name="<?php echo $this->get_field_name("tabs[{$i}][category_id]"); ?>" value="<?php echo (int) $tab['category_id']; ?>" placeholder="0"> <input class="tiny-text" type="number" min="0" name="<?php echo esc_attr($this->get_field_name("tabs[{$i}][category_id]")); ?>" value="<?php echo (int) $tab['category_id']; ?>" placeholder="0">
</p> </p>
<p style="margin:0 0 6px;"> <p style="margin:0 0 6px;">
<label><?php esc_html_e('排序:', 'aksrt'); ?></label> <label><?php esc_html_e('排序:', 'aksrt'); ?></label>
<select class="widefat" name="<?php echo $this->get_field_name("tabs[{$i}][orderby]"); ?>"> <select class="widefat" name="<?php echo esc_attr($this->get_field_name("tabs[{$i}][orderby]")); ?>">
<?php foreach ($orderby_options as $val => $label) : ?> <?php foreach ($orderby_options as $val => $label) : ?>
<option value="<?php echo esc_attr($val); ?>" <?php selected($tab['orderby'], $val); ?>><?php echo esc_html($label); ?></option> <option value="<?php echo esc_attr($val); ?>" <?php selected($tab['orderby'], $val); ?>><?php echo esc_html($label); ?></option>
<?php endforeach; ?> <?php endforeach; ?>
@@ -275,32 +250,30 @@ class TabPostsWidget extends \WP_Widget {
</p> </p>
<p style="margin:0;"> <p style="margin:0;">
<label><?php esc_html_e('数量(0=使用默认):', 'aksrt'); ?></label> <label><?php esc_html_e('数量(0=使用默认):', 'aksrt'); ?></label>
<input class="tiny-text" type="number" min="0" max="20" name="<?php echo $this->get_field_name("tabs[{$i}][count]"); ?>" value="<?php echo (int) $tab['count']; ?>"> <input class="tiny-text" type="number" min="0" max="20" name="<?php echo esc_attr($this->get_field_name("tabs[{$i}][count]")); ?>" value="<?php echo (int) $tab['count']; ?>">
</p> </p>
</div> </div>
<?php endforeach; <?php endforeach;
// Render hidden fields for any remaining tabs to preserve data
for ($i = count($tabs); $i < $max_tabs; $i++) :
?>
<input type="hidden" name="<?php echo $this->get_field_name("tabs[{$i}][enabled]"); ?>" value="">
<?php endfor;
} }
public function update($new_instance, $old_instance): array { public function update($new_instance, $old_instance): array {
$result = [ $result = [
'title' => sanitize_text_field($new_instance['title'] ?? ''), 'title' => sanitize_text_field((string) ($new_instance['title'] ?? '')),
'count' => max(1, min(20, (int) ($new_instance['count'] ?? 5))), 'count' => max(1, min(20, (int) ($new_instance['count'] ?? 5))),
]; ];
$tabs = []; $tabs = [];
if (isset($new_instance['tabs']) && is_array($new_instance['tabs'])) { if (isset($new_instance['tabs']) && is_array($new_instance['tabs'])) {
$allowed_orderby = ['date', 'modified', 'views', 'likes', 'comments', 'favorites', 'downloads', 'rand']; $allowed = ['date', 'modified', 'views', 'likes', 'comments', 'favorites', 'downloads', 'rand'];
foreach ($new_instance['tabs'] as $tab) { foreach ($new_instance['tabs'] as $tab) {
if (!is_array($tab)) continue; if (!is_array($tab)) {
continue;
}
$orderby = sanitize_key($tab['orderby'] ?? 'date'); $orderby = sanitize_key($tab['orderby'] ?? 'date');
if (!in_array($orderby, $allowed_orderby, true)) $orderby = 'date'; if (!in_array($orderby, $allowed, true)) {
$orderby = 'date';
}
$tabs[] = [ $tabs[] = [
'title' => sanitize_text_field($tab['title'] ?? ''), 'title' => sanitize_text_field((string) ($tab['title'] ?? '')),
'category_id' => absint($tab['category_id'] ?? 0), 'category_id' => absint($tab['category_id'] ?? 0),
'orderby' => $orderby, 'orderby' => $orderby,
'count' => max(0, min(20, (int) ($tab['count'] ?? 0))), 'count' => max(0, min(20, (int) ($tab['count'] ?? 0))),
@@ -308,8 +281,7 @@ class TabPostsWidget extends \WP_Widget {
]; ];
} }
} }
$result['tabs'] = !empty($tabs) ? $tabs : 'latest,comments,random';
$result['tabs'] = !empty($tabs) ? $tabs : sanitize_text_field($new_instance['tabs'] ?? 'latest,comments,random');
return $result; return $result;
} }
} }