MediaWiki:Gadget-Statistika.js
Qiyofa
Eʼtibor bering: Oʻzgartirishlaringizni koʻrish uchun, yangi moslamalaringizning saqlashdan keyin, brauzer keshini tozalash kerak:
Mozilla / Firefox: Ctrl+Shift+R, IE: Ctrl+F5, Safari: Cmd+Shift+R, Konqueror: F5, Opera: Tools → Preferences orqali keshni tozalang.
/**
* ==========================================================================
* ZIYOSFERA STATISTIKA — MEDIAWIKI GADGET / EXTENSION SCRIPT
* Manzil: Ziyosfera:Statistika sahifasi uchun maxsus ishlab chiqilgan
* Muallif: Antigravity IDE (Ziyosfera Ensiklopediyasi uchun)
* Xususiyatlar:
* - Ziyosfera:Statistika sahifasiga kirgan foydalanuvchining shaxsiy statistikasini avtomatik ko'rsatish
* - Aniq maqolalar soni (Progressive Background Streaming — no "100+")
* - Interaktiv kunlik maqolalar taqvimi (kalendari) va 1-bosishda saralash
* - "Andoza" terminologiyasi (shablon so'zi chiqarilgan)
* - Diagrammalar (Chart.js), So'nggi tahrirlar va Huquqlar tahlili
* - Ziyosfera rasmiy och (light) mavzusi va brend ranglari
* ==========================================================================
*/
(function(window, $, mw) {
'use strict';
// 1. Sahifani tekshirish (Faqat Ziyosfera:Statistika yoki #ziyo-userstats-root bo'lganda ishlaydi)
const pageName = (mw && mw.config && mw.config.get('wgPageName')) || '';
const isTargetPage = (pageName === 'Ziyosfera:Statistika' || pageName === 'Ziyosfera:Statistika/' || pageName.indexOf('Ziyosfera:Statistika') === 0);
function initWhenReady() {
const rootEl = document.getElementById('ziyo-userstats-root');
if (!isTargetPage && !rootEl) {
return; // Boshqa sahifalarda umuman ishga tushmaydi va xalaqit bermaydi
}
// Tashqi kutubxonalarni xavfsiz yuklash
loadDependencies(function() {
startApp(rootEl);
});
}
// DOM tayyor bo'lishini kutish
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initWhenReady);
} else {
initWhenReady();
}
// ==========================================================================
// DEPENDENCY LOADER (FontAwesome va Chart.js)
// ==========================================================================
function loadDependencies(callback) {
// 1. FontAwesome ikonkalari
if (!document.getElementById('zs-fa-styles')) {
const faLink = document.createElement('link');
faLink.id = 'zs-fa-styles';
faLink.rel = 'stylesheet';
faLink.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css';
document.head.appendChild(faLink);
}
// 2. Google Fonts (JetBrains Mono & Plus Jakarta Sans)
if (!document.getElementById('zs-fonts')) {
const fontLink = document.createElement('link');
fontLink.id = 'zs-fonts';
fontLink.rel = 'stylesheet';
fontLink.href = 'https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap';
document.head.appendChild(fontLink);
}
// 3. Chart.js
if (window.Chart) {
callback();
} else {
const chartScript = document.createElement('script');
chartScript.src = 'https://cdn.jsdelivr.net/npm/chart.js';
chartScript.onload = callback;
chartScript.onerror = callback; // xato bo'lsa ham asosiy qism ishlashi uchun
document.head.appendChild(chartScript);
}
}
// ==========================================================================
// ASOSIY DASTUR MANTIQI
// ==========================================================================
function startApp(targetRoot) {
// API endpoint — MediaWiki ichida nisbiy yo'l avtomatik ishlaydi
const API_ENDPOINT = (mw && mw.util && mw.util.wikiScript('api')) || '/api.php';
const ARTICLE_VIEW_BASE = (mw && mw.config && mw.config.get('wgArticlePath'))
? mw.config.get('wgArticlePath').replace('$1', '')
: '/ziyo/';
// MediaWiki Namespace xaritasi (10: Andoza)
const NAMESPACE_MAP = {
0: 'Asosiy (Maqola)',
1: 'Munozara',
2: 'Foydalanuvchi',
3: 'Foydalanuvchi munozarasi',
4: 'Loyiha',
5: 'Loyiha munozarasi',
6: 'Fayl',
7: 'Fayl munozarasi',
8: 'MediaWiki',
9: 'MediaWiki munozarasi',
10: 'Andoza',
11: 'Andoza munozarasi',
12: 'Yordam',
13: 'Yordam munozarasi',
14: 'Turkum',
15: 'Turkum munozarasi',
828: 'Modul',
829: 'Modul munozarasi'
};
const MONTH_NAMES_UZ = [
'Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'Iyun',
'Iyul', 'Avgust', 'Sentabr', 'Oktabr', 'Noyabr', 'Dekabr'
];
const GROUP_DEFINITIONS = {
'sysop': { name: 'Administrator', desc: 'Sahifalarni o\'chirish, himoyalash va bloklash vakolati', icon: 'fa-shield-halved', class: 'sysop' },
'bureaucrat': { name: 'Byurokrat', desc: 'Boshqaruv huquqlarini taqsimlash va nomlarni o\'zgartirish', icon: 'fa-crown', class: 'bureaucrat' },
'interface-admin': { name: 'Interfeys administratori', desc: 'Sayt CSS, JavaScript va tizim xabarlarini boshqarish', icon: 'fa-code', class: 'interface-admin' },
'oromgoh': { name: 'Wiki-oromgoh a\'zosi', desc: 'Ziyosfera ma\'rifiy oromgohi ishtirokchisi', icon: 'fa-campground', class: 'oromgoh' },
'admin-panel': { name: 'Admin panel a\'zosi', desc: 'Ziyosfera maxsus boshqaruv vakolati', icon: 'fa-sliders', class: 'sysop' },
'aihelper': { name: 'AI Yordamchi / Bot', desc: 'Sun\'iy intellekt xizmati', icon: 'fa-robot', class: 'bot' },
'suppress': { name: 'Nazoratchi (Oversight)', desc: 'Maxfiy ma\'lumotlarni yashirish huquqi', icon: 'fa-eye-slash', class: 'bureaucrat' },
'bot': { name: 'Bot dastur', desc: 'Avtomatlashtirilgan ommaviy tahrir tizimi', icon: 'fa-robot', class: 'bot' },
'autoconfirmed': { name: 'Avto-tasdiqlangan', desc: 'Yarim himoyalangan sahifalarni tahrirlash', icon: 'fa-user-check', class: 'autoconfirmed' },
'user': { name: 'Ro\'yxatdan o\'tgan a\'zo', desc: 'Ziyosferaning ro\'yxatdan o\'tgan foydalanuvchisi', icon: 'fa-user', class: 'user' },
'*': { name: 'Barcha tashrif buyuruvchilar', desc: 'Umumiy ochiq huquqlar', icon: 'fa-globe', class: 'user' }
};
// Dastur holati (State)
const state = {
currentUser: null,
createdArticles: [],
filteredArticles: [],
recentEdits: [],
articlesByDate: {},
daysWithArticles: [],
isStreamingArticles: false,
shouldStopStreaming: false,
activeTab: 'articles',
chartInstances: { namespace: null, byteDiff: null, weekday: null },
calendar: {
currentYear: new Date().getFullYear(),
currentMonth: new Date().getMonth(),
selectedDate: null,
viewMode: 'month',
isGrouped: false
}
};
// Konteynerni topish yoki yaratish
let container = targetRoot || document.getElementById('ziyo-userstats-root');
if (!container) {
// Agar wikitextda root bo'lmasa, content boshiga qo'yamiz
const mwContent = document.getElementById('mw-content-text') || document.querySelector('.mw-parser-output');
if (mwContent) {
container = document.createElement('div');
container.id = 'ziyo-userstats-root';
container.className = 'zs-stat-app';
mwContent.prepend(container);
} else {
return;
}
}
// HTML bazaviy skeletni qurish
renderBaseSkeleton(container);
// Kirgan foydalanuvchini aniqlash
const currentLoggedInUser = (mw && mw.config && mw.config.get('wgUserName')) || null;
const urlParams = new URLSearchParams(window.location.search);
const requestedUser = urlParams.get('user');
// Agar URL da user ko'rsatilgan bo'lsa, o'shani ochadi;
// Agar ko'rsatilmagan bo'lsa va foydalanuvchi tizimga kirgan bo'lsa — o'zini statistikasini ochadi!
const targetUsername = requestedUser || currentLoggedInUser;
if (targetUsername) {
document.getElementById('zs-username-input').value = targetUsername;
loadUserProfile(targetUsername, targetUsername === currentLoggedInUser);
} else {
// Mehmon (Login qilmagan foydalanuvchi va ?user berilmagan)
showGuestWelcome();
}
setupEventListeners();
// ========================================================================
// SKELET STRUKTURA
// ========================================================================
function renderBaseSkeleton(el) {
el.innerHTML = `
<div class="zs-stat-wrapper">
<!-- Top Hero & Search -->
<div class="zs-hero-card">
<div class="zs-hero-header">
<div class="zs-brand-row">
<div class="zs-brand-badge">
<i class="fa-solid fa-book-open-reader"></i>
</div>
<div>
<h2 class="zs-hero-title">Ziyosfera <span class="zs-text-sky">UserStats</span></h2>
<p class="zs-hero-subtitle">Foydalanuvchi faolligi, yaratgan barcha maqolalari va interaktiv tahlili</p>
</div>
</div>
<div id="zs-personal-badge-wrap" style="display: none;">
<span class="zs-personal-badge">
<i class="fa-solid fa-user-circle"></i> Sizning shaxsiy statistikangiz
</span>
</div>
</div>
<!-- Search Bar -->
<div class="zs-search-box-wrap">
<div class="zs-search-input-group">
<i class="fa-solid fa-magnifying-glass zs-search-icon"></i>
<input
type="text"
id="zs-username-input"
placeholder="Foydalanuvchi nomini yozing (masalan: Begzod Ergashev, Dilbar Axmadova, Admin)..."
autocomplete="off"
spellcheck="false"
>
<button type="button" class="zs-btn-clear" id="zs-clear-search-btn" style="display: none;">
<i class="fa-solid fa-xmark"></i>
</button>
<button type="button" class="zs-btn-search" id="zs-search-btn">
<span>Qidirish</span>
<i class="fa-solid fa-arrow-right"></i>
</button>
</div>
<div class="zs-autocomplete-dropdown" id="zs-autocomplete-list" style="display: none;"></div>
</div>
<!-- Quick pick chips -->
<div class="zs-quick-pick-row">
<span class="zs-quick-label"><i class="fa-solid fa-fire text-amber"></i> Faol a'zolar:</span>
<div class="zs-quick-chips">
<button type="button" class="zs-chip-btn" data-user="Dilbar Axmadova"><span class="zs-chip-dot">D</span> Dilbar Axmadova</button>
<button type="button" class="zs-chip-btn" data-user="Begzod Ergashev"><span class="zs-chip-dot">B</span> Begzod Ergashev</button>
<button type="button" class="zs-chip-btn" data-user="Programmer"><span class="zs-chip-dot">P</span> Programmer</button>
<button type="button" class="zs-chip-btn" data-user="Admin"><span class="zs-chip-dot">A</span> Admin</button>
</div>
</div>
</div>
<!-- Loading State -->
<div id="zs-loading-state" class="zs-card-block zs-text-center" style="display: none;">
<div class="zs-spinner"></div>
<h3 class="zs-loading-title">Ziyosfera ma'lumotlari tahlil qilinmoqda...</h3>
<p class="zs-loading-desc" id="zs-loading-desc">Foydalanuvchi ma'lumotlari yuklanmoqda...</p>
</div>
<!-- Error State -->
<div id="zs-error-state" class="zs-card-block zs-error-box" style="display: none;">
<div class="zs-error-icon"><i class="fa-solid fa-triangle-exclamation"></i></div>
<div class="zs-error-content">
<h3 id="zs-error-title">Xatolik yuz berdi</h3>
<p id="zs-error-desc">Foydalanuvchi topilmadi.</p>
<button type="button" class="zs-btn-subtle" id="zs-error-retry-btn">Qayta urinish</button>
</div>
</div>
<!-- Guest Welcome (Agar kirilmagan bo'lsa) -->
<div id="zs-guest-welcome" class="zs-card-block zs-guest-card" style="display: none;">
<div class="zs-guest-icon"><i class="fa-solid fa-chart-line"></i></div>
<div class="zs-guest-body">
<h3>Ziyosfera Statistika Markaziga xush kelibsiz!</h3>
<p>O'z shaxsiy statistikangizni ko'rish uchun <a href="/ziyo/Maxsus:UserLogin" class="zs-link-bold">tizimga kiring</a> yoki yuqoridagi qidiruv maydonidan istalgan foydalanuvchini tanlang.</p>
</div>
</div>
<!-- Streaming Progress Banner -->
<div id="zs-streaming-banner" class="zs-streaming-banner" style="display: none;">
<div class="zs-streaming-content">
<span class="zs-pulse-dot"></span>
<span>Yaratilgan barcha maqolalar aniq hisoblanmoqda: </span>
<span class="zs-counter-pill" id="zs-stream-count">0</span>
<span style="font-size: 12px; color: #64748b;" id="zs-stream-status">(fondan yuklanmoqda...)</span>
</div>
<button type="button" class="zs-btn-text" id="zs-stop-streaming-btn">To'xtatish</button>
</div>
<!-- User Profile Content Dashboard -->
<div id="zs-profile-dashboard" style="display: none;">
<!-- Profile Banner -->
<div class="zs-profile-banner">
<div class="zs-avatar-large" id="zs-user-avatar">?</div>
<div class="zs-user-meta-col">
<div class="zs-user-header-row">
<h1 class="zs-user-name" id="zs-user-name">Foydalanuvchi</h1>
<div class="zs-badges-wrap" id="zs-roles-list"></div>
</div>
<div class="zs-meta-tags-row" id="zs-submeta-tags"></div>
</div>
<div class="zs-profile-tools">
<button type="button" class="zs-btn-tool" id="zs-share-link-btn" title="Havoladan nusxa olish"><i class="fa-solid fa-link"></i> Ulashish</button>
<button type="button" class="zs-btn-tool" id="zs-export-csv-btn" title="Maqolalarni CSV formatda saqlash"><i class="fa-solid fa-file-csv"></i> CSV</button>
</div>
</div>
<!-- KPI Cards -->
<div class="zs-kpi-grid">
<!-- KPI 1: Articles -->
<div class="zs-kpi-card highlight-sky clickable" id="zs-kpi-articles">
<div class="zs-kpi-header">
<span class="zs-kpi-label">Yaratgan maqolalari</span>
<div class="zs-kpi-icon sky"><i class="fa-solid fa-newspaper"></i></div>
</div>
<div class="zs-kpi-val" id="zs-stat-articles-count">0</div>
<div class="zs-kpi-footer">
<span class="zs-kpi-status-badge green" id="zs-verified-badge"><i class="fa-solid fa-check"></i> Aniq hisoblandi</span>
</div>
</div>
<!-- KPI 2: Total Edits -->
<div class="zs-kpi-card highlight-green clickable" id="zs-kpi-edits">
<div class="zs-kpi-header">
<span class="zs-kpi-label">Jami tahrirlari</span>
<div class="zs-kpi-icon green"><i class="fa-solid fa-pen-nib"></i></div>
</div>
<div class="zs-kpi-val" id="zs-stat-edits-count">0</div>
<div class="zs-kpi-footer">
<span class="zs-kpi-status-badge gray"><i class="fa-solid fa-layer-group"></i> Turkum, andoza, modul</span>
</div>
</div>
<!-- KPI 3: Daily Pace -->
<div class="zs-kpi-card highlight-cyan clickable" id="zs-kpi-pace">
<div class="zs-kpi-header">
<span class="zs-kpi-label">Faollik sur'ati</span>
<div class="zs-kpi-icon cyan"><i class="fa-solid fa-bolt"></i></div>
</div>
<div class="zs-kpi-val" id="zs-stat-pace">0</div>
<div class="zs-kpi-footer">
<span style="font-size: 11px; color: #64748b;">Kunlik o'rtacha tahrir</span>
</div>
</div>
<!-- KPI 4: Registration -->
<div class="zs-kpi-card highlight-amber">
<div class="zs-kpi-header">
<span class="zs-kpi-label">Ro'yxatdan o'tgan</span>
<div class="zs-kpi-icon amber"><i class="fa-solid fa-calendar-check"></i></div>
</div>
<div class="zs-kpi-val sm" id="zs-stat-reg-date">—</div>
<div class="zs-kpi-footer">
<span style="font-size: 11px; color: #64748b;" id="zs-stat-reg-days">0 kun oldin</span>
</div>
</div>
</div>
<!-- Tab Navigation -->
<div class="zs-tabs-bar">
<button type="button" class="zs-tab-btn active" data-tab="articles">
<i class="fa-solid fa-calendar-days"></i> Maqolalar va Taqvim
<span class="zs-tab-counter" id="zs-tab-art-badge">0</span>
</button>
<button type="button" class="zs-tab-btn" data-tab="analytics">
<i class="fa-solid fa-chart-pie"></i> Tahrirlar tahlili (Andozalar & Turkumlar)
</button>
<button type="button" class="zs-tab-btn" data-tab="recent">
<i class="fa-solid fa-clock-rotate-left"></i> So'nggi tahrirlar
</button>
<button type="button" class="zs-tab-btn" data-tab="permissions">
<i class="fa-solid fa-shield-halved"></i> Huquq va guruhlar
</button>
</div>
<!-- TAB 1: Articles & Calendar -->
<div class="zs-tab-content active" id="zs-tab-content-articles">
<!-- Calendar Card -->
<div class="zs-card-block" id="zs-calendar-card">
<div class="zs-card-title-row">
<div>
<h3 class="zs-card-title"><i class="fa-solid fa-calendar-days text-emerald"></i> Maqolalar Taqvimi (Kalendar)</h3>
<p class="zs-card-sub">Oy kunlari bo'yicha yozilgan maqolalar soni. Kunga bosib darhol filtrlang.</p>
</div>
<div class="zs-toggle-group">
<button type="button" class="zs-toggle-btn active" id="zs-cal-month-view-btn">Oylik taqvim</button>
<button type="button" class="zs-toggle-btn" id="zs-cal-lead-view-btn">Eng faol kunlar</button>
</div>
</div>
<!-- Calendar Nav -->
<div class="zs-cal-nav-bar" id="zs-cal-month-nav">
<button type="button" class="zs-btn-subtle" id="zs-cal-prev-btn"><i class="fa-solid fa-chevron-left"></i> Oldingi oy</button>
<div class="zs-cal-month-display">
<span id="zs-cal-month-title" class="zs-month-title">Sentabr 2026</span>
<select id="zs-cal-month-select" class="zs-select-sm"></select>
</div>
<button type="button" class="zs-btn-subtle" id="zs-cal-next-btn">Keyingi oy <i class="fa-solid fa-chevron-right"></i></button>
</div>
<!-- Month Grid -->
<div id="zs-cal-grid-view">
<div class="zs-cal-weekdays">
<span>Dush</span><span>Sesh</span><span>Chor</span><span>Pay</span><span>Jum</span><span class="weekend">Shan</span><span class="weekend">Yak</span>
</div>
<div class="zs-cal-days-grid" id="zs-cal-days-grid"></div>
</div>
<!-- Leaderboard Grid -->
<div id="zs-cal-lead-view" style="display: none;">
<div class="zs-leaderboard-grid" id="zs-leaderboard-grid"></div>
</div>
<!-- Active Date Filter Alert -->
<div class="zs-active-filter-alert" id="zs-active-filter-alert" style="display: none;">
<div>
<i class="fa-solid fa-filter"></i> Tanlangan sana: <strong id="zs-filter-date-name">—</strong> (<span id="zs-filter-date-count">0</span> ta maqola)
</div>
<button type="button" class="zs-btn-subtle sm" id="zs-clear-filter-btn"><i class="fa-solid fa-xmark"></i> Barcha maqolalarni ko'rsatish</button>
</div>
</div>
<!-- Articles Table Card -->
<div class="zs-card-block">
<div class="zs-card-title-row">
<div>
<h3 class="zs-card-title"><i class="fa-solid fa-list-check text-sky"></i> Yaratilgan Barcha Maqolalar</h3>
<p class="zs-card-sub">Foydalanuvchi tomonidan asosiy nomlar fazosida (Namespace 0) yaratilgan maqolalar ro'yxati</p>
</div>
<div class="zs-table-actions">
<div class="zs-input-icon-wrap">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="text" id="zs-article-search-input" placeholder="Maqolalardan qidirish...">
</div>
<select id="zs-article-sort-select" class="zs-select-sm">
<option value="newest">Eng yangi</option>
<option value="oldest">Eng eski</option>
<option value="alpha">Alifbo bo'yicha</option>
</select>
<button type="button" class="zs-btn-subtle" id="zs-toggle-group-btn" title="Kunlar bo'yicha guruhlash">
<i class="fa-solid fa-layer-group"></i> Guruhlash
</button>
</div>
</div>
<!-- Table View -->
<div class="zs-table-responsive" id="zs-articles-table-wrap">
<table class="zs-data-table">
<thead>
<tr>
<th style="width: 45px;">#</th>
<th>Maqola nomi</th>
<th style="width: 170px;">Yaratilgan sana</th>
<th style="width: 110px;">Hajmi</th>
<th style="width: 100px; text-align: center;">Amal</th>
</tr>
</thead>
<tbody id="zs-articles-tbody"></tbody>
</table>
</div>
<!-- Grouped Accordion View -->
<div id="zs-articles-grouped-wrap" style="display: none;"></div>
<!-- Table Pagination / Status Footer -->
<div class="zs-table-footer">
<span id="zs-table-count-info">0 ta maqola ko'rsatilmoqda</span>
</div>
</div>
</div>
<!-- TAB 2: Analytics (Namespace, Andoza, Byte Diff) -->
<div class="zs-tab-content" id="zs-tab-content-analytics">
<div class="zs-analytics-grid">
<!-- Chart 1: Namespaces (Andoza, Turkum) -->
<div class="zs-card-block">
<h3 class="zs-card-title"><i class="fa-solid fa-chart-pie text-sky"></i> Nomlar Fazosi (Bo'limlar) Tahlili</h3>
<p class="zs-card-sub">Asosiy maqolalar, munozaralar, andozalar va turkumlardagi hissasi</p>
<div class="zs-chart-wrap">
<canvas id="zs-chart-namespace"></canvas>
</div>
<div class="zs-legend-list" id="zs-namespace-legend"></div>
</div>
<!-- Chart 2: Weekday Activity -->
<div class="zs-card-block">
<h3 class="zs-card-title"><i class="fa-solid fa-chart-simple text-green"></i> Haftaning Kunlari Bo'yicha Faollik</h3>
<p class="zs-card-sub">Qaysi kunlarda eng ko'p tahrir amalga oshirilgan</p>
<div class="zs-chart-wrap">
<canvas id="zs-chart-weekday"></canvas>
</div>
</div>
<!-- Chart 3: Byte Impact Differences -->
<div class="zs-card-block full-width">
<h3 class="zs-card-title"><i class="fa-solid fa-chart-column text-amber"></i> So'nggi Tahrirlardagi Bayt O'zgarishlari</h3>
<p class="zs-card-sub">Maqolalarga qo'shilgan (yashil) va o'chirilgan (qizil) matn hajmi</p>
<div class="zs-chart-wrap" style="height: 240px;">
<canvas id="zs-chart-bytediff"></canvas>
</div>
<div class="zs-byte-summary-row" id="zs-byte-summary"></div>
</div>
</div>
</div>
<!-- TAB 3: Recent Edits Timeline -->
<div class="zs-tab-content" id="zs-tab-content-recent">
<div class="zs-card-block">
<h3 class="zs-card-title"><i class="fa-solid fa-clock-rotate-left text-sky"></i> Foydalanuvchining So'nggi Tahrirlari</h3>
<p class="zs-card-sub">Oxirgi amalga oshirilgan tahrirlar tarixi va izohlari</p>
<div class="zs-timeline-list" id="zs-recent-timeline"></div>
</div>
</div>
<!-- TAB 4: Permissions & Groups -->
<div class="zs-tab-content" id="zs-tab-content-permissions">
<div class="zs-card-block">
<h3 class="zs-card-title"><i class="fa-solid fa-shield-halved text-sky"></i> Foydalanuvchi Guruhlari va Vakolatlari</h3>
<div class="zs-groups-list" id="zs-user-groups-list"></div>
<h4 style="margin: 20px 0 10px; font-size: 15px; font-weight: 700;">Tizimda berilgan barcha huquqlari (<span id="zs-rights-count">0</span> ta)</h4>
<div class="zs-rights-grid" id="zs-user-rights-grid"></div>
</div>
</div>
</div>
<!-- Article Preview Modal -->
<div class="zs-modal-overlay" id="zs-preview-modal" style="display: none;">
<div class="zs-modal-dialog">
<div class="zs-modal-header">
<div>
<span class="zs-modal-tag"><i class="fa-solid fa-newspaper"></i> Maqola matnidan parcha</span>
<h3 class="zs-modal-title" id="zs-modal-title">Maqola</h3>
</div>
<button type="button" class="zs-modal-close" id="zs-modal-close-btn">×</button>
</div>
<div class="zs-modal-body" id="zs-modal-body">
<div class="zs-spinner sm"></div>
</div>
<div class="zs-modal-footer">
<span class="zs-modal-note">Matn Ziyosfera ensiklopediyasidan olindi</span>
<a href="#" target="_blank" rel="noopener noreferrer" class="zs-btn-primary sm" id="zs-modal-full-link">
To'liq maqolani o'qish <i class="fa-solid fa-arrow-up-right-from-square"></i>
</a>
</div>
</div>
</div>
</div>
`;
}
// ========================================================================
// API SERVICE
// ========================================================================
function apiRequest(params) {
const urlParams = new URLSearchParams(params);
urlParams.set('format', 'json');
urlParams.set('origin', '*');
return fetch(`${API_ENDPOINT}?${urlParams.toString()}`).then(function(res) {
if (!res.ok) throw new Error('API javob bermadi');
return res.json();
});
}
// ========================================================================
// LOAD USER PROFILE
// ========================================================================
function loadUserProfile(username, isCurrentUser) {
if (!username || !username.trim()) return;
const cleanUser = username.trim();
// UI reset
document.getElementById('zs-guest-welcome').style.display = 'none';
document.getElementById('zs-profile-dashboard').style.display = 'none';
document.getElementById('zs-error-state').style.display = 'none';
document.getElementById('zs-loading-state').style.display = 'block';
document.getElementById('zs-loading-desc').textContent = cleanUser + " foydalanuvchisi ma'lumotlari olinmoqda...";
if (isCurrentUser) {
document.getElementById('zs-personal-badge-wrap').style.display = 'block';
} else {
document.getElementById('zs-personal-badge-wrap').style.display = 'none';
}
state.shouldStopStreaming = false;
state.createdArticles = [];
state.recentEdits = [];
state.articlesByDate = {};
state.calendar.selectedDate = null;
// 1. Foydalanuvchi profilini olish
apiRequest({
action: 'query',
list: 'users',
ususers: cleanUser,
usprop: 'blockinfo|groups|implicitgroups|rights|editcount|registration|emailable|gender'
}).then(function(data) {
const user = data.query.users.[0];
if (!user || user.missing !== undefined || user.invalid !== undefined) {
throw new Error("Bunday foydalanuvchi Ziyosferada topilmadi.");
}
state.currentUser = user;
renderUserProfileHeader(user);
// 2. So'nggi tahrirlarni olish
return apiRequest({
action: 'query',
list: 'usercontribs',
ucuser: cleanUser,
uclimit: 100,
ucprop: 'title|timestamp|comment|flags|sizediff'
});
}).then(function(contribData) {
state.recentEdits = contribData.query.usercontribs || [];
renderPermissions(state.currentUser);
renderRecentEdits(state.recentEdits);
renderAnalyticsCharts();
// 3. Yaratilgan maqolalarni backgroundda hisoblashni boshlash
document.getElementById('zs-loading-state').style.display = 'none';
document.getElementById('zs-profile-dashboard').style.display = 'block';
streamCreatedArticles(cleanUser);
}).catch(function(err) {
document.getElementById('zs-loading-state').style.display = 'none';
document.getElementById('zs-error-state').style.display = 'block';
document.getElementById('zs-error-title').textContent = "Ma'lumotlarni yuklab bo'lmadi";
document.getElementById('zs-error-desc').textContent = err.message || "Xatolik yuz berdi.";
});
}
// ========================================================================
// STREAM CREATED ARTICLES (No "100+", Exact count)
// ========================================================================
function streamCreatedArticles(username) {
state.isStreamingArticles = true;
const banner = document.getElementById('zs-streaming-banner');
const countPill = document.getElementById('zs-stream-count');
banner.style.display = 'flex';
let totalFound = 0;
function fetchNextBatch(contParams) {
if (state.shouldStopStreaming) {
finishStreaming();
return;
}
const params = {
action: 'query',
list: 'usercontribs',
ucuser: username,
ucshow: 'new',
ucnamespace: 0,
uclimit: 100,
ucprop: 'title|timestamp|size|comment'
};
if (contParams) {
Object.assign(params, contParams);
}
apiRequest(params).then(function(data) {
const items = data.query.usercontribs || [];
items.forEach(function(item) {
state.createdArticles.push(item);
const dateStr = item.timestamp.split('T')[0];
if (!state.articlesByDate[dateStr]) {
state.articlesByDate[dateStr] = [];
}
state.articlesByDate[dateStr].push(item);
});
totalFound += items.length;
countPill.textContent = totalFound;
document.getElementById('zs-stat-articles-count').textContent = totalFound.toLocaleString();
document.getElementById('zs-tab-art-badge').textContent = totalFound.toLocaleString();
// Taqvimni va jadvalni har bir partiyada yangilab borish
updateCalendarData();
filterAndRenderArticles();
if (data.continue && !state.shouldStopStreaming) {
fetchNextBatch(data.continue);
} else {
finishStreaming();
}
}).catch(function() {
finishStreaming();
});
}
function finishStreaming() {
state.isStreamingArticles = false;
banner.style.display = 'none';
document.getElementById('zs-verified-badge').innerHTML =
`<i class="fa-solid fa-check"></i> Aniq hisoblandi (${state.createdArticles.length.toLocaleString()})`;
renderCalendar();
}
fetchNextBatch(null);
}
// ========================================================================
// HEADER & METRICS
// ========================================================================
function renderUserProfileHeader(user) {
const avatarEl = document.getElementById('zs-user-avatar');
const firstLetter = (user.name || '?')[0].toUpperCase();
avatarEl.textContent = firstLetter;
document.getElementById('zs-user-name').textContent = user.name;
document.getElementById('zs-stat-edits-count').textContent = (user.editcount || 0).toLocaleString();
// Ro'yxatdan o'tgan sana
if (user.registration) {
const regDate = new Date(user.registration);
const diffDays = Math.max(1, Math.floor((Date.now() - regDate.getTime()) / (1000 * 60 * 60 * 24)));
document.getElementById('zs-stat-reg-date').textContent = formatDateUz(regDate);
document.getElementById('zs-stat-reg-days').textContent = diffDays.toLocaleString() + " kun oldin";
const pace = ((user.editcount || 0) / diffDays).toFixed(1);
document.getElementById('zs-stat-pace').textContent = pace + " tahrir/kun";
} else {
document.getElementById('zs-stat-reg-date').textContent = "Noma'lum";
document.getElementById('zs-stat-reg-days').textContent = "—";
document.getElementById('zs-stat-pace').textContent = "—";
}
// Rollar
const rolesContainer = document.getElementById('zs-roles-list');
const groups = user.groups || ['user'];
rolesContainer.innerHTML = groups.map(function(grp) {
const def = GROUP_DEFINITIONS[grp] || { name: grp, class: 'user' };
return `<span class="zs-badge-role ${def.class}">${escapeHtml(def.name)}</span>`;
}).join('');
// Submeta tags
const submeta = document.getElementById('zs-submeta-tags');
submeta.innerHTML = `
<span><i class="fa-solid fa-id-card"></i> ID: <strong>#${user.userid || 0}</strong></span>
<span><i class="fa-solid fa-pen-nib"></i> Jami tahrirlar: <strong>${(user.editcount || 0).toLocaleString()}</strong></span>
<span><i class="fa-solid fa-venus-mars"></i> Jinsi: <strong>${user.gender === 'female' ? 'Ayol' : (user.gender === 'male' ? 'Erkak' : 'Belgilanmagan')}</strong></span>
`;
}
// ========================================================================
// CALENDAR CONTROLLER
// ========================================================================
function updateCalendarData() {
state.daysWithArticles = Object.keys(state.articlesByDate).sort().reverse();
// Select boxdagi faol oylarni yangilash
const monthSet = new Set();
state.daysWithArticles.forEach(function(d) {
monthSet.add(d.substring(0, 7)); // 'YYYY-MM'
});
const select = document.getElementById('zs-cal-month-select');
const currentSelected = `${state.calendar.currentYear}-${String(state.calendar.currentMonth + 1).padStart(2, '0')}`;
select.innerHTML = Array.from(monthSet).map(function(ym) {
const parts = ym.split('-');
const y = parseInt(parts[0], 10);
const m = parseInt(parts[1], 10) - 1;
const isSel = (y === state.calendar.currentYear && m === state.calendar.currentMonth) ? 'selected' : '';
return `<option value="${ym}" ${isSel}>${MONTH_NAMES_UZ[m]} ${y}</option>`;
}).join('');
renderLeaderboard();
}
function renderCalendar() {
const year = state.calendar.currentYear;
const month = state.calendar.currentMonth;
document.getElementById('zs-cal-month-title').textContent = `${MONTH_NAMES_UZ[month]} ${year}`;
const grid = document.getElementById('zs-cal-days-grid');
grid.innerHTML = '';
const firstDay = new Date(year, month, 1).getDay();
const startingDay = (firstDay === 0) ? 6 : firstDay - 1; // Dushanbadan boshlanishi
const daysInMonth = new Date(year, month + 1, 0).getDate();
// Bo'sh boshlang'ich kataklar
for (let i = 0; i < startingDay; i++) {
const emptyCell = document.createElement('div');
emptyCell.className = 'zs-cal-cell empty';
grid.appendChild(emptyCell);
}
// Kunlar
for (let day = 1; day <= daysInMonth; day++) {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
const count = (state.articlesByDate[dateStr] || []).length;
const cell = document.createElement('div');
cell.className = 'zs-cal-cell' + (count > 0 ? ' has-articles' : '') + (state.calendar.selectedDate === dateStr ? ' selected' : '');
let inner = `<span class="zs-cal-day-num">${day}</span>`;
if (count > 0) {
inner += `<span class="zs-cal-count-badge">${count} ta</span>`;
cell.addEventListener('click', function() {
selectDateFilter(dateStr);
});
}
cell.innerHTML = inner;
grid.appendChild(cell);
}
}
function renderLeaderboard() {
const container = document.getElementById('zs-leaderboard-grid');
const days = state.daysWithArticles.slice(0, 30); // Top 30 faol kunlar
if (days.length === 0) {
container.innerHTML = '<div style="padding: 15px; color: #64748b;">Hali maqolalar yuklanmadi...</div>';
return;
}
container.innerHTML = days.map(function(d) {
const count = (state.articlesByDate[d] || []).length;
const isSel = (state.calendar.selectedDate === d) ? 'selected' : '';
return `
<div class="zs-leaderboard-card ${isSel}" data-date="${d}">
<span class="zs-lead-date">${d}</span>
<span class="zs-lead-count">${count} ta maqola</span>
</div>
`;
}).join('');
container.querySelectorAll('.zs-leaderboard-card').forEach(function(card) {
card.addEventListener('click', function() {
selectDateFilter(card.getAttribute('data-date'));
});
});
}
function selectDateFilter(dateStr) {
if (state.calendar.selectedDate === dateStr) {
clearDateFilter();
return;
}
state.calendar.selectedDate = dateStr;
document.getElementById('zs-active-filter-alert').style.display = 'flex';
document.getElementById('zs-filter-date-name').textContent = dateStr;
document.getElementById('zs-filter-date-count').textContent = (state.articlesByDate[dateStr] || []).length;
renderCalendar();
renderLeaderboard();
filterAndRenderArticles();
// Jadvalga scroll qilish
document.getElementById('zs-articles-table-wrap').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
function clearDateFilter() {
state.calendar.selectedDate = null;
document.getElementById('zs-active-filter-alert').style.display = 'none';
renderCalendar();
renderLeaderboard();
filterAndRenderArticles();
}
// ========================================================================
// ARTICLES TABLE & GROUPING
// ========================================================================
function filterAndRenderArticles() {
const search = (document.getElementById('zs-article-search-input').value || '').toLowerCase();
const sort = document.getElementById('zs-article-sort-select').value;
const selectedDate = state.calendar.selectedDate;
let list = state.createdArticles.slice();
// Sana filtri
if (selectedDate) {
list = list.filter(function(a) {
return a.timestamp.indexOf(selectedDate) === 0;
});
}
// Qidiruv filtri
if (search) {
list = list.filter(function(a) {
return a.title.toLowerCase().indexOf(search) !== -1;
});
}
// Saralash
if (sort === 'newest') {
list.sort(function(a, b) { return new Date(b.timestamp) - new Date(a.timestamp); });
} else if (sort === 'oldest') {
list.sort(function(a, b) { return new Date(a.timestamp) - new Date(b.timestamp); });
} else if (sort === 'alpha') {
list.sort(function(a, b) { return a.title.localeCompare(b.title); });
}
state.filteredArticles = list;
document.getElementById('zs-table-count-info').textContent = `${list.length.toLocaleString()} ta maqola ko'rsatilmoqda`;
if (state.calendar.isGrouped) {
renderGroupedView(list);
} else {
renderTableView(list);
}
}
function renderTableView(list) {
const tbody = document.getElementById('zs-articles-tbody');
if (list.length === 0) {
tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; padding: 24px; color: #64748b;">Maqolalar topilmadi</td></tr>`;
return;
}
tbody.innerHTML = list.slice(0, 150).map(function(item, idx) {
const url = `${ARTICLE_VIEW_BASE}${encodeURIComponent(item.title)}`;
const dateStr = formatDateTimeUz(new Date(item.timestamp));
const sizeStr = item.size ? `${item.size.toLocaleString()} bayt` : '—';
return `
<tr>
<td style="color: #64748b;">${idx + 1}</td>
<td>
<a href="${url}" target="_blank" rel="noopener noreferrer" class="zs-art-link">
<i class="fa-solid fa-file-lines" style="color: #0284c7; margin-right: 6px;"></i>
${escapeHtml(item.title)}
</a>
</td>
<td style="font-size: 12px; color: #475569;">${dateStr}</td>
<td><span class="zs-badge-size">${sizeStr}</span></td>
<td style="text-align: center;">
<button type="button" class="zs-btn-preview" data-title="${escapeHtml(item.title)}">
<i class="fa-solid fa-eye"></i> O'qish
</button>
</td>
</tr>
`;
}).join('');
tbody.querySelectorAll('.zs-btn-preview').forEach(function(btn) {
btn.addEventListener('click', function() {
openArticlePreview(btn.getAttribute('data-title'));
});
});
}
function renderGroupedView(list) {
const wrap = document.getElementById('zs-articles-grouped-wrap');
const grouped = {};
list.forEach(function(item) {
const d = item.timestamp.split('T')[0];
if (!grouped[d]) grouped[d] = [];
grouped[d].push(item);
});
const dates = Object.keys(grouped).sort().reverse();
if (dates.length === 0) {
wrap.innerHTML = `<div style="text-align: center; padding: 24px; color: #64748b;">Guruhlangan maqolalar topilmadi</div>`;
return;
}
wrap.innerHTML = dates.map(function(d) {
const items = grouped[d];
return `
<div class="zs-date-group-card">
<div class="zs-date-group-header">
<span><i class="fa-solid fa-calendar-day text-sky"></i> <strong>${d}</strong></span>
<span class="zs-counter-pill">${items.length} ta maqola</span>
</div>
<div class="zs-date-group-body">
${items.map(function(it) {
const url = `${ARTICLE_VIEW_BASE}${encodeURIComponent(it.title)}`;
return `
<div class="zs-group-item-row">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="zs-art-link">${escapeHtml(it.title)}</a>
<button type="button" class="zs-btn-preview sm" data-title="${escapeHtml(it.title)}">Ko'rish</button>
</div>
`;
}).join('')}
</div>
</div>
`;
}).join('');
wrap.querySelectorAll('.zs-btn-preview').forEach(function(btn) {
btn.addEventListener('click', function() {
openArticlePreview(btn.getAttribute('data-title'));
});
});
}
// ========================================================================
// ARTICLE PREVIEW MODAL
// ========================================================================
function openArticlePreview(title) {
const modal = document.getElementById('zs-preview-modal');
const modalTitle = document.getElementById('zs-modal-title');
const modalBody = document.getElementById('zs-modal-body');
const fullLink = document.getElementById('zs-modal-full-link');
modalTitle.textContent = title;
fullLink.href = `${ARTICLE_VIEW_BASE}${encodeURIComponent(title)}`;
modalBody.innerHTML = `<div class="zs-spinner sm"></div> <p style="text-align: center; color: #64748b; margin-top: 10px;">Matn yuklanmoqda...</p>`;
modal.style.display = 'flex';
apiRequest({
action: 'query',
prop: 'extracts',
exintro: true,
explaintext: true,
titles: title
}).then(function(data) {
const pages = data.query.pages || {};
const page = Object.values(pages)[0];
if (page && page.extract) {
modalBody.innerHTML = `<p>${escapeHtml(page.extract).replace(/\n\n/g, '</p><p>')}</p>`;
} else {
modalBody.innerHTML = `<p style="color: #64748b;">Ushbu maqolaning kirish qismi topilmadi.</p>`;
}
}).catch(function() {
modalBody.innerHTML = `<p style="color: #e11d48;">Maqola matnini yuklab bo'lmadi.</p>`;
});
}
// ========================================================================
// ANALYTICS & CHARTS (Namespace: Andoza, ByteDiff, Weekdays)
// ========================================================================
function renderAnalyticsCharts() {
if (!window.Chart) return;
const edits = state.recentEdits || [];
if (edits.length === 0) return;
// 1. Nomlar Fazosi (Namespace)
const nsCounts = {};
edits.forEach(function(e) {
const ns = e.ns || 0;
const name = NAMESPACE_MAP[ns] || `Bo'lim ${ns}`;
nsCounts[name] = (nsCounts[name] || 0) + 1;
});
const nsLabels = Object.keys(nsCounts);
const nsValues = Object.values(nsCounts);
const palette = ['#0284c7', '#059669', '#2563eb', '#d97706', '#7c3aed', '#ec4899', '#0891b2'];
if (state.chartInstances.namespace) state.chartInstances.namespace.destroy();
const ctxNs = document.getElementById('zs-chart-namespace').getContext('2d');
state.chartInstances.namespace = new Chart(ctxNs, {
type: 'doughnut',
data: {
labels: nsLabels,
datasets: [{
data: nsValues,
backgroundColor: palette.slice(0, nsLabels.length),
borderWidth: 2,
borderColor: '#ffffff'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
cutout: '70%'
}
});
document.getElementById('zs-namespace-legend').innerHTML = nsLabels.map(function(lbl, i) {
return `
<div class="zs-legend-item">
<span class="zs-legend-dot" style="background: ${palette[i % palette.length]}"></span>
<span>${escapeHtml(lbl)}: <strong>${nsValues[i]}</strong></span>
</div>
`;
}).join('');
// 2. Haftaning Kunlari (Weekdays)
const dayNames = ['Yakshanba', 'Dushanba', 'Seshanba', 'Chorshanba', 'Payshanba', 'Juma', 'Shanba'];
const dayCounts = [0, 0, 0, 0, 0, 0, 0];
edits.forEach(function(e) {
dayCounts[new Date(e.timestamp).getDay()]++;
});
if (state.chartInstances.weekday) state.chartInstances.weekday.destroy();
const ctxW = document.getElementById('zs-chart-weekday').getContext('2d');
state.chartInstances.weekday = new Chart(ctxW, {
type: 'bar',
data: {
labels: dayNames,
datasets: [{
data: dayCounts,
backgroundColor: '#0284c7',
borderRadius: 6
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
x: { grid: { display: false }, ticks: { font: { size: 11, weight: '600' } } },
y: { grid: { color: '#f1f5f9' }, ticks: { font: { size: 10 } } }
}
}
});
// 3. Bayt O'zgarishlari (Byte diffs)
let posBytes = 0, negBytes = 0;
const recentSample = edits.slice(0, 20).reverse();
const bLabels = recentSample.map(function(e) { return (e.title.length > 12) ? e.title.substring(0, 12) + '...' : e.title; });
const bData = recentSample.map(function(e) {
const d = e.sizediff || 0;
if (d > 0) posBytes += d; else if (d < 0) negBytes += Math.abs(d);
return d;
});
const bColors = bData.map(function(v) { return v >= 0 ? '#059669' : '#e11d48'; });
if (state.chartInstances.byteDiff) state.chartInstances.byteDiff.destroy();
const ctxB = document.getElementById('zs-chart-bytediff').getContext('2d');
state.chartInstances.byteDiff = new Chart(ctxB, {
type: 'bar',
data: {
labels: bLabels,
datasets: [{
data: bData,
backgroundColor: bColors,
borderRadius: 4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
x: { grid: { display: false }, ticks: { font: { size: 9 } } },
y: { grid: { color: '#f1f5f9' } }
}
}
});
document.getElementById('zs-byte-summary').innerHTML = `
<div>Qo'shilgan: <strong style="color: #059669;">+${posBytes.toLocaleString()} B</strong></div>
<div>O'chirilgan: <strong style="color: #e11d48;">-${negBytes.toLocaleString()} B</strong></div>
<div>Tahrirlar: <strong>${recentSample.length} ta namuna</strong></div>
`;
}
// ========================================================================
// RECENT EDITS TIMELINE
// ========================================================================
function renderRecentEdits(edits) {
const container = document.getElementById('zs-recent-timeline');
if (edits.length === 0) {
container.innerHTML = '<div style="color: #64748b; padding: 15px;">Tahrirlar topilmadi.</div>';
return;
}
container.innerHTML = edits.slice(0, 50).map(function(e) {
const time = formatDateTimeUz(new Date(e.timestamp));
const diff = e.sizediff || 0;
const diffText = diff > 0 ? `+${diff}` : `${diff}`;
const diffClass = diff > 0 ? 'pos' : (diff < 0 ? 'neg' : 'zero');
const url = `${ARTICLE_VIEW_BASE}${encodeURIComponent(e.title)}`;
return `
<div class="zs-timeline-item">
<div class="zs-timeline-icon"><i class="fa-solid fa-pen-nib"></i></div>
<div class="zs-timeline-content">
<div class="zs-timeline-title-row">
<a href="${url}" target="_blank" rel="noopener noreferrer" class="zs-art-link">${escapeHtml(e.title)}</a>
<span class="zs-timeline-date">${time}</span>
</div>
<div class="zs-timeline-meta-row">
<span class="zs-badge-diff ${diffClass}">${diffText} bayt</span>
<span class="zs-timeline-comment">${escapeHtml(e.comment || 'Tahrir izohisiz')}</span>
</div>
</div>
</div>
`;
}).join('');
}
// ========================================================================
// PERMISSIONS & RIGHTS
// ========================================================================
function renderPermissions(user) {
const groupsList = document.getElementById('zs-user-groups-list');
const groups = user.groups || ['user'];
groupsList.innerHTML = groups.map(function(grp) {
const def = GROUP_DEFINITIONS[grp] || { name: grp, desc: 'Ziyosfera tizimidagi biriktirilgan guruh', icon: 'fa-shield-halved', class: 'user' };
return `
<div class="zs-group-item-card">
<div class="zs-group-icon-wrap"><i class="fa-solid ${def.icon}"></i></div>
<div>
<div style="font-weight: 700; font-size: 14px;">${escapeHtml(def.name)} <code style="color: #64748b;">(${grp})</code></div>
<div style="font-size: 12px; color: #64748b;">${escapeHtml(def.desc)}</div>
</div>
</div>
`;
}).join('');
const rights = user.rights || [];
document.getElementById('zs-rights-count').textContent = rights.length;
document.getElementById('zs-user-rights-grid').innerHTML = rights.map(function(r) {
return `<div class="zs-right-chip"><i class="fa-solid fa-check text-green"></i> <code>${escapeHtml(r)}</code></div>`;
}).join('');
}
// ========================================================================
// GUEST WELCOME
// ========================================================================
function showGuestWelcome() {
document.getElementById('zs-guest-welcome').style.display = 'flex';
document.getElementById('zs-loading-state').style.display = 'none';
document.getElementById('zs-profile-dashboard').style.display = 'none';
}
// ========================================================================
// EVENT LISTENERS
// ========================================================================
function setupEventListeners() {
const input = document.getElementById('zs-username-input');
const searchBtn = document.getElementById('zs-search-btn');
const clearBtn = document.getElementById('zs-clear-search-btn');
const dropdown = document.getElementById('zs-autocomplete-list');
searchBtn.addEventListener('click', function() {
const val = input.value.trim();
if (val) loadUserProfile(val, false);
dropdown.style.display = 'none';
});
input.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
e.preventDefault();
const val = input.value.trim();
if (val) loadUserProfile(val, false);
dropdown.style.display = 'none';
}
});
clearBtn.addEventListener('click', function() {
input.value = '';
clearBtn.style.display = 'none';
dropdown.style.display = 'none';
input.focus();
});
let debounceTimer;
input.addEventListener('input', function(e) {
const val = e.target.value.trim();
clearBtn.style.display = val.length > 0 ? 'block' : 'none';
clearTimeout(debounceTimer);
if (val.length < 1) {
dropdown.style.display = 'none';
return;
}
debounceTimer = setTimeout(function() {
apiRequest({
action: 'query',
list: 'allusers',
auprefix: val,
aulimit: 8,
auprop: 'editcount'
}).then(function(data) {
const users = data.query.allusers || [];
if (users.length === 0) {
dropdown.style.display = 'none';
return;
}
dropdown.innerHTML = users.map(function(u) {
return `
<div class="zs-autocomplete-item" data-name="${escapeHtml(u.name)}">
<span><strong>${escapeHtml(u.name)}</strong></span>
<span style="font-family: monospace; font-size: 11px; color: #059669;">${(u.editcount || 0).toLocaleString()} tahrir</span>
</div>
`;
}).join('');
dropdown.style.display = 'block';
dropdown.querySelectorAll('.zs-autocomplete-item').forEach(function(item) {
item.addEventListener('click', function() {
const uName = item.getAttribute('data-name');
input.value = uName;
dropdown.style.display = 'none';
loadUserProfile(uName, false);
});
});
});
}, 250);
});
// Quick chips
document.querySelectorAll('.zs-chip-btn').forEach(function(chip) {
chip.addEventListener('click', function() {
const user = chip.getAttribute('data-user');
input.value = user;
loadUserProfile(user, false);
});
});
// Tabs
document.querySelectorAll('.zs-tab-btn').forEach(function(btn) {
btn.addEventListener('click', function() {
document.querySelectorAll('.zs-tab-btn').forEach(function(b) { b.classList.remove('active'); });
document.querySelectorAll('.zs-tab-content').forEach(function(c) { c.classList.remove('active'); });
btn.classList.add('active');
const tabId = btn.getAttribute('data-tab');
document.getElementById('zs-tab-content-' + tabId).classList.add('active');
if (tabId === 'analytics') renderAnalyticsCharts();
});
});
// Calendar month buttons
document.getElementById('zs-cal-prev-btn').addEventListener('click', function() {
state.calendar.currentMonth--;
if (state.calendar.currentMonth < 0) {
state.calendar.currentMonth = 11;
state.calendar.currentYear--;
}
renderCalendar();
});
document.getElementById('zs-cal-next-btn').addEventListener('click', function() {
state.calendar.currentMonth++;
if (state.calendar.currentMonth > 11) {
state.calendar.currentMonth = 0;
state.calendar.currentYear++;
}
renderCalendar();
});
document.getElementById('zs-cal-month-select').addEventListener('change', function(e) {
const parts = e.target.value.split('-');
state.calendar.currentYear = parseInt(parts[0], 10);
state.calendar.currentMonth = parseInt(parts[1], 10) - 1;
renderCalendar();
});
// Calendar view toggle (Month vs Leaderboard)
document.getElementById('zs-cal-month-view-btn').addEventListener('click', function() {
this.classList.add('active');
document.getElementById('zs-cal-lead-view-btn').classList.remove('active');
document.getElementById('zs-cal-grid-view').style.display = 'block';
document.getElementById('zs-cal-month-nav').style.display = 'flex';
document.getElementById('zs-cal-lead-view').style.display = 'none';
});
document.getElementById('zs-cal-lead-view-btn').addEventListener('click', function() {
this.classList.add('active');
document.getElementById('zs-cal-month-view-btn').classList.remove('active');
document.getElementById('zs-cal-grid-view').style.display = 'none';
document.getElementById('zs-cal-month-nav').style.display = 'none';
document.getElementById('zs-cal-lead-view').style.display = 'block';
});
// Clear filter
document.getElementById('zs-clear-filter-btn').addEventListener('click', clearDateFilter);
// Articles filter & sort
document.getElementById('zs-article-search-input').addEventListener('input', filterAndRenderArticles);
document.getElementById('zs-article-sort-select').addEventListener('change', filterAndRenderArticles);
document.getElementById('zs-toggle-group-btn').addEventListener('click', function() {
state.calendar.isGrouped = !state.calendar.isGrouped;
document.getElementById('zs-articles-table-wrap').style.display = state.calendar.isGrouped ? 'none' : 'block';
document.getElementById('zs-articles-grouped-wrap').style.display = state.calendar.isGrouped ? 'block' : 'none';
filterAndRenderArticles();
});
// Stop streaming
document.getElementById('zs-stop-streaming-btn').addEventListener('click', function() {
state.shouldStopStreaming = true;
});
// Modal close
document.getElementById('zs-modal-close-btn').addEventListener('click', function() {
document.getElementById('zs-preview-modal').style.display = 'none';
});
document.getElementById('zs-preview-modal').addEventListener('click', function(e) {
if (e.target.id === 'zs-preview-modal') {
document.getElementById('zs-preview-modal').style.display = 'none';
}
});
// Share button
document.getElementById('zs-share-link-btn').addEventListener('click', function() {
const u = state.currentUser ? state.currentUser.name : '';
const url = `${window.location.origin}${window.location.pathname}?title=Ziyosfera:Statistika&user=${encodeURIComponent(u)}`;
navigator.clipboard.writeText(url).then(function() {
alert("Havola nusxalandi: " + url);
});
});
// Export CSV
document.getElementById('zs-export-csv-btn').addEventListener('click', function() {
if (state.createdArticles.length === 0) return;
const rows = [["Raqam", "Maqola nomi", "Yaratilgan sana", "Hajmi (bayt)"]];
state.createdArticles.forEach(function(a, i) {
rows.push([i + 1, `"${a.title.replace(/"/g, '""')}"`, a.timestamp, a.size || 0]);
});
const csvContent = "data:text/csv;charset=utf-8," + rows.map(function(e) { return e.join(","); }).join("\n");
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", `ziyosfera_maqolalar_${state.currentUser.name}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
// ========================================================================
// FORMATTERS
// ========================================================================
function formatDateUz(d) {
return `${d.getDate()}-${MONTH_NAMES_UZ[d.getMonth()].toLowerCase()}, ${d.getFullYear()}`;
}
function formatDateTimeUz(d) {
const day = d.getDate();
const month = MONTH_NAMES_UZ[d.getMonth()].toLowerCase();
const year = d.getFullYear();
const hours = String(d.getHours()).padStart(2, '0');
const mins = String(d.getMinutes()).padStart(2, '0');
return `${day}-${month}, ${year} ${hours}:${mins}`;
}
function escapeHtml(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
}
})(window, window.jQuery || window.$, window.mediaWiki || window.mw || {});