Evan.tld
Evan Lv2 OP
Domain portfolio · mi.cd
· 48 views#0

image

It's actually not very useful, I just made it display on the homepage. If you're interested, feel free to take it.

code
// ==UserScript==
// @name         NHT Homepage Online Users
// @namespace    https://n.ht/
// @version      1.0.0
// @description  Display avatars of online users among current homepage users at the bottom of the right sidebar on the n.ht homepage.
// @author       Evan
// @match        https://n.ht/
// @match        https://n.ht/?*
// @match        http://n.ht/
// @match        http://n.ht/?*
// @run-at       document-idle
// @grant        none
// @noframes
// ==/UserScript==

(() => {
  'use strict';

  if (location.pathname !== '/' || (location.search && !/^\?page=\d+$/.test(location.search))) return;

  const PANEL_ID = 'nht-online-users-panel';
  const REFRESH_MS = 60 * 1000;
  const REQUEST_TIMEOUT_MS = 10 * 1000;
  let refreshTimer = 0;
  let refreshSequence = 0;
  let refreshDebounce = 0;

  injectStyle();
  ensurePanel();
  refreshOnlineUsers();
  refreshTimer = window.setInterval(refreshOnlineUsers, REFRESH_MS);

  const observer = new MutationObserver(records => {
    if (records.length && records.every(record => {
      const target = record.target instanceof Element ? record.target : null;
      return target?.closest(`#${PANEL_ID}`) || target?.id === PANEL_ID;
    })) return;
    window.clearTimeout(refreshDebounce);
    refreshDebounce = window.setTimeout(() => {
      ensurePanel();
      refreshOnlineUsers();
    }, 500);
  });
  const topicRoot = document.querySelector('#topic-list-placeholder') || document.body;
  observer.observe(topicRoot, { childList: true, subtree: true });

  function injectStyle() {
    const style = document.createElement('style');
    style.id = `${PANEL_ID}-style`;
    style.textContent = `
      #${PANEL_ID}{margin-top:12px;overflow:hidden}
      #${PANEL_ID} .nht-online-cell{padding:12px 14px}
      #${PANEL_ID} .nht-online-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px}
      #${PANEL_ID} .nht-online-title{margin:0;color:#30343b;font-size:14px;font-weight:600;line-height:1.4}
      #${PANEL_ID} .nht-online-count{color:#7b858e;font-size:11px;font-weight:400}
      #${PANEL_ID} .nht-online-list{display:flex;flex-wrap:wrap;align-items:center;gap:9px;min-height:34px}
      #${PANEL_ID} .nht-online-user{position:relative;display:block;width:32px;height:32px;flex:0 0 32px;border-radius:50%;text-decoration:none}
      #${PANEL_ID} .nht-online-avatar{display:block;width:32px;height:32px;border:1px solid #e1e5e8;border-radius:50%;background:#f3f5f6;object-fit:cover}
      #${PANEL_ID} .nht-online-dot{position:absolute;right:-1px;bottom:-1px;width:9px;height:9px;border:2px solid #fff;border-radius:50%;background:#35a269}
      #${PANEL_ID} .nht-online-empty{color:#9aa2a9;font-size:12px}
      html.dark #${PANEL_ID} .nht-online-title{color:#f4f4f5}
      html.dark #${PANEL_ID} .nht-online-avatar{border-color:#454b52;background:#272b30}
      html.dark #${PANEL_ID} .nht-online-dot{border-color:#18181b}
    `;
    (document.head || document.documentElement).append(style);
  }

  function ensurePanel() {
    const rightbar = document.querySelector('#Rightbar');
    if (!rightbar) return null;
    let panel = document.getElementById(PANEL_ID);
    if (!panel) {
      panel = document.createElement('section');
      panel.id = PANEL_ID;
      panel.className = 'box sidebar-panel-card sidebar-online-users-card';
      panel.setAttribute('aria-label', 'Online Users');
      panel.innerHTML = `
        <div class="cell nht-online-cell">
          <div class="nht-online-head">
            <h3 class="nht-online-title">Online Users</h3>
            <span class="nht-online-count" aria-live="polite"></span>
          </div>
          <div class="nht-online-list" aria-live="polite">
            <span class="nht-online-empty">Loading…</span>
          </div>
        </div>`;
    }
    if (panel.parentElement !== rightbar || rightbar.lastElementChild !== panel) rightbar.append(panel);
    return panel;
  }

  function collectUsernames() {
    const names = new Map();
    for (const img of document.querySelectorAll('.topic-avatar img[alt], .floor-avatar img[alt]')) {
      const username = String(img.getAttribute('alt') || '').trim();
      if (username) names.set(username.toLowerCase(), username);
    }
    return [...names.values()];
  }

  async function refreshOnlineUsers() {
    const panel = ensurePanel();
    if (!panel) return;
    const sequence = ++refreshSequence;
    const usernames = collectUsernames();
    if (!usernames.length) {
      renderUsers(panel, [], sequence);
      return;
    }

    const results = await Promise.all(usernames.map(username => readProfile(username)));
    if (sequence !== refreshSequence) return;
    const online = results
      .filter(profile => profile && profile.online === true)
      .sort((a, b) => a.username.localeCompare(b.username, 'zh-CN'));
    renderUsers(panel, online, sequence);
  }

  async function readProfile(username) {
    const controller = new AbortController();
    const timeout = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
    try {
      const url = new URL(`/u/${encodeURIComponent(username)}`, location.origin);
      url.searchParams.set('nht_online_check', String(Date.now()));
      const response = await fetch(url.href, {
        credentials: 'same-origin',
        cache: 'no-store',
        headers: { Accept: 'text/html' },
        signal: controller.signal,
      });
      if (!response.ok) return null;
      const html = await response.text();
      const doc = new DOMParser().parseFromString(html, 'text/html');
      const script = [...doc.querySelectorAll('script')].find(node =>
        /^\s*window\.__NHT_SSR__\s*=/.test(node.textContent || '')
      );
      if (!script) return null;
      const source = script.textContent || '';
      const state = JSON.parse(source.slice(source.indexOf('=') + 1).replace(/;\s*$/, '').trim());
      const user = state?.profileData?.user;
      if (!user || String(user.username || '').toLowerCase() !== username.toLowerCase()) return null;
      return {
        username: String(user.username),
        online: user.online === true,
        avatarUrl: String(user.avatar_url || `https://avatar.n.ht/${encodeURIComponent(user.username)}?av=5`),
      };
    } catch {
      return null;
    } finally {
      window.clearTimeout(timeout);
    }
  }

  function renderUsers(panel, users, sequence) {
    if (!panel || sequence !== refreshSequence) return;
    const list = panel.querySelector('.nht-online-list');
    const count = panel.querySelector('.nht-online-count');
    if (!list || !count) return;
    list.replaceChildren();
    count.textContent = `${users.length} users`;
    if (!users.length) {
      list.append(makeNode('span', 'nht-online-empty', 'No online users'));
      return;
    }
    for (const user of users) {
      const link = document.createElement('a');
      link.className = 'nht-online-user';
      link.href = `/u/${encodeURIComponent(user.username)}`;
      link.title = `${user.username} online`;
      link.setAttribute('aria-label', `${user.username} online`);
      const avatar = document.createElement('img');
      avatar.className = 'nht-online-avatar';
      avatar.src = user.avatarUrl;
      avatar.alt = user.username;
      avatar.loading = 'lazy';
      avatar.decoding = 'async';
      link.append(avatar, makeNode('span', 'nht-online-dot', ''));
      list.append(link);
    }
  }

  function makeNode(tag, className, text) {
    const node = document.createElement(tag);
    node.className = className;
    if (text) node.textContent = text;
    return node;
  }
})();

SIGNYee.cx
Login