/** * AKSRT Follow — 前台关注交互 * * 监听 [data-aksrt-follow] 按钮点击,切换关注状态。 * * @package AKSRT */ (function () { 'use strict'; var API_ROOT = (function () { var d = window.aksrtData || {}; var raw = d.apiUrl || d.restUrl || d.rest_url || '/index.php?rest_route=/aksrt/v1'; return String(raw).replace(/\/$/, ''); })(); var NONCE = (window.aksrtData && window.aksrtData.restNonce) || ''; // 初始关注状态由服务端渲染(is-following class + 文案),无需逐按钮查询。 function initFollowButtons() { document.addEventListener('click', function (e) { var btn = e.target.closest('[data-aksrt-follow]'); if (!btn) return; e.preventDefault(); var targetUserId = parseInt(btn.getAttribute('data-aksrt-follow')); if (!targetUserId) return; btn.disabled = true; fetch(API_ROOT + '/follow/toggle', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': NONCE, }, body: JSON.stringify({ target_user_id: targetUserId }), }) .then(function (res) { return res.json(); }) .then(function (result) { if (result.success && result.data) { var isFollowing = result.data.is_following; updateFollowButton(btn, isFollowing, result.data.follower_count); notyf(isFollowing ? '关注成功' : '已取消关注', 'success'); } else { notyf(result.message || '操作失败', 'danger'); } }) .catch(function () { notyf('网络错误,请重试', 'danger'); }) .finally(function () { btn.disabled = false; }); }); } function updateFollowButton(btn, isFollowing, count) { var icon = btn.querySelector('i'); var text = btn.querySelector('span'); function setLabel(label) { if (text) { text.textContent = label; return; } // Fallback when markup has bare text nodes next to the icon. var nodes = Array.prototype.slice.call(btn.childNodes); var textNode = nodes.filter(function (n) { return n.nodeType === 3 && n.textContent.trim() !== ''; })[0]; if (textNode) { textNode.textContent = ' ' + label + ' '; } } if (isFollowing) { btn.classList.add('is-following'); if (icon) icon.className = 'fa fas fa-heart'; setLabel('已关注'); btn.title = '点击取消关注'; } else { btn.classList.remove('is-following'); if (icon) icon.className = 'fa fas fa-heart'; setLabel('关注'); btn.title = '关注该用户'; } if (!isFollowing && btn.closest('.uc-follow-management__item')) { btn.closest('.uc-follow-management__item').remove(); } // Update follower count display if exists var countEl = document.querySelector('.aksrt-user-home__stat-value[data-followers]'); if (countEl && count !== undefined) { countEl.textContent = count; } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initFollowButtons); } else { initFollowButtons(); } })();