User:Chatsven/NewcomerDashboard.js
外观
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
//一个可以替换维基新手主页为自定义影响力仪表盘的脚本。
//反馈:[[User talk:Chatsven/NewcomerDashboard.js]]
//------------------------------------------------
(function () {
'use strict';
const DASHBOARD_ID = 'csn-homepage-preview-dashboard';
const STYLE_ID = 'csn-homepage-preview-dashboard-style-v81';
const RECENT_EDIT_LIMIT = 11;
const FAST_CONTRIBUTION_LIMIT = 500;
const TOP_VIEW_LIMIT = 6;
const VIEW_CANDIDATE_LIMIT = Infinity;
const MAX_CONTRIBUTIONS_TO_LOAD = 50000;
const PAGEVIEW_CONCURRENCY = 24;
const PAGEVIEWS_EARLIEST = new Date(2015, 6, 1);
const PAGEVIEWS_INITIAL_END_LAG_DAYS = 2;
const PAGEVIEWS_MAX_END_LAG_DAYS = 7;
const PAGEVIEWS_AGENT_PRIORITY = ['all-agents', 'user'];
const CHART_LINE_ANIMATION_MS = 3600;
const CHART_AREA_FADE_MS = 320;
// 总览渐变不要等折线完全跑完;在折线后段提前淡入,避免 PC 端观感过慢。
const CHART_AREA_FADE_DELAY_MS = 2280;
const TOP_PAGE_FRAME_DELAY_MS = 620;
const VIEWS_COMPACT_STEP_DELAY_MS = 560;
const VIEWS_COMPACT_STEP_ANIMATION_MS = 520;
const VIEWS_COMPACT_UNIT_ENTER_DELAY_MS = 720;
const VIEWS_COMPACT_FINAL_SETTLE_MS = 760;
const VIEWS_COMPACT_UNIT_ENTER_ANIMATION_MS = 680;
const VIEWS_PLAIN_FINAL_SETTLE_MS = 1580;
const METRIC_ROLL_FINAL_SETTLE_MS = 1580;
// v73: 累计浏览量的单字符翻槽动画时长与总编辑数一致,但连续步进不再一格等 900ms。
const ROLLING_SLOT_SETTLE_MS = 1520;
const PAGEVIEW_CACHE_KEY_PREFIX = 'csn-dashboard-pageviews-v1:';
const PAGEVIEW_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
let activityResizeObserver = null;
let dashboardOverflowResizeObserver = null;
let totalEditDisplayMode = 'total';
let totalEditAllCount = 0;
let totalEditMainNamespaceCount = 0;
let totalEditToggleToken = 0;
let viewsDisplayMode = 'compact';
let totalViewsRawCount = 0;
let viewsToggleToken = 0;
let recentEditPool = [];
let recentEditPageIndex = 0;
let recentEditPoolComplete = false;
let recentEditWheelInstalled = false;
let recentEditPageAnimating = false;
let recentEditWheelLockedUntil = 0;
let pendingRecentEditPoolRefresh = false;
hardPrehideOriginalHomepage();
prehideOriginalHomepage();
mw.loader.using(['mediawiki.api', 'mediawiki.util'], function () {
if (!isHomepage()) {
return;
}
installStyles();
setPageHeading();
replaceHomepage();
loadDashboardData();
});
function hardPrehideOriginalHomepage() {
try {
const href = location.href || '';
const path = location.pathname || '';
const likelyHomepage = /Special:Homepage|特殊:新手主页|Special:%E9%A6%96%E9%A1%B5/i.test(href) || /Special:Homepage/i.test(path);
if (!likelyHomepage) {
return;
}
document.documentElement.classList.add('csn-dashboard-prehide');
const css = [
'html.csn-dashboard-prehide body{background:#fff!important;}',
'html.csn-dashboard-prehide #mw-content-text,',
'html.csn-dashboard-prehide #bodyContent .mw-body-content,',
'html.csn-dashboard-prehide .growthexperiments-homepage-container,',
'html.csn-dashboard-prehide [data-mw-ve-target-container],',
'html.csn-dashboard-prehide .mw-parser-output{',
'opacity:0!important;',
'visibility:hidden!important;',
'background:#fff!important;',
'}'
].join('');
let style = document.getElementById('csn-dashboard-hard-prehide-style');
if (!style) {
style = document.createElement('style');
style.id = 'csn-dashboard-hard-prehide-style';
style.textContent = css;
if (document.head) {
document.head.appendChild(style);
} else {
document.documentElement.appendChild(style);
}
}
} catch (e) {}
}
function prehideOriginalHomepage() {
try {
const href = location.href || '';
const path = location.pathname || '';
if (/Special:Homepage|特殊:新手主页|Special:%E9%A6%96%E9%A1%B5|Special:Homepage/i.test(href) || /Special:Homepage/i.test(path)) {
document.documentElement.classList.add('csn-dashboard-prehide');
if (!document.getElementById('csn-dashboard-prehide-style')) {
const style = document.createElement('style');
style.id = 'csn-dashboard-prehide-style';
style.textContent = 'html.csn-dashboard-prehide body{background:#fff!important;}html.csn-dashboard-prehide #mw-content-text,html.csn-dashboard-prehide #bodyContent .mw-body-content{opacity:0!important;visibility:hidden!important;background:#fff!important;}@media screen{html.skin-theme-clientpref-night.csn-dashboard-prehide body{background:#0b0f14!important;}html.skin-theme-clientpref-night.csn-dashboard-prehide #mw-content-text,html.skin-theme-clientpref-night.csn-dashboard-prehide #bodyContent .mw-body-content{background:#0b0f14!important;}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os.csn-dashboard-prehide body{background:#0b0f14!important;}html.skin-theme-clientpref-os.csn-dashboard-prehide #mw-content-text,html.skin-theme-clientpref-os.csn-dashboard-prehide #bodyContent .mw-body-content{background:#0b0f14!important;}}';
document.head.appendChild(style);
}
}
} catch (e) {}
}
function isHomepage() {
const canonicalSpecial = mw.config.get('wgCanonicalSpecialPageName');
const pageName = mw.config.get('wgPageName') || '';
const title = document.title || '';
return canonicalSpecial === 'Homepage' ||
pageName === 'Special:Homepage' ||
pageName === '特殊:新手主页' ||
pageName === 'Special:新手主页' ||
/新手主页|新手主頁|Homepage/.test(title);
}
function installStyles() {
Array.from(document.querySelectorAll('style[id^="csn-homepage-preview-dashboard-style"]')).forEach(function (styleNode) {
styleNode.remove();
});
const style = document.createElement('style');
style.id = STYLE_ID;
style.textContent = `
.mw-indicators,
.catlinks {
display: none !important;
}
#firstHeading {
display: block !important;
margin: 0 0 0.25em 0 !important;
padding: 0 !important;
color: rgba(0, 0, 0, 0.88) !important;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif !important;
font-size: 1.8em !important;
font-weight: 700 !important;
line-height: 1.2 !important;
border-bottom: 0 !important;
}
#bodyContent,
#mw-content-text,
.mw-body-content {
max-width: none !important;
}
#${DASHBOARD_ID},
#${DASHBOARD_ID} * {
box-sizing: border-box;
-webkit-user-select: none;
user-select: none;
}
#${DASHBOARD_ID} {
width: 100%;
-webkit-touch-callout: none;
min-height: calc(100vh - 160px);
padding: 22.5px;
background: transparent;
color: rgba(0, 0, 0, 0.88);
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif;
scrollbar-width: none;
-ms-overflow-style: none;
}
#${DASHBOARD_ID}.csn-dashboard-entering {
opacity: 0;
visibility: hidden;
pointer-events: none;
transform: translateY(8px);
}
#${DASHBOARD_ID}.csn-dashboard-ready {
opacity: 1;
visibility: visible;
pointer-events: auto;
transform: translateY(0);
transition:
opacity 0.28s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.28s cubic-bezier(0.16, 1, 0.3, 1),
visibility 0s linear 0s;
}
#${DASHBOARD_ID} a {
color: #000000 !important;
-webkit-user-drag: none;
user-drag: none;
}
#${DASHBOARD_ID} img,
#${DASHBOARD_ID} svg {
-webkit-user-drag: none;
user-drag: none;
}
#${DASHBOARD_ID}::-webkit-scrollbar,
#${DASHBOARD_ID} *::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
#${DASHBOARD_ID}.csn-dashboard-overflow-scaled {
overflow-x: hidden;
max-width: 100vw;
}
.csn-shell {
width: 100%;
max-width: none;
margin: 0;
transform-origin: top left;
display: grid;
grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.42fr) minmax(0, 1fr);
grid-template-rows: 356px auto 294px 455px;
grid-template-areas:
"overview overview overview"
"activity activity activity"
"total views recent"
"top top recent";
gap: 22.5px;
align-items: stretch;
}
.csn-card {
background: #ffffff;
border-radius: 24.3px;
overflow: hidden;
border: 0;
box-shadow: 0 3.5px 45.1px rgba(0, 0, 0, 0.06);
}
.csn-pad {
padding: 22.5px;
}
.csn-overview {
grid-area: overview;
padding: 22.5px;
display: flex;
flex-direction: column;
}
.csn-total-card {
grid-area: total;
display: flex;
flex-direction: column;
overflow: visible;
cursor: pointer;
touch-action: manipulation;
transform-origin: center center;
transition:
transform 0.18s cubic-bezier(0.20, 0, 0.13, 1),
filter 0.18s cubic-bezier(0.20, 0, 0.13, 1);
will-change: transform, filter;
}
.csn-total-card.csn-total-card-pressed {
transform: scale(0.965);
filter: brightness(0.985);
}
.csn-total-card.csn-total-card-bounce {
animation: csn-total-card-bounce 0.46s cubic-bezier(0.20, 0, 0.13, 1) both;
}
.csn-total-card .csn-title {
transition:
opacity 0.16s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.16s cubic-bezier(0.16, 1, 0.3, 1),
filter 0.16s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-total-card .csn-title.csn-title-swapping {
opacity: 0.36;
transform: translateY(-2px);
filter: blur(3px);
}
@keyframes csn-total-card-bounce {
0% {
transform: scale(0.965);
}
54% {
transform: scale(1.018);
}
100% {
transform: scale(1);
}
}
.csn-views-card {
grid-area: views;
display: flex;
flex-direction: column;
overflow: visible;
cursor: pointer;
touch-action: manipulation;
transform-origin: center center;
transition:
transform 0.18s cubic-bezier(0.20, 0, 0.13, 1),
filter 0.18s cubic-bezier(0.20, 0, 0.13, 1);
will-change: transform, filter;
}
.csn-views-card.csn-views-card-pressed {
transform: scale(0.965);
filter: brightness(0.985);
}
.csn-views-card.csn-views-card-bounce {
animation: csn-total-card-bounce 0.46s cubic-bezier(0.20, 0, 0.13, 1) both;
}
.csn-recent-card {
grid-area: recent;
min-height: 771.5px;
}
.csn-recent-head {
position: relative;
width: 100%;
min-height: 32px;
}
.csn-recent-head .csn-title {
padding-right: 46px;
}
.csn-recent-page-reset {
position: absolute;
right: 0;
top: -2px;
width: 32px;
height: 32px;
margin: 0;
padding: 0;
border: 0;
border-radius: 999px;
background: #F6F6F6;
box-shadow: none;
appearance: none;
-webkit-appearance: none;
cursor: pointer;
opacity: 0;
pointer-events: none;
transform: scale(0.82);
transition:
opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.28s cubic-bezier(0.20, 0, 0.13, 1);
-webkit-tap-highlight-color: transparent;
outline: none;
}
.csn-recent-page-reset::before {
content: "";
position: absolute;
left: 50%;
top: 50%;
width: 9px;
height: 9px;
border-left: 2px solid rgba(16, 20, 24, 0.72);
border-top: 2px solid rgba(16, 20, 24, 0.72);
border-radius: 1px 0 0 0;
transform: translate(-50%, -34%) rotate(45deg);
}
.csn-recent-page-reset.csn-recent-page-reset-visible {
opacity: 1;
pointer-events: auto;
transform: scale(1);
}
.csn-recent-page-reset:active,
.csn-recent-page-reset.csn-recent-page-reset-pressed {
opacity: 1;
transform: scale(1.28);
}
.csn-recent-page-reset.csn-recent-page-reset-pop {
opacity: 1;
pointer-events: auto;
animation: csn-recent-page-reset-pop 0.56s cubic-bezier(0.20, 0, 0.13, 1) both;
}
@keyframes csn-recent-page-reset-pop {
0% {
transform: scale(1);
}
24% {
transform: scale(1.24);
}
52% {
transform: scale(1.035);
}
70% {
transform: scale(0.992);
}
86% {
transform: scale(1.008);
}
100% {
transform: scale(1);
}
}
.csn-top-card {
grid-area: top;
overflow: visible;
}
.csn-activity-card {
grid-area: activity;
position: relative;
padding: 22.5px;
display: flex;
flex-direction: column;
min-height: 0;
overflow: visible;
}
.csn-activity-head {
position: relative;
display: block;
width: 100%;
min-height: 27px;
opacity: 0;
transform: translateY(4px);
transition:
opacity 0.38s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.38s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-activity-head .csn-title {
padding-right: 118px;
}
#${DASHBOARD_ID}.csn-dashboard-ready .csn-activity-head {
opacity: 1;
transform: translateY(0);
}
.csn-activity-box {
--csn-activity-cell-size: 12px;
--csn-activity-gap: 4px;
--csn-activity-week-count: 53;
position: relative;
margin-top: 22.5px;
width: 100%;
overflow: visible;
border-radius: 15.6px;
padding: 0;
}
.csn-activity-board {
display: grid;
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto;
column-gap: 0;
align-items: start;
}
.csn-activity-month-row {
display: grid;
grid-template-columns: repeat(var(--csn-activity-week-count), var(--csn-activity-cell-size));
grid-auto-rows: 18px;
gap: var(--csn-activity-gap);
width: max-content;
min-width: 100%;
color: rgba(0, 0, 0, 0.46);
font-size: 11.2px;
line-height: 18px;
font-weight: 600;
white-space: nowrap;
user-select: none;
}
.csn-activity-month-label {
overflow: visible;
text-overflow: clip;
}
.csn-activity-month-label-last {
text-align: right;
}
.csn-activity-scroll {
grid-column: 1;
grid-row: 1;
width: 100%;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none;
-ms-overflow-style: none;
padding-right: 22px;
padding-bottom: 0;
}
.csn-activity-scroll::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
.csn-activity-grid {
margin-top: 4px;
display: grid;
grid-auto-flow: column;
grid-template-rows: repeat(7, var(--csn-activity-cell-size));
grid-auto-columns: var(--csn-activity-cell-size);
gap: var(--csn-activity-gap);
width: max-content;
min-width: 100%;
align-items: center;
}
.csn-activity-cell {
display: block;
position: relative;
width: var(--csn-activity-cell-size);
height: var(--csn-activity-cell-size);
aspect-ratio: 1 / 1;
border-radius: 2px;
background: #eff4ff;
border: 0;
padding: 0;
cursor: default;
outline: 1px solid rgba(47, 111, 218, 0.08);
outline-offset: -1px;
transition:
background-color 0.20s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.16s cubic-bezier(0.16, 1, 0.3, 1),
opacity 0.20s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-activity-cell:hover {
transform: scale(1.18);
z-index: 2;
}
.csn-activity-level-0 {
background: #eff4ff;
}
.csn-activity-future {
visibility: hidden;
pointer-events: none;
}
.csn-activity-outside-year {
visibility: hidden;
pointer-events: none;
}
.csn-activity-outside-year:hover {
transform: none;
}
.csn-activity-level-1 {
background: #d8e8ff;
}
.csn-activity-level-2 {
background: #a8ccff;
}
.csn-activity-level-3 {
background: #6fa5f5;
}
.csn-activity-level-4 {
background: #2F6FDA;
}
.csn-activity-level-5 {
background: #1f54b5;
}
.csn-activity-legend {
position: absolute;
top: 50%;
right: 0;
display: inline-flex;
align-items: center;
gap: 5px;
flex: 0 0 auto;
white-space: nowrap;
color: rgba(0, 0, 0, 0.46);
font-size: 12px;
line-height: 1;
font-weight: 600;
transform: translateY(-50%);
}
.csn-activity-legend-cell {
width: 10px;
height: 10px;
border-radius: 2px;
outline: 1px solid rgba(47, 111, 218, 0.08);
outline-offset: -1px;
}
.csn-activity-legend-cell.csn-activity-level-0 {
background: #eff4ff;
}
.csn-activity-tooltip {
position: absolute;
left: 0;
top: 0;
z-index: 8;
display: block;
min-width: 132px;
box-sizing: border-box;
padding: 9px 11px;
border-radius: 4px;
background: rgba(40, 40, 40, 0.72);
color: #ffffff;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif;
font-size: 13px;
font-weight: 700;
line-height: 1.35;
pointer-events: none;
white-space: nowrap;
box-shadow: none;
opacity: 0;
visibility: hidden;
will-change: transform, opacity;
transition:
opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1),
visibility 0s linear 0.22s;
}
.csn-activity-tooltip.csn-activity-tooltip-visible {
opacity: 1;
visibility: visible;
transition:
opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1),
visibility 0s linear 0s;
}
.csn-activity-tooltip-date,
.csn-activity-tooltip-line {
display: block;
}
.csn-activity-tooltip-date {
margin-bottom: 3px;
}
.csn-title {
margin: 0;
padding: 0;
font-size: 23.4px;
line-height: 1.15;
font-weight: 700;
letter-spacing: 0;
color: rgba(0, 0, 0, 0.88);
mix-blend-mode: plus-darker;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif;
}
.csn-stat-body {
flex: 1 1 auto;
min-height: 0;
min-width: 0;
display: flex;
align-items: center;
justify-content: center;
overflow: visible;
padding: 0 2px;
}
.csn-overview .csn-title {
font-size: 28.6px;
font-weight: 700;
}
.csn-chart-box {
position: relative;
margin-top: 22.5px;
flex: 1 1 auto;
min-height: 0;
width: 100%;
border-radius: 15.6px;
background: #f5f8ff;
overflow: hidden;
cursor: default;
touch-action: none;
}
.csn-chart-box svg {
display: block;
width: 100%;
height: 100%;
pointer-events: none;
}
.csn-chart-area-path {
opacity: 0;
transform: translateY(2px);
transition:
opacity 0.32s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.32s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-chart-area-path.csn-chart-area-visible {
opacity: 1;
transform: translateY(0);
}
.csn-chart-line-path {
stroke-dasharray: var(--csn-chart-path-length, 0);
stroke-dashoffset: var(--csn-chart-path-length, 0);
animation: csn-chart-draw 3.60s cubic-bezier(0.37, 0, 0.13, 1) forwards;
}
@keyframes csn-chart-draw {
to {
stroke-dashoffset: 0;
}
}
.csn-chart-hover-dot {
position: absolute;
left: 0;
top: 0;
z-index: 5;
width: 11px;
height: 11px;
margin-left: -5.5px;
margin-top: -5.5px;
border-radius: 999px;
background: #ffffff;
border: 2px solid #2f6fdb;
opacity: 0;
pointer-events: none;
will-change: transform, opacity;
transition: opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-chart-hover-dot.csn-chart-hover-dot-visible {
opacity: 1;
}
.csn-chart-tooltip {
position: absolute;
left: 0;
top: 0;
z-index: 6;
display: block;
min-width: 148px;
box-sizing: border-box;
padding: 9px 11px;
border-radius: 4px;
background: rgba(40, 40, 40, 0.72);
color: #ffffff;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif;
font-size: 13px;
font-weight: 700;
line-height: 1.35;
pointer-events: none;
white-space: nowrap;
box-shadow: none;
opacity: 0;
visibility: hidden;
will-change: transform, opacity;
transition:
opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1),
visibility 0s linear 0.22s;
}
.csn-chart-tooltip.csn-chart-tooltip-visible {
opacity: 1;
visibility: visible;
transition:
opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1),
visibility 0s linear 0s;
}
.csn-chart-tooltip-date {
display: block;
margin-bottom: 3px;
}
.csn-chart-tooltip-line {
display: block;
}
.csn-big-number {
margin: 0;
padding: 0;
font-size: 65px;
line-height: 1;
font-weight: 700;
letter-spacing: -0.06em;
color: #000000;
font-variant-numeric: tabular-nums;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif;
mix-blend-mode: plus-darker;
text-align: center;
white-space: nowrap;
min-width: 0;
max-width: none;
overflow: visible;
isolation: isolate;
will-change: transform, opacity, filter;
transition:
transform 0.22s cubic-bezier(0.16, 1, 0.3, 1),
opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1),
filter 0.22s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-big-number.csn-number-changing {
transform: none;
opacity: 1;
filter: none;
}
.csn-number-wheel {
display: inline-flex;
align-items: center;
justify-content: center;
white-space: nowrap;
font-variant-numeric: tabular-nums;
gap: 0;
max-width: none;
padding-left: 0;
padding-right: 0;
transform-origin: center center;
transform: translateZ(0);
}
.csn-number-slot {
position: relative;
display: inline-block;
width: 0.66em;
height: 1.18em;
overflow: hidden;
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.18) 7%, #000 22%, #000 78%, rgba(0, 0, 0, 0.18) 93%, transparent 100%);
mask-image: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.18) 7%, #000 22%, #000 78%, rgba(0, 0, 0, 0.18) 93%, transparent 100%);
-webkit-mask-size: 100% 100%;
mask-size: 100% 100%;
vertical-align: top;
flex: 0 0 auto;
}
.csn-number-slot.csn-number-comma {
width: 0.32em;
}
.csn-number-slot.csn-number-suffix {
width: 0.64em;
}
.csn-big-number .csn-number-slot {
width: 0.68em;
}
.csn-big-number .csn-number-slot.csn-number-comma {
width: 0.34em;
}
.csn-big-number .csn-number-slot.csn-number-suffix {
width: 0.78em;
}
.csn-view-count .csn-number-slot {
width: 0.62em;
}
.csn-view-count .csn-number-slot.csn-number-comma {
width: 0.34em;
}
.csn-number-strip {
position: absolute;
left: 50%;
top: 0.08em;
width: 100%;
will-change: transform, filter, opacity;
filter: blur(0);
transform: translate(-50%, 0);
transition:
transform 1.08s cubic-bezier(0.16, 1, 0.3, 1),
filter 1.08s cubic-bezier(0.16, 1, 0.3, 1),
opacity 1.08s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-number-slot[data-changed="1"].csn-number-rolling .csn-number-strip {
animation: csn-number-motion-blur 1.08s cubic-bezier(0.16, 1, 0.3, 1) both;
animation-delay: var(--csn-slot-delay, 0ms);
}
.csn-number-slot[data-changed="1"].csn-number-settled .csn-number-strip,
.csn-number-slot[data-changed="0"] .csn-number-strip {
filter: blur(0);
opacity: 1;
}
@keyframes csn-number-motion-blur {
0% {
filter: blur(0);
opacity: 1;
}
16% {
filter: blur(3.8px);
opacity: 0.42;
}
48% {
filter: blur(2.4px);
opacity: 0.62;
}
76% {
filter: blur(0.95px);
opacity: 0.88;
}
100% {
filter: blur(0);
opacity: 1;
}
}
.csn-number-strip span {
display: block;
height: 1em;
line-height: 1;
text-align: center;
}
.csn-step-number {
display: inline-flex;
align-items: center;
justify-content: center;
white-space: nowrap;
font-variant-numeric: tabular-nums;
gap: 0;
padding-left: 0.32em;
padding-right: 0.32em;
transform: translateZ(0);
}
.csn-step-char {
position: relative;
display: inline-block;
width: 0.68em;
height: 1.18em;
overflow: hidden;
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.18) 7%, #000 22%, #000 78%, rgba(0, 0, 0, 0.18) 93%, transparent 100%);
mask-image: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.18) 7%, #000 22%, #000 78%, rgba(0, 0, 0, 0.18) 93%, transparent 100%);
-webkit-mask-size: 100% 100%;
mask-size: 100% 100%;
vertical-align: top;
text-align: center;
flex: 0 0 auto;
transform: translateZ(0);
}
.csn-step-char.csn-step-char-dot {
width: 0.30em;
}
.csn-step-char.csn-step-char-comma {
width: 0.34em;
}
.csn-step-char.csn-step-char-suffix {
width: 0.84em;
}
.csn-step-char-track {
position: absolute;
left: 50%;
top: 0.08em;
width: 100%;
transform: translate(-50%, 0);
will-change: transform, filter, opacity;
}
.csn-step-char-track span {
display: block;
height: 1em;
line-height: 1;
text-align: center;
}
.csn-step-char-changing .csn-step-char-track {
animation: csn-step-char-roll 0.62s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing .csn-step-char-track {
animation-duration: 0.84s;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing.csn-step-char-suffix .csn-step-char-track {
animation-duration: 1.08s;
}
@keyframes csn-step-char-roll {
0% {
transform: translate(-50%, 0);
filter: blur(0);
opacity: 1;
}
18% {
filter: blur(4.2px);
opacity: 0.38;
}
48% {
filter: blur(2.5px);
opacity: 0.62;
}
72% {
filter: blur(1.05px);
opacity: 0.86;
}
100% {
transform: translate(-50%, -1em);
filter: blur(0);
opacity: 1;
}
}
.csn-views-number {
position: relative;
display: block;
width: 100%;
min-height: 1.42em;
font-size: 65px;
letter-spacing: -0.06em;
max-width: 100%;
min-width: 0;
overflow: visible;
transform-origin: center center;
white-space: nowrap;
text-align: center;
padding: 0;
transform: translateZ(0);
}
.csn-views-number .csn-step-number {
position: absolute;
left: 50%;
top: 50%;
width: max-content;
max-width: none;
margin: 0;
justify-content: center;
transform: translate(-50%, -50%);
transform-origin: center center;
}
.csn-views-morph-stage {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
white-space: nowrap;
overflow: visible;
transform: translateZ(0);
}
.csn-views-morph-text {
position: absolute;
left: 50%;
top: 50%;
display: block;
width: max-content;
max-width: none;
line-height: 1;
text-align: center;
opacity: 1;
filter: blur(0);
transform: translate3d(-50%, -50%, 0) scale(1);
transform-origin: center center;
backface-visibility: hidden;
will-change: opacity, transform, filter;
}
.csn-views-morph-stage.csn-views-morph-out .csn-views-morph-text {
animation: csn-views-morph-out 0.18s cubic-bezier(0.4, 0, 1, 1) both;
}
.csn-views-morph-stage.csn-views-morph-in .csn-views-morph-text {
animation: csn-views-morph-in 0.34s cubic-bezier(0.20, 0, 0.13, 1) both;
}
@keyframes csn-views-morph-out {
0% {
opacity: 1;
filter: blur(0);
transform: translate3d(-50%, -50%, 0) scale(1);
}
100% {
opacity: 0.32;
filter: blur(2px);
transform: translate3d(-50%, -50%, 0) scale(0.985);
}
}
@keyframes csn-views-morph-in {
0% {
opacity: 0.28;
filter: blur(2px);
transform: translate3d(-50%, -50%, 0) scale(1.012);
}
58% {
opacity: 1;
filter: blur(0.25px);
transform: translate3d(-50%, -50%, 0) scale(1.004);
}
100% {
opacity: 1;
filter: blur(0);
transform: translate3d(-50%, -50%, 0) scale(1);
}
}
.csn-total-card,
.csn-views-card {
overflow: visible;
}
.csn-total-card .csn-stat-body,
.csn-views-card .csn-stat-body {
display: contents;
overflow: visible;
padding: 0;
}
.csn-total-card .csn-big-number,
.csn-views-card .csn-big-number {
align-self: center;
margin-top: auto;
margin-bottom: auto;
max-width: none;
overflow: visible;
}
.csn-views-card .csn-big-number {
align-self: stretch;
}
.csn-total-card .csn-big-number {
font-size: 65px !important;
letter-spacing: -0.06em !important;
padding: 0 !important;
}
.csn-total-card .csn-number-wheel {
padding-left: 0 !important;
padding-right: 0 !important;
}
.csn-total-card .csn-number-slot {
width: 0.56em;
height: 1.08em;
}
.csn-total-card .csn-number-slot.csn-number-comma {
width: 0.22em;
}
.csn-total-card .csn-number-slot.csn-number-suffix {
width: 0.56em;
}
.csn-total-card .csn-number-strip {
top: 0.04em;
}
/* v65:大数字改成双层淡入淡出翻动,不再让旧数字条带硬露出一截。 */
.csn-number-slot,
.csn-step-char {
overflow: hidden;
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.05) 5%, rgba(0, 0, 0, 0.42) 16%, #000 34%, #000 66%, rgba(0, 0, 0, 0.42) 84%, rgba(0, 0, 0, 0.05) 95%, transparent 100%);
mask-image: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.05) 5%, rgba(0, 0, 0, 0.42) 16%, #000 34%, #000 66%, rgba(0, 0, 0, 0.42) 84%, rgba(0, 0, 0, 0.05) 95%, transparent 100%);
}
.csn-big-number .csn-number-slot,
.csn-step-char {
height: 1.34em;
}
.csn-total-card .csn-number-slot {
height: 1.34em;
}
.csn-number-flip,
.csn-step-char-flip {
position: absolute;
left: 50%;
top: 50%;
display: block;
width: 100%;
height: 1em;
line-height: 1;
text-align: center;
transform: translate(-50%, -50%);
will-change: transform, opacity, filter;
pointer-events: none;
}
.csn-number-slot[data-changed="1"] .csn-number-strip,
.csn-step-char-changing .csn-step-char-track {
display: none;
}
.csn-number-slot[data-changed="1"].csn-number-rolling .csn-number-flip-from {
animation: csn-number-flip-from 1.12s cubic-bezier(0.16, 1, 0.3, 1) both;
animation-delay: var(--csn-slot-delay, 0ms);
}
.csn-number-slot[data-changed="1"].csn-number-rolling .csn-number-flip-to {
animation: csn-number-flip-to 1.12s cubic-bezier(0.16, 1, 0.3, 1) both;
animation-delay: var(--csn-slot-delay, 0ms);
}
.csn-number-slot[data-changed="1"].csn-number-settled .csn-number-flip-from {
opacity: 0;
filter: blur(7px);
transform: translate(-50%, -50%) translateY(-0.92em) scale(0.985);
}
.csn-number-slot[data-changed="1"].csn-number-settled .csn-number-flip-to {
opacity: 1;
filter: blur(0);
transform: translate(-50%, -50%);
}
.csn-step-char-changing .csn-step-char-from {
animation: csn-step-char-fade-from 0.66s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.csn-step-char-changing .csn-step-char-to {
animation: csn-step-char-fade-to 0.66s cubic-bezier(0.16, 1, 0.3, 1) both;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing .csn-step-char-from,
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing .csn-step-char-to {
animation-duration: 0.92s;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing.csn-step-char-suffix .csn-step-char-from,
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing.csn-step-char-suffix .csn-step-char-to {
animation-duration: 1.18s;
}
@keyframes csn-number-flip-from {
0% {
opacity: 1;
filter: blur(0);
transform: translate(-50%, -50%) translateY(0) scale(1);
}
22% {
opacity: 0.52;
filter: blur(5.2px);
}
58% {
opacity: 0.16;
filter: blur(7.2px);
transform: translate(-50%, -50%) translateY(-0.62em) scale(0.988);
}
100% {
opacity: 0;
filter: blur(8px);
transform: translate(-50%, -50%) translateY(-0.96em) scale(0.982);
}
}
@keyframes csn-number-flip-to {
0% {
opacity: 0;
filter: blur(8px);
transform: translate(-50%, -50%) translateY(0.96em) scale(0.982);
}
32% {
opacity: 0.18;
filter: blur(7px);
}
68% {
opacity: 0.82;
filter: blur(2.4px);
transform: translate(-50%, -50%) translateY(0.12em) scale(1.003);
}
100% {
opacity: 1;
filter: blur(0);
transform: translate(-50%, -50%) translateY(0) scale(1);
}
}
@keyframes csn-step-char-fade-from {
0% {
opacity: 1;
filter: blur(0);
transform: translate(-50%, -50%) translateY(0) scale(1);
}
26% {
opacity: 0.50;
filter: blur(5px);
}
100% {
opacity: 0;
filter: blur(7px);
transform: translate(-50%, -50%) translateY(-0.92em) scale(0.985);
}
}
@keyframes csn-step-char-fade-to {
0% {
opacity: 0;
filter: blur(7px);
transform: translate(-50%, -50%) translateY(0.92em) scale(0.985);
}
44% {
opacity: 0.40;
filter: blur(5px);
}
100% {
opacity: 1;
filter: blur(0);
transform: translate(-50%, -50%) translateY(0) scale(1);
}
}
.csn-total-card .csn-number-slot[data-changed="1"],
.csn-views-card .csn-step-char-changing,
.csn-views-card .csn-number-slot[data-changed="1"] {
opacity: 0.999;
}
/* v66:取消上下渐变遮罩和硬裁切。数字槽只占位,旧/新字符用透明度和模糊过渡。 */
.csn-number-slot,
.csn-step-char,
.csn-big-number .csn-number-slot,
.csn-total-card .csn-number-slot,
.csn-views-card .csn-number-slot,
.csn-views-card .csn-step-char {
overflow: visible !important;
-webkit-mask-image: none !important;
mask-image: none !important;
height: 1.08em !important;
}
.csn-total-card .csn-number-slot { height: 1em !important; }
.csn-number-slot[data-changed="0"] .csn-number-strip,
.csn-step-char:not(.csn-step-char-changing) .csn-step-char-track {
top: 50% !important;
transform: translate(-50%, -50%) !important;
}
.csn-number-flip,
.csn-step-char-flip {
top: 50% !important;
height: 1em !important;
line-height: 1 !important;
overflow: visible !important;
backface-visibility: hidden;
}
.csn-number-slot[data-changed="1"].csn-number-rolling .csn-number-flip-from {
animation-name: csn-number-soft-fade-from !important;
animation-duration: 1.18s !important;
}
.csn-number-slot[data-changed="1"].csn-number-rolling .csn-number-flip-to {
animation-name: csn-number-soft-fade-to !important;
animation-duration: 1.18s !important;
}
.csn-step-char-changing .csn-step-char-from {
animation-name: csn-step-soft-fade-from !important;
animation-duration: 0.74s !important;
}
.csn-step-char-changing .csn-step-char-to {
animation-name: csn-step-soft-fade-to !important;
animation-duration: 0.74s !important;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing .csn-step-char-from,
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing .csn-step-char-to {
animation-duration: 1.02s !important;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing.csn-step-char-suffix .csn-step-char-from,
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing.csn-step-char-suffix .csn-step-char-to {
animation-duration: 1.26s !important;
}
@keyframes csn-number-soft-fade-from {
0% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
24% { opacity: 0.50; filter: blur(5.6px); transform: translate(-50%, -50%) translateY(-0.10em) scale(0.997); }
62% { opacity: 0.08; filter: blur(8.2px); transform: translate(-50%, -50%) translateY(-0.28em) scale(0.99); }
100% { opacity: 0; filter: blur(9px); transform: translate(-50%, -50%) translateY(-0.38em) scale(0.985); }
}
@keyframes csn-number-soft-fade-to {
0% { opacity: 0; filter: blur(9px); transform: translate(-50%, -50%) translateY(0.38em) scale(0.985); }
34% { opacity: 0.18; filter: blur(7.2px); transform: translate(-50%, -50%) translateY(0.22em) scale(0.99); }
72% { opacity: 0.92; filter: blur(1.8px); transform: translate(-50%, -50%) translateY(0.04em) scale(1.001); }
100% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
}
@keyframes csn-step-soft-fade-from {
0% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
28% { opacity: 0.48; filter: blur(5.2px); transform: translate(-50%, -50%) translateY(-0.10em) scale(0.997); }
100% { opacity: 0; filter: blur(8.2px); transform: translate(-50%, -50%) translateY(-0.34em) scale(0.987); }
}
@keyframes csn-step-soft-fade-to {
0% { opacity: 0; filter: blur(8.2px); transform: translate(-50%, -50%) translateY(0.34em) scale(0.987); }
46% { opacity: 0.42; filter: blur(5.4px); transform: translate(-50%, -50%) translateY(0.18em) scale(0.992); }
100% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
}
.csn-views-number[data-views-unit="K"],
.csn-views-number[data-views-unit="M"],
.csn-views-number[data-views-unit="B"] {
min-width: 0;
}
.csn-views-number.csn-views-number-changing {
animation: csn-views-number-change 0.34s cubic-bezier(0.16, 1, 0.3, 1) both;
}
@keyframes csn-views-number-change {
0% {
opacity: 0.72;
filter: blur(0.9px);
transform: translateY(4px) scale(0.992);
}
100% {
opacity: 1;
filter: blur(0);
transform: translateY(0) scale(1);
}
}
.csn-foot {
margin-top: 18.2px;
font-size: 15.6px;
line-height: 1.25;
font-weight: 700;
color: rgba(0, 0, 0, 0.50);
mix-blend-mode: plus-darker;
}
.csn-recent-list {
margin-top: 22.5px;
display: flex;
flex-direction: column;
gap: 17px;
}
.csn-recent-item {
display: grid;
grid-template-columns: minmax(0, 1fr) 58px;
gap: 10.4px;
align-items: start;
position: relative;
opacity: 0;
transform: translateY(-14px) scale(0.985);
filter: blur(0.7px);
overflow: visible;
will-change: transform, opacity, filter;
}
.csn-recent-main {
min-width: 0;
overflow: visible;
}
.csn-recent-item.csn-recent-pre-in {
opacity: 0;
transform: translateY(-14px) scale(0.985);
filter: blur(0.7px);
}
.csn-recent-item.csn-recent-stack-in {
animation: csn-recent-stack-in 0.72s cubic-bezier(0.16, 1, 0.3, 1) forwards;
animation-delay: var(--csn-recent-delay, 0ms);
}
.csn-recent-item.csn-recent-stack-settled {
opacity: 1;
transform: translateY(0) scale(1);
filter: blur(0);
overflow: visible;
}
@keyframes csn-recent-stack-in {
0% {
opacity: 0;
transform: translateY(-14px) scale(0.985);
filter: blur(0.9px);
}
58% {
opacity: 1;
transform: translateY(2px) scale(1.004);
filter: blur(0.18px);
}
100% {
opacity: 1;
transform: translateY(0) scale(1);
filter: blur(0);
}
}
.csn-recent-list.csn-recent-page-out-up {
animation: csn-recent-page-out-up 0.24s cubic-bezier(0.4, 0, 1, 1) both;
}
.csn-recent-list.csn-recent-page-out-down {
animation: csn-recent-page-out-down 0.24s cubic-bezier(0.4, 0, 1, 1) both;
}
.csn-recent-list.csn-recent-page-in-up {
animation: csn-recent-page-in-up 0.48s cubic-bezier(0.20, 0, 0.13, 1) both;
}
.csn-recent-list.csn-recent-page-in-down {
animation: csn-recent-page-in-down 0.48s cubic-bezier(0.20, 0, 0.13, 1) both;
}
.csn-recent-list.csn-recent-page-bounce-up {
animation: csn-recent-page-bounce-up 0.42s cubic-bezier(0.20, 0, 0.13, 1) both;
}
.csn-recent-list.csn-recent-page-bounce-down {
animation: csn-recent-page-bounce-down 0.42s cubic-bezier(0.20, 0, 0.13, 1) both;
}
@keyframes csn-recent-page-out-up {
0% { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
100% { opacity: 0; transform: translateY(-34px) scale(0.972); filter: blur(7px); }
}
@keyframes csn-recent-page-out-down {
0% { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
100% { opacity: 0; transform: translateY(34px) scale(0.972); filter: blur(7px); }
}
@keyframes csn-recent-page-in-up {
0% { opacity: 0; transform: translateY(38px) scale(0.982); filter: blur(7px); }
58% { opacity: 1; transform: translateY(-3px) scale(1.006); filter: blur(0.6px); }
100% { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
}
@keyframes csn-recent-page-in-down {
0% { opacity: 0; transform: translateY(-38px) scale(0.982); filter: blur(7px); }
58% { opacity: 1; transform: translateY(3px) scale(1.006); filter: blur(0.6px); }
100% { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
}
@keyframes csn-recent-page-bounce-up {
0% { transform: translateY(0) scale(1); filter: blur(0); }
38% { transform: translateY(-13px) scale(0.992); filter: blur(1.4px); }
100% { transform: translateY(0) scale(1); filter: blur(0); }
}
@keyframes csn-recent-page-bounce-down {
0% { transform: translateY(0) scale(1); filter: blur(0); }
38% { transform: translateY(13px) scale(0.992); filter: blur(1.4px); }
100% { transform: translateY(0) scale(1); filter: blur(0); }
}
.csn-page-link {
display: block;
color: #000000 !important;
text-decoration: none !important;
font-size: 17.3px;
line-height: 1.18;
font-weight: 700;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif;
}
.csn-summary {
margin-top: 5.2px;
color: rgba(0, 0, 0, 0.50);
font-size: 13.9px;
line-height: 1.2;
font-weight: 400;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.csn-side {
text-align: right;
font-size: 11px;
line-height: 1.15;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.csn-diff-pos {
color: #4f9b5c;
}
.csn-diff-neg {
color: #bd5555;
}
.csn-diff-zero {
color: rgba(0, 0, 0, 0.36);
}
.csn-time {
display: block;
margin-top: 10.4px;
color: rgba(0, 0, 0, 0.50);
}
.csn-top-list {
position: relative;
margin-top: 22.5px;
display: flex;
flex-direction: column;
gap: 22.5px;
}
.csn-top-name-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 15.6px;
margin-bottom: 7.8px;
}
.csn-top-name {
color: #000000 !important;
text-decoration: none !important;
font-size: 17.3px;
line-height: 1.18;
font-weight: 700;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro", "Segoe UI", sans-serif;
}
.csn-view-count {
flex: 0 0 auto;
color: #3366cc;
font-size: 13.9px;
line-height: 1;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.csn-top-item {
display: block;
width: 100%;
min-width: 0;
grid-column: 1 / -1;
opacity: 1;
transform: translateY(0) scale(1);
filter: blur(0);
will-change: transform, opacity, filter;
transition:
opacity 0.32s cubic-bezier(0.16, 1, 0.3, 1),
transform 0.58s cubic-bezier(0.16, 1, 0.3, 1),
filter 0.32s cubic-bezier(0.16, 1, 0.3, 1);
}
.csn-top-item.csn-top-enter {
opacity: 0;
filter: blur(1.1px);
transform: translateY(10px) scale(0.986);
}
.csn-top-item.csn-top-exit {
opacity: 0;
filter: blur(1.2px);
transform: translateY(-10px) scale(0.986);
}
.csn-top-item.csn-top-moving {
filter: blur(0);
}
.csn-top-item.csn-top-exit-floating {
position: absolute;
left: 0;
right: 0;
width: 100%;
pointer-events: none;
z-index: 2;
}
.csn-view-count {
min-width: 5.4ch;
text-align: right;
overflow: visible;
}
.csn-bar-track {
height: 6px;
width: 100%;
border-radius: 100px;
background: rgba(51, 102, 204, 0.16);
overflow: hidden;
}
.csn-bar {
display: block;
height: 100%;
width: 0;
border-radius: 100px;
background: #3366cc;
}
.csn-bar {
transition: width 0.44s cubic-bezier(0.16, 1, 0.3, 1);
}
/* v68:回到 Apple Watch 心率 App 风格的“单字符翻槽”。
不是整组数字 dissolve,也不再靠 mask 裁切;每个字符槽只保留占位,
旧字符上移 + 加重模糊 + 淡出,新字符从下方模糊淡入。 */
.csn-total-card,
.csn-views-card {
overflow: visible !important;
contain: none !important;
}
.csn-total-card .csn-stat-body,
.csn-views-card .csn-stat-body {
display: contents !important;
overflow: visible !important;
contain: none !important;
}
.csn-total-card .csn-big-number,
.csn-views-card .csn-big-number {
overflow: visible !important;
max-width: none !important;
line-height: 1 !important;
contain: none !important;
}
.csn-total-card .csn-big-number {
font-size: 65px !important;
letter-spacing: -0.06em !important;
padding: 0 !important;
}
.csn-number-wheel,
.csn-step-number {
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
white-space: nowrap !important;
gap: 0 !important;
padding: 0 !important;
overflow: visible !important;
transform: translateZ(0);
font-variant-numeric: tabular-nums;
}
.csn-number-slot,
.csn-step-char,
.csn-big-number .csn-number-slot,
.csn-big-number .csn-step-char,
.csn-total-card .csn-number-slot,
.csn-views-card .csn-number-slot,
.csn-views-card .csn-step-char {
position: relative !important;
display: inline-block !important;
flex: 0 0 auto !important;
width: 0.58em !important;
height: 1em !important;
line-height: 1 !important;
overflow: visible !important;
vertical-align: top !important;
text-align: center !important;
-webkit-mask-image: none !important;
mask-image: none !important;
-webkit-mask-size: auto !important;
mask-size: auto !important;
transform: translateZ(0);
}
.csn-number-slot.csn-number-comma,
.csn-step-char.csn-step-char-comma,
.csn-big-number .csn-number-slot.csn-number-comma,
.csn-big-number .csn-step-char.csn-step-char-comma,
.csn-total-card .csn-number-slot.csn-number-comma,
.csn-views-card .csn-step-char.csn-step-char-comma {
width: 0.25em !important;
}
.csn-step-char.csn-step-char-dot,
.csn-views-card .csn-step-char.csn-step-char-dot {
width: 0.32em !important;
}
.csn-number-slot.csn-number-suffix,
.csn-step-char.csn-step-char-suffix,
.csn-big-number .csn-number-slot.csn-number-suffix,
.csn-big-number .csn-step-char.csn-step-char-suffix,
.csn-total-card .csn-number-slot.csn-number-suffix,
.csn-views-card .csn-step-char.csn-step-char-suffix {
width: 0.72em !important;
}
.csn-number-strip,
.csn-step-char-track {
position: absolute !important;
left: 50% !important;
top: 50% !important;
width: 100% !important;
transform: translate(-50%, -50%) !important;
transition: none !important;
filter: blur(0) !important;
opacity: 1 !important;
overflow: visible !important;
}
.csn-number-strip span,
.csn-step-char-track span {
display: block !important;
height: 1em !important;
line-height: 1 !important;
text-align: center !important;
}
.csn-number-slot[data-changed="1"] .csn-number-strip,
.csn-step-char-changing .csn-step-char-track {
display: none !important;
}
.csn-number-flip,
.csn-step-char-flip {
position: absolute !important;
left: 50% !important;
top: 50% !important;
display: block !important;
width: 100% !important;
height: 1em !important;
line-height: 1 !important;
text-align: center !important;
overflow: visible !important;
transform: translate(-50%, -50%) translateY(0) scale(1);
will-change: transform, opacity, filter;
pointer-events: none;
backface-visibility: hidden;
transform-origin: center center;
}
.csn-number-slot[data-changed="1"].csn-number-rolling .csn-number-flip-from {
animation: csn-applewatch-slot-out 0.84s cubic-bezier(0.20, 0, 0.13, 1) both !important;
animation-delay: var(--csn-slot-delay, 0ms) !important;
}
.csn-number-slot[data-changed="1"].csn-number-rolling .csn-number-flip-to {
animation: csn-applewatch-slot-in 0.84s cubic-bezier(0.20, 0, 0.13, 1) both !important;
animation-delay: var(--csn-slot-delay, 0ms) !important;
}
.csn-step-char-changing .csn-step-char-from {
animation: csn-applewatch-step-out var(--csn-step-duration, 840ms) cubic-bezier(0.20, 0, 0.13, 1) both !important;
animation-delay: var(--csn-slot-delay, 0ms) !important;
}
.csn-step-char-changing .csn-step-char-to {
animation: csn-applewatch-step-in var(--csn-step-duration, 840ms) cubic-bezier(0.20, 0, 0.13, 1) both !important;
animation-delay: var(--csn-slot-delay, 0ms) !important;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing .csn-step-char-from,
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing .csn-step-char-to {
animation-duration: var(--csn-step-duration, 1240ms) !important;
}
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing.csn-step-char-suffix .csn-step-char-from,
.csn-step-number.csn-step-number-unit-enter .csn-step-char-changing.csn-step-char-suffix .csn-step-char-to {
animation-duration: var(--csn-step-duration, 840ms) !important;
}
.csn-number-slot[data-changed="1"].csn-number-settled .csn-number-flip-from {
opacity: 0 !important;
filter: blur(10px) !important;
transform: translate(-50%, -50%) translateY(-0.54em) scale(0.985) !important;
}
.csn-number-slot[data-changed="1"].csn-number-settled .csn-number-flip-to {
opacity: 1 !important;
filter: blur(0) !important;
transform: translate(-50%, -50%) translateY(0) scale(1) !important;
}
@keyframes csn-applewatch-slot-out {
0% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
24% { opacity: 0.64; filter: blur(4.8px); transform: translate(-50%, -50%) translateY(-0.10em) scale(0.997); }
58% { opacity: 0.18; filter: blur(9.5px); transform: translate(-50%, -50%) translateY(-0.38em) scale(0.988); }
100% { opacity: 0; filter: blur(12px); transform: translate(-50%, -50%) translateY(-0.58em) scale(0.982); }
}
@keyframes csn-applewatch-slot-in {
0% { opacity: 0; filter: blur(12px); transform: translate(-50%, -50%) translateY(0.58em) scale(0.982); }
34% { opacity: 0.24; filter: blur(8.8px); transform: translate(-50%, -50%) translateY(0.34em) scale(0.99); }
76% { opacity: 0.86; filter: blur(2px); transform: translate(-50%, -50%) translateY(0.04em) scale(1.002); }
100% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
}
@keyframes csn-applewatch-step-out {
0% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
28% { opacity: 0.58; filter: blur(4.8px); }
100% { opacity: 0; filter: blur(10px); transform: translate(-50%, -50%) translateY(-0.50em) scale(0.985); }
}
@keyframes csn-applewatch-step-in {
0% { opacity: 0; filter: blur(10px); transform: translate(-50%, -50%) translateY(0.50em) scale(0.985); }
48% { opacity: 0.42; filter: blur(6.2px); }
100% { opacity: 1; filter: blur(0); transform: translate(-50%, -50%) translateY(0) scale(1); }
}
.csn-total-card .csn-big-number,
.csn-views-card .csn-big-number,
.csn-views-number {
font-size: 65px !important;
letter-spacing: -0.06em !important;
padding-left: 0 !important;
padding-right: 0 !important;
min-width: 0 !important;
}
.csn-total-card .csn-number-wheel,
.csn-views-card .csn-step-number {
transform-origin: center center;
}
@media (max-width: 980px) {
.csn-total-card .csn-big-number,
.csn-views-card .csn-big-number,
.csn-views-number {
font-size: clamp(48px, 14vw, 65px) !important;
letter-spacing: -0.06em !important;
}
}
/* 深色模式:使用 MediaWiki/Vector 的 client preference 类。
强制深色:html.skin-theme-clientpref-night;自动模式:html.skin-theme-clientpref-os + prefers-color-scheme。 */
@media screen {
html.skin-theme-clientpref-night #${DASHBOARD_ID} {
color: rgba(239, 244, 255, 0.90);
}
html.skin-theme-clientpref-night #firstHeading {
color: rgba(239, 244, 255, 0.92) !important;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} a,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-page-link,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-top-name {
color: rgba(242, 246, 255, 0.94) !important;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-card {
background: #101418;
box-shadow: 0 3.5px 45.1px rgba(255, 255, 255, 0.055);
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-title,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-big-number,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-foot {
mix-blend-mode: normal;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-title,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-big-number {
color: rgba(242, 246, 255, 0.94);
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-foot,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-summary,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-time,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-month-row,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-legend {
color: rgba(224, 233, 255, 0.58);
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-diff-zero {
color: rgba(224, 233, 255, 0.38);
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-diff-pos {
color: #8ed69b;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-diff-neg {
color: #e17c84;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-chart-box {
background: #121821;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-chart-line-path,
html.skin-theme-clientpref-night #${DASHBOARD_ID} #csn-chart-line-path {
stroke: #88A3E7 !important;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} #csn-trend-fill stop:first-child {
stop-color: #88A3E7 !important;
stop-opacity: 0.18 !important;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} #csn-trend-fill stop:last-child {
stop-color: #88A3E7 !important;
stop-opacity: 0.015 !important;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-chart-hover-dot {
background: #101418;
border-color: #88A3E7;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-chart-tooltip,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-tooltip {
background: rgba(8, 12, 16, 0.92);
color: rgba(242, 246, 255, 0.96);
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-view-count {
color: #88A3E7;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-bar-track {
background: rgba(136, 163, 231, 0.18);
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-bar {
background: #88A3E7;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-cell,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-legend-cell {
outline-color: rgba(136, 163, 231, 0.14);
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-level-0,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-0 {
background: #172033;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-level-1,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-1 {
background: #23365a;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-level-2,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-2 {
background: #365a93;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-level-3,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-3 {
background: #5f7fd0;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-level-4,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-4 {
background: #88A3E7;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-activity-level-5 {
background: #B4C7FF;
}
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-top-item.csn-top-enter,
html.skin-theme-clientpref-night #${DASHBOARD_ID} .csn-top-item.csn-top-exit {
filter: blur(1.2px);
}
}
@media screen and (prefers-color-scheme: dark) {
html.skin-theme-clientpref-os #${DASHBOARD_ID} {
color: rgba(239, 244, 255, 0.90);
}
html.skin-theme-clientpref-os #firstHeading {
color: rgba(239, 244, 255, 0.92) !important;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} a,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-page-link,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-top-name {
color: rgba(242, 246, 255, 0.94) !important;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-card {
background: #101418;
box-shadow: 0 3.5px 45.1px rgba(255, 255, 255, 0.055);
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-title,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-big-number,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-foot {
mix-blend-mode: normal;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-title,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-big-number {
color: rgba(242, 246, 255, 0.94);
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-foot,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-summary,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-time,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-month-row,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-legend {
color: rgba(224, 233, 255, 0.58);
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-diff-zero {
color: rgba(224, 233, 255, 0.38);
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-diff-pos {
color: #8ed69b;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-diff-neg {
color: #e17c84;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-chart-box {
background: #121821;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-chart-line-path,
html.skin-theme-clientpref-os #${DASHBOARD_ID} #csn-chart-line-path {
stroke: #88A3E7 !important;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} #csn-trend-fill stop:first-child {
stop-color: #88A3E7 !important;
stop-opacity: 0.18 !important;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} #csn-trend-fill stop:last-child {
stop-color: #88A3E7 !important;
stop-opacity: 0.015 !important;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-chart-hover-dot {
background: #101418;
border-color: #88A3E7;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-chart-tooltip,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-tooltip {
background: rgba(8, 12, 16, 0.92);
color: rgba(242, 246, 255, 0.96);
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-view-count {
color: #88A3E7;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-bar-track {
background: rgba(136, 163, 231, 0.18);
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-bar {
background: #88A3E7;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-cell,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-legend-cell {
outline-color: rgba(136, 163, 231, 0.14);
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-level-0,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-0 {
background: #172033;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-level-1,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-1 {
background: #23365a;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-level-2,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-2 {
background: #365a93;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-level-3,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-3 {
background: #5f7fd0;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-level-4,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-legend-cell.csn-activity-level-4 {
background: #88A3E7;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-activity-level-5 {
background: #B4C7FF;
}
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-top-item.csn-top-enter,
html.skin-theme-clientpref-os #${DASHBOARD_ID} .csn-top-item.csn-top-exit {
filter: blur(1.2px);
}
}
@media (max-width: 1280px) {
.csn-shell {
grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.42fr) minmax(0, 1fr);
}
}
@media (max-width: 980px) {
.csn-shell {
width: 100%;
grid-template-columns: 1fr;
grid-template-rows: auto;
grid-template-areas:
"overview"
"activity"
"total"
"views"
"recent"
"top";
gap: 22.5px;
}
.csn-overview,
.csn-total-card,
.csn-views-card,
.csn-recent-card,
.csn-top-card,
.csn-activity-card {
grid-column: 1;
grid-row: auto;
min-height: auto;
}
.csn-overview {
min-height: 330px;
}
.csn-chart-box {
height: 240px;
}
.csn-activity-card {
min-height: 0;
padding-bottom: 22.5px;
}
.csn-activity-box {
--csn-activity-cell-size: 11px;
--csn-activity-gap: 4px;
overflow: visible;
padding-top: 0;
padding-bottom: 0;
}
.csn-activity-scroll {
scroll-snap-type: x proximity;
scroll-padding-left: 0;
-webkit-overflow-scrolling: touch;
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 0;
}
.csn-activity-month-row {
font-size: 10.5px;
}
.csn-activity-head {
min-height: 25px;
}
.csn-activity-head .csn-title {
padding-right: 118px;
}
}
/* 移动端:恢复统计数字与标题之间的真实布局间距。
之前 display: contents 会让 .csn-stat-body 不参与排版,导致标题和大数字之间的间距不可控。 */
@media (max-width: 980px) {
.csn-total-card .csn-stat-body,
.csn-views-card .csn-stat-body {
display: flex !important;
align-items: center !important;
justify-content: center !important;
width: 100% !important;
min-height: 72px !important;
margin-top: 22.5px !important;
margin-bottom: 18.2px !important;
padding: 0 !important;
overflow: visible !important;
contain: none !important;
}
.csn-total-card .csn-big-number,
.csn-views-card .csn-big-number {
align-self: center !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
.csn-total-card .csn-foot,
.csn-views-card .csn-foot {
margin-top: 0 !important;
}
}
`;
document.head.appendChild(style);
}
function setPageHeading() {
const heading = document.getElementById('firstHeading');
if (heading) {
heading.textContent = '总览';
}
const titleParts = document.title.split(' - ');
if (titleParts.length > 1) {
titleParts[0] = '总览';
document.title = titleParts.join(' - ');
} else {
document.title = '总览';
}
}
function replaceHomepage() {
const content = document.getElementById('mw-content-text') ||
document.querySelector('.mw-body-content') ||
document.getElementById('bodyContent');
if (!content) {
return;
}
// 只清空总览正文内容,不覆盖维基顶部导航栏、侧栏和页面操作菜单。
content.innerHTML = '';
const root = document.createElement('div');
root.id = DASHBOARD_ID;
root.className = 'csn-dashboard-entering';
root.innerHTML = `
<div class="csn-shell" aria-label="总览">
<div class="csn-card csn-overview">
<div class="csn-title">总览</div>
<div class="csn-chart-box" id="csn-chart-box"></div>
</div>
<div class="csn-card csn-activity-card">
<div class="csn-activity-head">
<div class="csn-title">编辑活跃</div>
<span class="csn-activity-legend" aria-hidden="true">
<span>少</span>
<span class="csn-activity-legend-cell csn-activity-level-0"></span>
<span class="csn-activity-legend-cell csn-activity-level-1"></span>
<span class="csn-activity-legend-cell csn-activity-level-2"></span>
<span class="csn-activity-legend-cell csn-activity-level-3"></span>
<span class="csn-activity-legend-cell csn-activity-level-4"></span>
<span>多</span>
</span>
</div>
<div class="csn-activity-box" id="csn-activity-box"></div>
</div>
<div class="csn-card csn-pad csn-total-card">
<div class="csn-title" id="csn-total-title">总编辑数</div>
<div class="csn-stat-body">
<div class="csn-big-number" id="csn-total-edits">0</div>
</div>
<div class="csn-foot" id="csn-total-date">截至XX月XX日</div>
</div>
<div class="csn-card csn-pad csn-views-card">
<div class="csn-title">累计浏览量</div>
<div class="csn-stat-body">
<div class="csn-big-number csn-views-number" id="csn-total-views">0</div>
</div>
<div class="csn-foot" id="csn-view-date">截至XX月XX日</div>
</div>
<div class="csn-card csn-pad csn-recent-card">
<div class="csn-recent-head">
<div class="csn-title">最近编辑</div>
<button type="button" class="csn-recent-page-reset" id="csn-recent-page-reset" aria-label="返回最近编辑第一页"></button>
</div>
<div class="csn-recent-list" id="csn-recent-list"></div>
</div>
<div class="csn-card csn-pad csn-top-card">
<div class="csn-title">浏览次数最多的页面</div>
<div class="csn-top-list" id="csn-top-list"></div>
</div>
</div>
`;
content.appendChild(root);
document.documentElement.classList.remove('csn-dashboard-prehide');
document.documentElement.classList.add('csn-dashboard-ready');
const hardPrehideStyle = document.getElementById('csn-dashboard-hard-prehide-style');
if (hardPrehideStyle) {
hardPrehideStyle.remove();
}
installNumberResizeFitter();
installDashboardOverflowScaler();
installDashboardInteractionGuards();
installTotalEditToggle();
installViewsToggle();
requestDashboardOverflowScale();
}
function installDashboardInteractionGuards() {
const root = document.getElementById(DASHBOARD_ID);
if (!root || root.getAttribute('data-interaction-guards-installed') === '1') {
return;
}
root.setAttribute('data-interaction-guards-installed', '1');
root.addEventListener('dragstart', function (event) {
const target = event.target;
if (target && target.closest && target.closest('a, img, svg')) {
event.preventDefault();
}
}, true);
root.addEventListener('contextmenu', function (event) {
event.preventDefault();
}, true);
root.addEventListener('mouseover', function (event) {
stripDashboardNativeTitles(event.target && event.target.closest ? event.target.closest('[title]') : null);
}, true);
root.addEventListener('mousemove', function (event) {
stripDashboardNativeTitles(event.target && event.target.closest ? event.target.closest('[title]') : null);
}, true);
root.addEventListener('focusin', function (event) {
stripDashboardNativeTitles(event.target && event.target.closest ? event.target.closest('[title]') : null);
}, true);
stripDashboardNativeTitles(root);
if (window.MutationObserver) {
const titleObserver = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'attributes' && mutation.attributeName === 'title') {
stripDashboardNativeTitles(mutation.target);
}
Array.from(mutation.addedNodes || []).forEach(function (node) {
stripDashboardNativeTitles(node);
});
});
});
titleObserver.observe(root, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['title']
});
}
}
function stripDashboardNativeTitles(node) {
if (!node || node.nodeType !== 1) {
return;
}
if (node.hasAttribute && node.hasAttribute('title')) {
node.setAttribute('data-csn-native-title', node.getAttribute('title') || '');
node.removeAttribute('title');
}
if (node.querySelectorAll) {
node.querySelectorAll('[title]').forEach(function (item) {
item.setAttribute('data-csn-native-title', item.getAttribute('title') || '');
item.removeAttribute('title');
});
}
}
function revealDashboardWhenReady() {
const root = document.getElementById(DASHBOARD_ID);
if (root && root.getAttribute('data-dashboard-revealed') !== '1') {
root.setAttribute('data-dashboard-revealed', '1');
window.requestAnimationFrame(function () {
root.classList.remove('csn-dashboard-entering');
root.classList.add('csn-dashboard-ready');
requestDashboardOverflowScale();
});
}
}
function installDashboardOverflowScaler() {
if (window.__csnDashboardOverflowScalerInstalled) {
return;
}
window.__csnDashboardOverflowScalerInstalled = true;
const root = document.getElementById(DASHBOARD_ID);
const shell = root ? root.querySelector('.csn-shell') : null;
if (window.ResizeObserver && root && shell) {
dashboardOverflowResizeObserver = new ResizeObserver(function () {
requestDashboardOverflowScale();
});
dashboardOverflowResizeObserver.observe(root);
dashboardOverflowResizeObserver.observe(shell);
}
window.addEventListener('resize', requestDashboardOverflowScale, { passive: true });
window.addEventListener('orientationchange', requestDashboardOverflowScale, { passive: true });
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', requestDashboardOverflowScale, { passive: true });
window.visualViewport.addEventListener('scroll', requestDashboardOverflowScale, { passive: true });
}
}
function requestDashboardOverflowScale() {
if (window.__csnDashboardOverflowScaleRaf) {
return;
}
window.__csnDashboardOverflowScaleRaf = window.requestAnimationFrame(function () {
window.__csnDashboardOverflowScaleRaf = 0;
fitDashboardOverflowScale();
});
}
function fitDashboardOverflowScale() {
const root = document.getElementById(DASHBOARD_ID);
const shell = root ? root.querySelector('.csn-shell') : null;
if (!root || !shell) {
return;
}
shell.style.transform = '';
shell.style.marginBottom = '';
root.style.maxWidth = '';
root.style.width = '';
root.classList.remove('csn-dashboard-overflow-scaled');
const rootStyle = window.getComputedStyle(root);
const paddingLeft = parseFloat(rootStyle.paddingLeft) || 0;
const paddingRight = parseFloat(rootStyle.paddingRight) || 0;
const rootRect = root.getBoundingClientRect();
const layoutWidth = Math.max(
1,
window.innerWidth || document.documentElement.clientWidth || root.clientWidth || rootRect.width || 1
);
let viewportWidth = layoutWidth;
if (window.visualViewport && window.visualViewport.width) {
viewportWidth = Math.max(1, window.visualViewport.width);
}
const leftInViewport = window.visualViewport ?
Math.max(0, rootRect.left - (window.visualViewport.offsetLeft || 0)) :
Math.max(0, rootRect.left);
let availableWidth = Math.max(
1,
Math.min(root.clientWidth || layoutWidth, viewportWidth - leftInViewport) - paddingLeft - paddingRight
);
const naturalWidth = Math.max(
shell.scrollWidth || 0,
shell.getBoundingClientRect().width || 0
);
if (!naturalWidth || naturalWidth <= availableWidth + 1) {
return;
}
// 不设 0.68 这类硬下限;特定内嵌浏览器比例下必须允许缩到 0.4 左右才不会横向溢出。
const scale = Math.max(0.32, Math.min(1, availableWidth / naturalWidth));
if (scale >= 0.998) {
return;
}
const naturalHeight = shell.offsetHeight || shell.getBoundingClientRect().height || 0;
const constrainedRootWidth = Math.max(1, Math.ceil(viewportWidth - leftInViewport));
root.classList.add('csn-dashboard-overflow-scaled');
root.style.maxWidth = constrainedRootWidth + 'px';
root.style.width = constrainedRootWidth + 'px';
shell.style.transform = 'scale(' + scale.toFixed(4) + ')';
if (naturalHeight) {
shell.style.marginBottom = '-' + Math.max(0, Math.round(naturalHeight * (1 - scale))) + 'px';
}
}
function installNumberResizeFitter() {
if (window.__csnDashboardNumberResizeFitterInstalled) {
return;
}
window.__csnDashboardNumberResizeFitterInstalled = true;
window.addEventListener('resize', function () {
document.querySelectorAll('.csn-big-number').forEach(function (el) {
fitBigNumberToContainer(el);
});
fitPlainViewsNumber(document.getElementById('csn-total-views'));
fitPlainMetricNumber(document.getElementById('csn-total-edits'));
requestDashboardOverflowScale();
}, { passive: true });
}
async function loadDashboardData() {
try {
const userName = mw.config.get('wgUserName');
if (!userName) {
renderEmptyState();
revealDashboardWhenReady();
return;
}
const api = new mw.Api();
const userInfoPromise = getUserInfo(api, userName);
const fastContribsPromise = getRecentContributions(api, userName, FAST_CONTRIBUTION_LIMIT);
const userInfo = await userInfoPromise;
const fastContribs = await fastContribsPromise;
const fastSortedContribs = fastContribs.slice().sort(sortNewestFirst);
const registrationDate = parseMediaWikiDate(userInfo.registration) || getEarliestContributionDate(fastContribs) || new Date();
const totalEdits = Number(userInfo.editcount || fastContribs.length || 0);
const today = new Date();
updateTotalEditStats(totalEdits, countMainNamespaceContributions(fastContribs), {
animate: true
});
setText('csn-total-date', '截至' + formatMonthDay(today));
setText('csn-view-date', '截至' + formatMonthDay(getPageviewsDisplayEndDate()));
// 首屏先用最近贡献快速填充,避免等待注册至今贡献全部拉完。
renderRecentEdits(fastSortedContribs, { complete: false });
safeRenderActivityHeatmap(fastContribs, registrationDate);
renderEditTrendChart(fastContribs, registrationDate, totalEdits);
// 浏览量区域先按最近条目索引顺序占位,数值为 0,随后后台更新。
renderTopPages(makeFirstEditedArticlePages(fastContribs).slice(0, TOP_VIEW_LIMIT).map(function (page) {
return {
title: page.title,
timestamp: page.timestamp,
views: 0,
pending: true
};
}));
animateViewsNumberTextWhenReady(0);
revealDashboardWhenReady();
window.setTimeout(async function () {
try {
const contributions = await getAllContributions(api, userName);
const sortedContribs = contributions.slice().sort(sortNewestFirst);
const fullRegistrationDate = parseMediaWikiDate(userInfo.registration) || getEarliestContributionDate(contributions) || registrationDate;
updateTotalEditStats(totalEdits, countMainNamespaceContributions(contributions), {
animate: true
});
renderEditTrendChart(contributions, fullRegistrationDate, totalEdits);
safeRenderActivityHeatmap(contributions, fullRegistrationDate);
renderRecentEdits(sortedContribs, { complete: true });
const editedArticlePages = makeFirstEditedArticlePages(contributions);
hydrateViewStatsProgressively(editedArticlePages);
} catch (error) {
console.error('[总览] 后台完整数据加载失败', error);
}
}, 0);
} catch (error) {
console.error('[总览]', error);
renderEmptyState();
revealDashboardWhenReady();
}
}
function renderEmptyState() {
updateTotalEditStats(0, 0, {
animate: false
});
renderEditTrendChart([], new Date(), 0);
safeRenderActivityHeatmap([], new Date());
renderRecentEdits([]);
renderTopPages([]);
}
function countMainNamespaceContributions(contributions) {
return (Array.isArray(contributions) ? contributions : []).reduce(function (sum, item) {
return sum + (item && String(item.ns) === '0' ? 1 : 0);
}, 0);
}
function updateTotalEditStats(totalCount, mainNamespaceCount, options) {
totalEditAllCount = Number(totalCount || 0);
totalEditMainNamespaceCount = Number(mainNamespaceCount || 0);
updateTotalEditCardContent(options || {});
}
function getCurrentTotalEditValue() {
return totalEditDisplayMode === 'main' ? totalEditMainNamespaceCount : totalEditAllCount;
}
function getCurrentTotalEditTitle() {
return totalEditDisplayMode === 'main' ? '主条目编辑数' : '总编辑数';
}
function updateTotalEditCardContent(options) {
const title = document.getElementById('csn-total-title') ||
document.querySelector('.csn-total-card .csn-title');
const value = getCurrentTotalEditValue();
const titleText = getCurrentTotalEditTitle();
const animate = !options || options.animate !== false;
const titleAnimate = !!(options && options.titleAnimate);
if (title && title.textContent !== titleText) {
if (titleAnimate) {
const token = String(Date.now()) + ':' + String(Math.random());
title.setAttribute('data-title-switch-token', token);
title.classList.add('csn-title-swapping');
title.textContent = titleText;
window.setTimeout(function () {
if (title.getAttribute('data-title-switch-token') !== token) {
return;
}
title.classList.remove('csn-title-swapping');
title.removeAttribute('data-title-switch-token');
}, 160);
} else {
title.textContent = titleText;
title.classList.remove('csn-title-swapping');
title.removeAttribute('data-title-switch-token');
}
}
if (animate) {
animateCompactMetricNumberTextWhenReady('csn-total-edits', value);
} else {
const el = document.getElementById('csn-total-edits');
const text = getCompactNumberParts(value).text;
if (el) {
el.setAttribute('data-raw-value', String(value));
el.setAttribute('data-display-value', text);
renderRollingStaticNumber(el, text);
fitPlainMetricNumber(el);
}
}
const card = document.querySelector('.csn-total-card');
if (card) {
card.setAttribute('data-total-edit-mode', totalEditDisplayMode);
card.setAttribute('aria-label', titleText + ',点击切换');
card.removeAttribute('title');
}
}
function installViewsToggle() {
const card = document.querySelector('.csn-views-card');
if (!card || card.getAttribute('data-views-toggle-installed') === '1') {
return;
}
card.setAttribute('data-views-toggle-installed', '1');
card.setAttribute('role', 'button');
card.setAttribute('tabindex', '0');
card.setAttribute('aria-label', '累计浏览量,点击切换完整显示');
function press() {
card.classList.remove('csn-views-card-bounce');
card.classList.add('csn-views-card-pressed');
}
function release() {
if (!card.classList.contains('csn-views-card-pressed')) {
return;
}
card.classList.remove('csn-views-card-pressed');
card.classList.remove('csn-views-card-bounce');
void card.offsetWidth;
card.classList.add('csn-views-card-bounce');
window.setTimeout(function () {
card.classList.remove('csn-views-card-bounce');
}, 520);
}
function toggle() {
++viewsToggleToken;
const previousMode = viewsDisplayMode;
viewsDisplayMode = viewsDisplayMode === 'full' ? 'compact' : 'full';
// 标题保持“累计浏览量”,只切换数字显示形态。
updateViewsCardContent({
animate: true,
forceModeSwitch: true,
fromMode: previousMode
});
}
card.addEventListener('pointerdown', function (event) {
if (event && event.button != null && event.button !== 0) {
return;
}
press();
}, { passive: true });
card.addEventListener('pointerup', release, { passive: true });
card.addEventListener('pointercancel', release, { passive: true });
card.addEventListener('pointerleave', release, { passive: true });
card.addEventListener('click', function () {
toggle();
});
card.addEventListener('keydown', function (event) {
if (!event || (event.key !== 'Enter' && event.key !== ' ')) {
return;
}
event.preventDefault();
press();
window.setTimeout(function () {
release();
toggle();
}, 90);
});
}
function installTotalEditToggle() {
const card = document.querySelector('.csn-total-card');
if (!card || card.getAttribute('data-total-edit-toggle-installed') === '1') {
return;
}
card.setAttribute('data-total-edit-toggle-installed', '1');
card.setAttribute('role', 'button');
card.setAttribute('tabindex', '0');
card.setAttribute('aria-label', getCurrentTotalEditTitle() + ',点击切换');
function press() {
card.classList.remove('csn-total-card-bounce');
card.classList.add('csn-total-card-pressed');
}
function release() {
if (!card.classList.contains('csn-total-card-pressed')) {
return;
}
card.classList.remove('csn-total-card-pressed');
card.classList.remove('csn-total-card-bounce');
void card.offsetWidth;
card.classList.add('csn-total-card-bounce');
window.setTimeout(function () {
card.classList.remove('csn-total-card-bounce');
}, 520);
}
function toggle() {
++totalEditToggleToken;
totalEditDisplayMode = totalEditDisplayMode === 'main' ? 'total' : 'main';
// 数字立即换槽,不再等按压动画或标题淡出完成,避免点击后读取慢一拍。
updateTotalEditCardContent({
animate: true,
titleAnimate: true
});
}
card.addEventListener('pointerdown', function (event) {
if (event && event.button != null && event.button !== 0) {
return;
}
press();
}, { passive: true });
card.addEventListener('pointerup', release, { passive: true });
card.addEventListener('pointercancel', release, { passive: true });
card.addEventListener('pointerleave', release, { passive: true });
card.addEventListener('click', function () {
toggle();
});
card.addEventListener('keydown', function (event) {
if (!event || (event.key !== 'Enter' && event.key !== ' ')) {
return;
}
event.preventDefault();
press();
window.setTimeout(function () {
release();
toggle();
}, 90);
});
}
function getUserInfo(api, userName) {
return api.get({
action: 'query',
list: 'users',
ususers: userName,
usprop: 'editcount|registration',
format: 'json'
}).then(function (data) {
return data.query && data.query.users && data.query.users[0] ? data.query.users[0] : {};
});
}
async function getRecentContributions(api, userName, limit) {
const data = await api.get({
action: 'query',
list: 'usercontribs',
ucuser: userName,
uclimit: String(Math.max(1, Math.min(500, limit || 500))),
ucprop: 'title|timestamp|comment|sizediff|ids|ns',
ucdir: 'older',
format: 'json'
});
return data.query && data.query.usercontribs ? data.query.usercontribs : [];
}
async function getAllContributions(api, userName) {
const all = [];
let uccontinue = null;
do {
const params = {
action: 'query',
list: 'usercontribs',
ucuser: userName,
uclimit: '500',
ucprop: 'title|timestamp|comment|sizediff|ids|ns',
ucdir: 'older',
format: 'json'
};
if (uccontinue) {
params.uccontinue = uccontinue;
}
const data = await api.get(params);
const batch = data.query && data.query.usercontribs ? data.query.usercontribs : [];
all.push.apply(all, batch);
uccontinue = data.continue && data.continue.uccontinue ? data.continue.uccontinue : null;
} while (uccontinue && all.length < MAX_CONTRIBUTIONS_TO_LOAD);
return all;
}
function renderEditTrendChart(contributions, registrationDate, totalEdits) {
const box = document.getElementById('csn-chart-box');
if (!box) {
return;
}
const start = startOfDay(registrationDate || getEarliestContributionDate(contributions) || new Date());
const end = startOfDay(new Date());
const dailyCounts = new Map();
(contributions || []).forEach(function (item) {
const d = parseMediaWikiDate(item.timestamp);
if (!d) {
return;
}
const key = toDateKey(d);
dailyCounts.set(key, (dailyCounts.get(key) || 0) + 1);
});
const days = Math.max(1, Math.floor((end - start) / 86400000) + 1);
const chartData = [];
let cumulative = 0;
for (let i = 0; i < days; i++) {
const current = new Date(start.getTime() + i * 86400000);
const daily = dailyCounts.get(toDateKey(current)) || 0;
cumulative += daily;
chartData.push({
date: current,
daily: daily,
cumulative: cumulative
});
}
if (totalEdits && chartData.length && chartData[chartData.length - 1].cumulative < totalEdits) {
chartData[chartData.length - 1].cumulative = totalEdits;
}
const entryDone = box.getAttribute('data-chart-entry-done') === '1';
let startedAt = Number(box.getAttribute('data-chart-entry-started-at') || 0);
const shouldStartEntry = !entryDone && !startedAt;
// 后台完整数据可能在首屏折线动画尚未结束时回来。
// 这时不要重绘 SVG,否则 PC 端的线条动画会被打断,渐变也会继续等固定剩余时间。
// 只缓存最新图表数据,等首屏线条动画和渐变淡入完成后再静态刷新。
if (!entryDone && startedAt && !shouldStartEntry) {
box.__csnPendingTrendChartData = chartData;
return;
}
if (shouldStartEntry) {
const gate = getComponentAnimationGateElement(box);
box.__csnPendingTrendChartData = chartData;
if (!isElementTopPastViewportHalf(gate || box)) {
if (box.getAttribute('data-chart-entry-gate-pending') !== '1') {
box.setAttribute('data-chart-entry-gate-pending', '1');
runWhenTopPastViewportHalf(gate || box, function () {
if (box.getAttribute('data-chart-entry-done') === '1') {
return;
}
const pendingChartData = box.__csnPendingTrendChartData || chartData;
box.__csnPendingTrendChartData = null;
box.removeAttribute('data-chart-entry-gate-pending');
startTrendChartEntryAnimation(box, pendingChartData);
});
}
return;
}
box.__csnPendingTrendChartData = null;
startTrendChartEntryAnimation(box, chartData);
} else {
renderStaticTrendChart(box, chartData);
}
}
function startTrendChartEntryAnimation(box, chartData) {
if (!box) {
return;
}
box.innerHTML = createLineSvg(chartData);
const startedAt = performance.now();
box.setAttribute('data-chart-entry-started-at', String(startedAt));
if (prepareChartDrawAnimation(box)) {
restartChartLineDrawAnimation(box);
scheduleChartAreaFade(box, CHART_AREA_FADE_DELAY_MS, true);
} else {
scheduleChartAreaFade(box, 0, false);
}
bindTrendChartHover(box, chartData);
requestDashboardOverflowScale();
}
function scheduleChartAreaFade(box, delay, waitForLineAnimation) {
if (!box) {
return;
}
if (box.__csnChartAreaFadeTimer) {
window.clearTimeout(box.__csnChartAreaFadeTimer);
box.__csnChartAreaFadeTimer = 0;
}
if (box.__csnChartAreaFadeOnEnd && box.__csnChartAreaFadeLine) {
box.__csnChartAreaFadeLine.removeEventListener('animationend', box.__csnChartAreaFadeOnEnd);
box.__csnChartAreaFadeOnEnd = null;
box.__csnChartAreaFadeLine = null;
}
const line = waitForLineAnimation ? box.querySelector('.csn-chart-line-path') : null;
let finished = false;
function finish() {
if (finished) {
return;
}
finished = true;
if (box.__csnChartAreaFadeTimer) {
window.clearTimeout(box.__csnChartAreaFadeTimer);
box.__csnChartAreaFadeTimer = 0;
}
if (box.__csnChartAreaFadeOnEnd && box.__csnChartAreaFadeLine) {
box.__csnChartAreaFadeLine.removeEventListener('animationend', box.__csnChartAreaFadeOnEnd);
box.__csnChartAreaFadeOnEnd = null;
box.__csnChartAreaFadeLine = null;
}
revealChartArea(box);
}
if (line) {
box.__csnChartAreaFadeOnEnd = function (event) {
if (event && event.target !== line) {
return;
}
finish();
};
box.__csnChartAreaFadeLine = line;
line.addEventListener('animationend', box.__csnChartAreaFadeOnEnd);
}
// 传入的 delay 是渐变最早淡入时间;animationend 只是兜底补齐,不能再强制等到线条全结束。
box.__csnChartAreaFadeTimer = window.setTimeout(finish, Math.max(0, Number(delay || 0)) + (line ? 20 : 0));
}
function revealChartArea(box) {
const area = box ? box.querySelector('.csn-chart-area-path') : null;
if (area) {
area.classList.add('csn-chart-area-visible');
}
window.setTimeout(function () {
if (!box) {
return;
}
box.setAttribute('data-chart-entry-done', '1');
if (box.__csnPendingTrendChartData) {
const pendingChartData = box.__csnPendingTrendChartData;
box.__csnPendingTrendChartData = null;
renderStaticTrendChart(box, pendingChartData);
}
}, CHART_AREA_FADE_MS + 40);
}
function renderStaticTrendChart(box, chartData) {
if (!box) {
return;
}
box.innerHTML = createLineSvg(chartData);
const area = box.querySelector('.csn-chart-area-path');
const line = box.querySelector('.csn-chart-line-path');
if (area) {
area.classList.remove('csn-chart-area-path');
}
if (line) {
line.classList.remove('csn-chart-line-path');
}
bindTrendChartHover(box, chartData);
requestDashboardOverflowScale();
}
function prepareChartDrawAnimation(box) {
const path = box ? box.querySelector('#csn-chart-line-path') : null;
if (!path || typeof path.getTotalLength !== 'function') {
return false;
}
let length = 0;
try {
length = path.getTotalLength();
} catch (e) {
length = 0;
}
if (!length || !Number.isFinite(length)) {
return false;
}
path.style.setProperty('--csn-chart-path-length', String(Math.ceil(length)));
return true;
}
function restartChartLineDrawAnimation(box) {
const path = box ? box.querySelector('#csn-chart-line-path') : null;
if (!path) {
return;
}
path.classList.remove('csn-chart-line-path');
void path.getBoundingClientRect();
path.classList.add('csn-chart-line-path');
}
function createLineSvg(chartData) {
const width = 1100;
const height = 318;
const padY = 48;
const values = chartData.map(function (item) {
return item.cumulative;
});
const max = Math.max.apply(null, values.concat([1]));
const min = Math.min.apply(null, values.concat([0]));
const range = Math.max(1, max - min);
const baseY = height - padY;
const coords = values.map(function (value, index) {
const x = values.length <= 1 ? 0 : (index / (values.length - 1)) * width;
const y = height - padY - ((value - min) / range) * (height - padY * 2);
return {
x: x,
y: y
};
});
const linePath = makeSmoothPath(coords);
const areaPath = makeAreaPath(coords, height);
return '<svg viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="none" aria-hidden="true">' +
'<defs>' +
'<linearGradient id="csn-trend-fill" x1="0" y1="0" x2="0" y2="1">' +
'<stop offset="0%" stop-color="#2f6fdb" stop-opacity="0.22"></stop>' +
'<stop offset="100%" stop-color="#2f6fdb" stop-opacity="0.02"></stop>' +
'</linearGradient>' +
'</defs>' +
'<path class="csn-chart-area-path" d="' + escapeAttr(areaPath) + '" fill="url(#csn-trend-fill)"></path>' +
'<path class="csn-chart-line-path" id="csn-chart-line-path" d="' + escapeAttr(linePath) + '" fill="none" stroke="#2f6fdb" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"></path>' +
'<rect x="0" y="0" width="' + width + '" height="' + height + '" fill="transparent"></rect>' +
'</svg>' +
'<div class="csn-chart-hover-dot" id="csn-chart-hover-point"></div>' +
'<div class="csn-chart-tooltip" id="csn-chart-tooltip"></div>';
}
function makeSmoothPath(points) {
if (!points.length) {
return '';
}
if (points.length === 1) {
return 'M ' + points[0].x.toFixed(2) + ' ' + points[0].y.toFixed(2);
}
let d = 'M ' + points[0].x.toFixed(2) + ' ' + points[0].y.toFixed(2);
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[Math.max(0, i - 1)];
const p1 = points[i];
const p2 = points[i + 1];
const p3 = points[Math.min(points.length - 1, i + 2)];
const cp1x = p1.x + (p2.x - p0.x) / 6;
const cp1y = p1.y + (p2.y - p0.y) / 6;
const cp2x = p2.x - (p3.x - p1.x) / 6;
const cp2y = p2.y - (p3.y - p1.y) / 6;
d += ' C ' + cp1x.toFixed(2) + ' ' + cp1y.toFixed(2) + ', ' + cp2x.toFixed(2) + ' ' + cp2y.toFixed(2) + ', ' + p2.x.toFixed(2) + ' ' + p2.y.toFixed(2);
}
return d;
}
function makeAreaPath(points, baseY) {
if (!points.length) {
return '';
}
const line = makeSmoothPath(points);
const last = points[points.length - 1];
const first = points[0];
return line + ' L ' + last.x.toFixed(2) + ' ' + baseY.toFixed(2) + ' L ' + first.x.toFixed(2) + ' ' + baseY.toFixed(2) + ' Z';
}
function bindTrendChartHover(box, chartData) {
const svg = box.querySelector('svg');
const point = box.querySelector('#csn-chart-hover-point');
const tooltip = box.querySelector('#csn-chart-tooltip');
if (!svg || !point || !tooltip || !chartData.length) {
return;
}
const width = 1100;
const height = 318;
const padY = 48;
const values = chartData.map(function (item) {
return item.cumulative;
});
const max = Math.max.apply(null, values.concat([1]));
const min = Math.min.apply(null, values.concat([0]));
const range = Math.max(1, max - min);
let hoverActive = false;
let rafId = 0;
let currentPointX = 0;
let currentPointY = 0;
let targetPointX = 0;
let targetPointY = 0;
let currentTipX = 0;
let currentTipY = 0;
let targetTipX = 0;
let targetTipY = 0;
let hasCurrent = false;
function pointAt(index) {
const item = chartData[index];
const x = chartData.length <= 1 ? 0 : (index / (chartData.length - 1)) * width;
const y = height - padY - ((item.cumulative - min) / range) * (height - padY * 2);
return {
x: x,
y: y,
item: item
};
}
function showHover() {
hoverActive = true;
point.classList.add('csn-chart-hover-dot-visible');
tooltip.classList.add('csn-chart-tooltip-visible');
if (!rafId) {
rafId = window.requestAnimationFrame(animateHover);
}
}
function hideHover() {
hoverActive = false;
point.classList.remove('csn-chart-hover-dot-visible');
tooltip.classList.remove('csn-chart-tooltip-visible');
}
function animateHover() {
rafId = 0;
if (!hasCurrent) {
return;
}
const curve = hoverActive ? 0.22 : 0.18;
currentPointX += (targetPointX - currentPointX) * curve;
currentPointY += (targetPointY - currentPointY) * curve;
currentTipX += (targetTipX - currentTipX) * curve;
currentTipY += (targetTipY - currentTipY) * curve;
point.style.transform = 'translate3d(' + currentPointX.toFixed(1) + 'px, ' + currentPointY.toFixed(1) + 'px, 0)';
tooltip.style.transform = 'translate3d(' + currentTipX.toFixed(1) + 'px, ' + currentTipY.toFixed(1) + 'px, 0)';
const pointSettled = Math.abs(targetPointX - currentPointX) < 0.1 && Math.abs(targetPointY - currentPointY) < 0.1;
const tipSettled = Math.abs(targetTipX - currentTipX) < 0.1 && Math.abs(targetTipY - currentTipY) < 0.1;
if (hoverActive || !pointSettled || !tipSettled) {
rafId = window.requestAnimationFrame(animateHover);
}
}
function updateTarget(clientX) {
const rect = svg.getBoundingClientRect();
if (!rect.width || !rect.height) {
hideHover();
return;
}
const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
const index = Math.min(chartData.length - 1, Math.max(0, Math.round(ratio * (chartData.length - 1))));
const p = pointAt(index);
const pointClientX = (p.x / width) * rect.width;
const pointClientY = (p.y / height) * rect.height;
const hoverClientX = Math.min(rect.width, Math.max(0, clientX - rect.left));
targetPointX = pointClientX;
targetPointY = pointClientY;
tooltip.innerHTML = '<span class="csn-chart-tooltip-date">' + escapeHtml(formatShortDate(p.item.date)) + '</span>' +
'<span class="csn-chart-tooltip-line">当日编辑数:' + escapeHtml(formatNumber(p.item.daily)) + '</span>' +
'<span class="csn-chart-tooltip-line">累计编辑数:' + escapeHtml(formatNumber(p.item.cumulative)) + '</span>';
tooltip.classList.add('csn-chart-tooltip-visible');
const tooltipWidth = tooltip.offsetWidth || 148;
const tooltipHeight = tooltip.offsetHeight || 58;
let left = hoverClientX - tooltipWidth - 16;
let top = pointClientY - tooltipHeight / 2;
if (left < 8) {
left = hoverClientX + 16;
}
if (left + tooltipWidth > rect.width - 8) {
left = rect.width - tooltipWidth - 8;
}
if (top < 8) {
top = 8;
}
if (top + tooltipHeight > rect.height - 8) {
top = rect.height - tooltipHeight - 8;
}
targetTipX = left;
targetTipY = top;
if (!hasCurrent) {
currentPointX = targetPointX;
currentPointY = targetPointY;
currentTipX = targetTipX;
currentTipY = targetTipY;
hasCurrent = true;
point.style.transform = 'translate3d(' + currentPointX.toFixed(1) + 'px, ' + currentPointY.toFixed(1) + 'px, 0)';
tooltip.style.transform = 'translate3d(' + currentTipX.toFixed(1) + 'px, ' + currentTipY.toFixed(1) + 'px, 0)';
}
showHover();
}
box.addEventListener('mousemove', function (e) {
updateTarget(e.clientX);
});
box.addEventListener('mouseenter', function (e) {
updateTarget(e.clientX);
});
box.addEventListener('mouseleave', function () {
hideHover();
});
box.addEventListener('touchstart', function (e) {
if (e.touches && e.touches[0]) {
updateTarget(e.touches[0].clientX);
}
}, { passive: true });
box.addEventListener('touchmove', function (e) {
if (e.touches && e.touches[0]) {
updateTarget(e.touches[0].clientX);
}
}, { passive: true });
box.addEventListener('touchend', hideHover, { passive: true });
hideHover();
}
function safeRenderActivityHeatmap(contributions, registrationDate) {
try {
renderActivityHeatmap(contributions, registrationDate);
} catch (error) {
const box = document.getElementById('csn-activity-box');
if (box) {
box.innerHTML = '';
}
console.error('[总览] 编辑活跃渲染失败', error);
}
}
function renderActivityHeatmap(contributions, registrationDate) {
const box = document.getElementById('csn-activity-box');
if (!box) {
return;
}
const today = startOfDay(new Date());
const displayYear = today.getFullYear();
const rangeStart = new Date(displayYear, 0, 1);
const rangeEnd = new Date(displayYear, 11, 31);
const calendarStart = startOfWeek(rangeStart);
const calendarEnd = endOfWeek(rangeEnd);
const dailyCounts = new Map();
const sourceContributions = Array.isArray(contributions) ? contributions : [];
sourceContributions.forEach(function (item) {
const d = parseMediaWikiDate(item.timestamp);
if (!d) {
return;
}
const day = startOfDay(d);
if (day < rangeStart || day > today) {
return;
}
const key = toDateKey(day);
dailyCounts.set(key, (dailyCounts.get(key) || 0) + 1);
});
const days = Math.max(7, Math.floor((calendarEnd - calendarStart) / 86400000) + 1);
const dayItems = [];
for (let i = 0; i < days; i++) {
const current = new Date(calendarStart.getTime() + i * 86400000);
const isOutsideRange = current < rangeStart || current > rangeEnd;
const isFuture = current > today;
const count = isOutsideRange || isFuture ? 0 : dailyCounts.get(toDateKey(current)) || 0;
dayItems.push({
date: current,
count: count,
isFuture: isFuture,
isOutsideYear: isOutsideRange
});
}
let maxDaily = 1;
dayItems.forEach(function (item) {
if (!item.isFuture && !item.isOutsideYear && item.count > maxDaily) {
maxDaily = item.count;
}
});
const weekCount = Math.max(1, Math.ceil(dayItems.length / 7));
box.innerHTML = '' +
'<div class="csn-activity-board">' +
'<div class="csn-activity-scroll" id="csn-activity-scroll">' +
'<div class="csn-activity-month-row" id="csn-activity-month-row">' +
createActivityMonthLabels(calendarStart, rangeEnd, weekCount, displayYear) +
'</div>' +
'<div class="csn-activity-grid" id="csn-activity-grid">' +
createActivityGridHtml(dayItems, maxDaily) +
'</div>' +
'</div>' +
'</div>' +
'<div class="csn-activity-tooltip" id="csn-activity-tooltip"></div>';
const scroll = box.querySelector('#csn-activity-scroll');
const grid = box.querySelector('#csn-activity-grid');
fitActivityGrid(grid, dayItems.length);
if (activityResizeObserver) {
activityResizeObserver.disconnect();
activityResizeObserver = null;
}
if (window.ResizeObserver && grid) {
activityResizeObserver = new ResizeObserver(function () {
fitActivityGrid(grid, dayItems.length);
});
activityResizeObserver.observe(box);
}
if (scroll) {
scroll.scrollLeft = 0;
}
bindActivityHover(box);
requestDashboardOverflowScale();
}
function createActivityGridHtml(dayItems, maxDaily) {
return dayItems.map(function (item) {
return createActivityCellHtml(item, getActivityLevel(item.count, maxDaily));
}).join('');
}
function createActivityMonthLabels(calendarStart, calendarEnd, weekCount, displayYear) {
const labels = [];
const year = Number(displayYear || new Date().getFullYear());
const yearEnd = new Date(year, 11, 31);
let current = new Date(year, 0, 1);
while (current <= yearEnd && current <= calendarEnd) {
const monthStartWeek = Math.max(0, Math.floor((startOfWeek(current) - calendarStart) / 604800000));
const nextMonth = new Date(current.getFullYear(), current.getMonth() + 1, 1);
const nextMonthWeek = Math.min(
weekCount,
Math.max(monthStartWeek + 1, Math.floor((startOfWeek(nextMonth) - calendarStart) / 604800000))
);
const span = Math.max(1, nextMonthWeek - monthStartWeek);
const label = String(current.getMonth() + 1) + '月';
const lastClass = current.getMonth() === 11 ? ' csn-activity-month-label-last' : '';
labels.push(
'<span class="csn-activity-month-label' + lastClass + '" style="grid-column:' + (monthStartWeek + 1) + ' / span ' + span + ';">' +
escapeHtml(label) +
'</span>'
);
current = nextMonth;
}
return labels.join('');
}
function isMobileActivityLayout() {
return window.matchMedia && window.matchMedia('(max-width: 980px)').matches;
}
function createActivityCellHtml(item, level) {
const futureClass = item.isFuture ? ' csn-activity-future' : '';
const outsideClass = item.isOutsideYear ? ' csn-activity-outside-year' : '';
const dateText = formatShortDate(item.date);
const titleText = item.isOutsideYear ?
dateText + ':不在本年范围' :
item.isFuture ?
dateText + ':未到日期' :
dateText + ':' + item.count + ' 次编辑';
return '' +
'<span class="csn-activity-cell csn-activity-level-' + level + futureClass + outsideClass + '" ' +
'data-date="' + escapeAttr(dateText) + '" ' +
'data-count="' + escapeAttr(String(item.count)) + '" ' +
'data-future="' + (item.isFuture ? '1' : '0') + '" ' +
'data-outside-year="' + (item.isOutsideYear ? '1' : '0') + '" ' +
'title="' + escapeAttr(titleText) + '">' +
'</span>';
}
function fitActivityGrid(grid, dayCount) {
if (!grid) {
return;
}
const box = document.getElementById('csn-activity-box');
const weeks = Math.max(1, Math.ceil(dayCount / 7));
const gap = 4;
const maxCell = isMobileActivityLayout() ? 11 : 12;
const boxWidth = box && box.clientWidth ? Math.max(1, box.clientWidth - 22) : 900;
const fitted = Math.floor((boxWidth - Math.max(0, weeks - 1) * gap) / weeks);
const cellSize = Math.max(10, Math.min(maxCell, fitted || maxCell));
if (box) {
box.style.setProperty('--csn-activity-cell-size', cellSize + 'px');
box.style.setProperty('--csn-activity-gap', gap + 'px');
box.style.setProperty('--csn-activity-week-count', String(weeks));
}
}
function getActivityLevel(count, maxDaily) {
if (!count) {
return 0;
}
if (maxDaily <= 1) {
return 3;
}
const ratio = count / maxDaily;
if (ratio <= 0.10) {
return 1;
}
if (ratio <= 0.25) {
return 2;
}
if (ratio <= 0.50) {
return 3;
}
if (ratio <= 0.75) {
return 4;
}
return 5;
}
function bindActivityHover(box) {
const tooltip = box.querySelector('#csn-activity-tooltip');
if (!tooltip) {
return;
}
let rafId = 0;
let hoverActive = false;
let currentX = 0;
let currentY = 0;
let targetX = 0;
let targetY = 0;
let hasCurrent = false;
function show() {
hoverActive = true;
tooltip.classList.add('csn-activity-tooltip-visible');
if (!rafId) {
rafId = window.requestAnimationFrame(animate);
}
}
function hide() {
hoverActive = false;
tooltip.classList.remove('csn-activity-tooltip-visible');
}
function animate() {
rafId = 0;
if (!hasCurrent) {
return;
}
const curve = hoverActive ? 0.24 : 0.18;
currentX += (targetX - currentX) * curve;
currentY += (targetY - currentY) * curve;
tooltip.style.transform = 'translate3d(' + currentX.toFixed(1) + 'px, ' + currentY.toFixed(1) + 'px, 0)';
const settled = Math.abs(targetX - currentX) < 0.1 && Math.abs(targetY - currentY) < 0.1;
if (hoverActive || !settled) {
rafId = window.requestAnimationFrame(animate);
}
}
function updateFromCell(cell) {
const boxRect = box.getBoundingClientRect();
const cellRect = cell.getBoundingClientRect();
const date = cell.getAttribute('data-date') || '';
const count = Number(cell.getAttribute('data-count') || 0);
const isFuture = cell.getAttribute('data-future') === '1';
const isOutsideYear = cell.getAttribute('data-outside-year') === '1';
tooltip.innerHTML = '<span class="csn-activity-tooltip-date">' + escapeHtml(date) + '</span>' +
'<span class="csn-activity-tooltip-line">' + escapeHtml(
isOutsideYear ? '不在本年范围' : isFuture ? '未到日期' : '当日编辑数:' + formatNumber(count)
) + '</span>';
tooltip.classList.add('csn-activity-tooltip-visible');
const tooltipWidth = tooltip.offsetWidth || 132;
const tooltipHeight = tooltip.offsetHeight || 48;
const cellCenterX = cellRect.left - boxRect.left + cellRect.width / 2;
const cellTop = cellRect.top - boxRect.top;
const cellBottom = cellRect.bottom - boxRect.top;
let left = cellCenterX - tooltipWidth / 2;
let top = cellTop - tooltipHeight - 10;
if (top < 8) {
top = cellBottom + 10;
}
if (left < 8) {
left = 8;
}
if (left + tooltipWidth > boxRect.width - 8) {
left = boxRect.width - tooltipWidth - 8;
}
if (top + tooltipHeight > boxRect.height - 8) {
top = boxRect.height - tooltipHeight - 8;
}
targetX = left;
targetY = top;
if (!hasCurrent) {
currentX = targetX;
currentY = targetY;
hasCurrent = true;
tooltip.style.transform = 'translate3d(' + currentX.toFixed(1) + 'px, ' + currentY.toFixed(1) + 'px, 0)';
}
show();
}
box.addEventListener('mousemove', function (e) {
const cell = e.target && e.target.closest ? e.target.closest('.csn-activity-cell') : null;
if (!cell || !box.contains(cell)) {
hide();
return;
}
updateFromCell(cell);
});
box.addEventListener('mouseleave', hide);
box.addEventListener('touchstart', function (e) {
const touch = e.touches && e.touches[0];
if (!touch) {
return;
}
const el = document.elementFromPoint(touch.clientX, touch.clientY);
const cell = el && el.closest ? el.closest('.csn-activity-cell') : null;
if (cell && box.contains(cell)) {
updateFromCell(cell);
}
}, { passive: true });
box.addEventListener('touchmove', function (e) {
const touch = e.touches && e.touches[0];
if (!touch) {
return;
}
const el = document.elementFromPoint(touch.clientX, touch.clientY);
const cell = el && el.closest ? el.closest('.csn-activity-cell') : null;
if (cell && box.contains(cell)) {
updateFromCell(cell);
}
}, { passive: true });
box.addEventListener('touchend', hide, { passive: true });
hide();
}
function settleRecentEditCards(list) {
if (!list) {
return;
}
Array.from(list.querySelectorAll('.csn-recent-item')).forEach(function (card) {
card.classList.remove('csn-recent-pre-in');
card.classList.remove('csn-recent-stack-in');
card.classList.add('csn-recent-stack-settled');
});
}
function animateRecentEditCards(list) {
if (!list) {
return;
}
const cards = Array.from(list.querySelectorAll('.csn-recent-item'));
const token = String(Date.now()) + ':' + String(Math.random());
const cardContainer = list.closest ? list.closest('.csn-recent-card') : list;
list.setAttribute('data-recent-animation-token', token);
list.setAttribute('data-recent-animation-pending', '1');
cards.forEach(function (card, index) {
card.classList.remove('csn-recent-stack-in');
card.classList.remove('csn-recent-stack-settled');
card.classList.add('csn-recent-pre-in');
card.style.setProperty('--csn-recent-delay', String(index * 86) + 'ms');
});
runWhenTopPastViewportHalf(cardContainer || list, function () {
if (list.getAttribute('data-recent-animation-token') !== token) {
return;
}
list.removeAttribute('data-recent-animation-pending');
// 先等 DOM 文字和布局落地,再播放动画;避免条目名称还没绘制就开始缩放/裁切。
window.requestAnimationFrame(function () {
cards.forEach(function (card) {
void card.offsetHeight;
});
window.requestAnimationFrame(function () {
if (list.getAttribute('data-recent-animation-token') !== token) {
return;
}
cards.forEach(function (card) {
card.classList.add('csn-recent-stack-in');
});
window.setTimeout(function () {
if (list.getAttribute('data-recent-animation-token') !== token) {
return;
}
cards.forEach(function (card) {
card.classList.remove('csn-recent-stack-in');
card.classList.add('csn-recent-stack-settled');
});
}, 1180);
});
});
});
}
function renderRecentEdits(items, options) {
const list = document.getElementById('csn-recent-list');
if (!list) {
return;
}
installRecentEditWheelPager();
recentEditPool = (items || []).filter(Boolean);
recentEditPoolComplete = !!(options && options.complete);
if (recentEditPageAnimating) {
pendingRecentEditPoolRefresh = true;
return;
}
const maxPage = getRecentEditMaxPageIndex();
if (recentEditPageIndex > maxPage) {
recentEditPageIndex = maxPage;
}
if (recentEditPageIndex < 0) {
recentEditPageIndex = 0;
}
const rows = getRecentEditPageRows(recentEditPageIndex);
// 没有真实最近编辑数据时保持空白,不再提前塞“条目名称/编辑摘要”占位。
if (!rows.length) {
list.innerHTML = '';
list.removeAttribute('data-recent-animated');
list.removeAttribute('data-recent-animation-pending');
updateRecentEditResetButton();
return;
}
const shouldAnimate = list.getAttribute('data-recent-animated') !== '1';
renderRecentRowsIntoList(list, rows);
// 先强制完成标题布局,避免动画开始时标题还没绘制。
Array.from(list.querySelectorAll('.csn-page-link')).forEach(function (link) {
void link.offsetWidth;
});
if (shouldAnimate || list.getAttribute('data-recent-animation-pending') === '1') {
list.setAttribute('data-recent-animated', '1');
animateRecentEditCards(list);
} else {
settleRecentEditCards(list);
}
updateRecentEditResetButton();
requestDashboardOverflowScale();
}
function renderRecentRowsIntoList(list, rows) {
if (!list) {
return;
}
list.innerHTML = (rows || []).map(function (item) {
const diff = Number(item.sizediff || 0);
const diffText = diff > 0 ? '+' + diff : String(diff);
const diffClass = diff > 0 ? 'csn-diff-pos' : diff < 0 ? 'csn-diff-neg' : 'csn-diff-zero';
const title = item.title || '条目名称';
const summary = item.comment || '编辑摘要';
const href = mw.util.getUrl(title);
const time = formatRelativeTime(parseMediaWikiDate(item.timestamp));
return createRecentItemHtml(title, summary, diffText, time, href, diffClass);
}).join('');
}
function getRecentEditPageRows(pageIndex) {
const page = Math.max(0, Number(pageIndex || 0));
const start = page * RECENT_EDIT_LIMIT;
return recentEditPool.slice(start, start + RECENT_EDIT_LIMIT);
}
function getRecentEditMaxPageIndex() {
if (!recentEditPool.length || recentEditPool.length <= RECENT_EDIT_LIMIT) {
return 0;
}
// 除第一页外,只允许翻到完整页;避免出现半页或空页。
return Math.max(0, Math.floor(recentEditPool.length / RECENT_EDIT_LIMIT) - 1);
}
function getRecentEditTargetPageState(targetPage) {
if (targetPage < 0) {
return {
available: false,
reason: 'boundary'
};
}
if (targetPage === 0 && recentEditPool.length > 0) {
return {
available: true,
reason: 'ready'
};
}
const targetStart = targetPage * RECENT_EDIT_LIMIT;
const targetEnd = targetStart + RECENT_EDIT_LIMIT;
if (targetEnd <= recentEditPool.length) {
return {
available: true,
reason: 'ready'
};
}
return {
available: false,
reason: recentEditPoolComplete ? 'boundary' : 'pending'
};
}
function installRecentEditWheelPager() {
const card = document.querySelector('.csn-recent-card');
if (!card || recentEditWheelInstalled) {
return;
}
recentEditWheelInstalled = true;
card.addEventListener('wheel', function (event) {
handleRecentEditWheel(event);
}, { passive: false });
const resetButton = document.getElementById('csn-recent-page-reset');
if (resetButton) {
resetButton.addEventListener('pointerdown', function () {
resetButton.classList.add('csn-recent-page-reset-pressed');
}, { passive: true });
resetButton.addEventListener('pointerup', function () {
resetButton.classList.remove('csn-recent-page-reset-pressed');
}, { passive: true });
resetButton.addEventListener('pointercancel', function () {
resetButton.classList.remove('csn-recent-page-reset-pressed');
}, { passive: true });
resetButton.addEventListener('pointerleave', function () {
resetButton.classList.remove('csn-recent-page-reset-pressed');
}, { passive: true });
resetButton.addEventListener('click', function (event) {
event.preventDefault();
event.stopPropagation();
resetButton.classList.remove('csn-recent-page-reset-pressed');
resetButton.classList.remove('csn-recent-page-reset-pop');
void resetButton.offsetWidth;
resetButton.classList.add('csn-recent-page-reset-pop');
// 先完整播放“放大 -> 轻微回收 -> 贴回原样”的弹性反馈,再回第一页。
window.setTimeout(function () {
returnRecentEditsToFirstPage();
}, 560);
window.setTimeout(function () {
resetButton.classList.remove('csn-recent-page-reset-pop');
}, 620);
});
}
}
function updateRecentEditResetButton() {
const button = document.getElementById('csn-recent-page-reset');
if (!button) {
return;
}
if (recentEditPageIndex > 0) {
button.classList.add('csn-recent-page-reset-visible');
} else {
button.classList.remove('csn-recent-page-reset-visible');
button.classList.remove('csn-recent-page-reset-pressed');
button.classList.remove('csn-recent-page-reset-pop');
}
}
function returnRecentEditsToFirstPage() {
const list = document.getElementById('csn-recent-list');
if (!list || recentEditPageAnimating || recentEditPageIndex <= 0) {
playRecentEditPageBounce(list, -1);
return;
}
recentEditWheelLockedUntil = performance.now() + 560;
flipRecentEditPage(list, 0, -1);
}
function handleRecentEditWheel(event) {
const list = document.getElementById('csn-recent-list');
if (!list || !recentEditPool.length) {
return;
}
const delta = Number(event.deltaY || 0);
if (Math.abs(delta) < 8) {
return;
}
const direction = delta > 0 ? 1 : -1;
const now = performance.now();
if (recentEditPageAnimating || now < recentEditWheelLockedUntil) {
event.preventDefault();
return;
}
const targetPage = recentEditPageIndex + direction;
const state = getRecentEditTargetPageState(targetPage);
if (!state.available) {
// 鼠标在最近编辑区域内时,边界和未加载完成都只触发模块回弹,不让网页跟着滑动。
event.preventDefault();
playRecentEditPageBounce(list, direction);
recentEditWheelLockedUntil = now + 460;
return;
}
event.preventDefault();
recentEditWheelLockedUntil = now + 560;
flipRecentEditPage(list, targetPage, direction);
}
function flipRecentEditPage(list, targetPage, direction) {
if (!list || recentEditPageAnimating) {
return;
}
const rows = getRecentEditPageRows(targetPage);
if (!rows.length || (targetPage > 0 && rows.length < RECENT_EDIT_LIMIT)) {
playRecentEditPageBounce(list, direction);
return;
}
const outClass = direction > 0 ? 'csn-recent-page-out-up' : 'csn-recent-page-out-down';
const inClass = direction > 0 ? 'csn-recent-page-in-up' : 'csn-recent-page-in-down';
recentEditPageAnimating = true;
clearRecentPageMotionClasses(list);
list.classList.add(outClass);
window.setTimeout(function () {
recentEditPageIndex = targetPage;
updateRecentEditResetButton();
renderRecentRowsIntoList(list, rows);
settleRecentEditCards(list);
clearRecentPageMotionClasses(list);
list.classList.add(inClass);
window.setTimeout(function () {
clearRecentPageMotionClasses(list);
settleRecentEditCards(list);
updateRecentEditResetButton();
recentEditPageAnimating = false;
if (pendingRecentEditPoolRefresh) {
pendingRecentEditPoolRefresh = false;
renderRecentEdits(recentEditPool, {
complete: recentEditPoolComplete
});
}
requestDashboardOverflowScale();
}, 520);
}, 240);
}
function playRecentEditPageBounce(list, direction) {
if (!list) {
return;
}
clearRecentPageMotionClasses(list);
void list.offsetWidth;
list.classList.add(direction > 0 ? 'csn-recent-page-bounce-up' : 'csn-recent-page-bounce-down');
window.setTimeout(function () {
list.classList.remove('csn-recent-page-bounce-up');
list.classList.remove('csn-recent-page-bounce-down');
}, 460);
}
function clearRecentPageMotionClasses(list) {
if (!list) {
return;
}
list.classList.remove('csn-recent-page-out-up');
list.classList.remove('csn-recent-page-out-down');
list.classList.remove('csn-recent-page-in-up');
list.classList.remove('csn-recent-page-in-down');
list.classList.remove('csn-recent-page-bounce-up');
list.classList.remove('csn-recent-page-bounce-down');
}
function createRecentItemHtml(title, summary, diffText, timeText, href, diffClass) {
const safeDiffClass = diffClass || 'csn-diff-zero';
return '' +
'<div class="csn-recent-item">' +
'<div class="csn-recent-main">' +
'<a class="csn-page-link" href="' + escapeAttr(href) + '" title="' + escapeAttr(title) + '">' + escapeHtml(title) + '</a>' +
'<div class="csn-summary" title="' + escapeAttr(summary) + '">' + escapeHtml(summary) + '</div>' +
'</div>' +
'<div class="csn-side">' +
'<span class="' + safeDiffClass + '">' + escapeHtml(diffText || '') + '</span>' +
'<span class="csn-time">' + escapeHtml(timeText || '时间') + '</span>' +
'</div>' +
'</div>';
}
let pendingTopPagesForMobile = null;
let topPagesObserverInstalled = false;
function shouldDeferTopPageSortAnimation() {
return !isElementTopPastViewportHalf(document.querySelector('.csn-top-card'));
}
function isElementFullyInViewport(el) {
if (!el) {
return true;
}
const rect = el.getBoundingClientRect();
const vh = window.innerHeight || document.documentElement.clientHeight || 0;
const vw = window.innerWidth || document.documentElement.clientWidth || 0;
if (!vh || !vw) {
return true;
}
// “完整出现在屏幕”必须是真的完整可见;容器比视口高/宽时不能误判为已触发。
if (rect.height > vh || rect.width > vw) {
return false;
}
return rect.top >= 0 && rect.bottom <= vh && rect.left >= 0 && rect.right <= vw;
}
function isElementTopPastViewportHalf(el) {
if (!el) {
return true;
}
const rect = el.getBoundingClientRect();
const vh = window.innerHeight || document.documentElement.clientHeight || 0;
const vw = window.innerWidth || document.documentElement.clientWidth || 0;
if (!vh) {
return true;
}
// 移动端沿用“顶部过半”触发;桌面端只要组件进入视口约 15% 就触发。
// 桌面端按可见高度计算,避免大卡片必须滚到屏幕中间才开始动画。
if (vw > 980) {
const visibleHeight = Math.min(rect.bottom, vh) - Math.max(rect.top, 0);
const requiredVisible = Math.min(rect.height || vh, vh) * 0.15;
return visibleHeight >= Math.max(1, requiredVisible) && rect.bottom > 0 && rect.top < vh;
}
return rect.top <= vh * 0.5 && rect.bottom > 0;
}
let gatedAnimationQueue = [];
let gatedAnimationRaf = 0;
let gatedAnimationWatcherInstalled = false;
function runWhenVisibilityGatePassed(el, test, callback) {
const gateTest = typeof test === 'function' ? test : isElementFullyInViewport;
if (!el || gateTest(el)) {
callback();
return;
}
gatedAnimationQueue.push({
el: el,
test: gateTest,
callback: callback
});
installGatedAnimationWatcher();
scheduleGatedAnimationFlush();
}
function runWhenFullyVisible(el, callback) {
runWhenVisibilityGatePassed(el, isElementFullyInViewport, callback);
}
function runWhenTopPastViewportHalf(el, callback) {
runWhenVisibilityGatePassed(el, isElementTopPastViewportHalf, callback);
}
function installGatedAnimationWatcher() {
if (gatedAnimationWatcherInstalled) {
return;
}
gatedAnimationWatcherInstalled = true;
window.addEventListener('scroll', scheduleGatedAnimationFlush, { passive: true });
window.addEventListener('resize', scheduleGatedAnimationFlush, { passive: true });
}
function scheduleGatedAnimationFlush() {
if (gatedAnimationRaf) {
return;
}
gatedAnimationRaf = window.requestAnimationFrame(flushGatedAnimationQueue);
}
function flushGatedAnimationQueue() {
gatedAnimationRaf = 0;
if (!gatedAnimationQueue.length) {
return;
}
const pending = [];
gatedAnimationQueue.forEach(function (item) {
if (!item || !item.el || !document.documentElement.contains(item.el)) {
return;
}
if (item.test(item.el)) {
item.callback();
} else {
pending.push(item);
}
});
gatedAnimationQueue = pending;
}
function installTopPageVisibilityObserver() {
if (topPagesObserverInstalled) {
return;
}
topPagesObserverInstalled = true;
const card = document.querySelector('.csn-top-card');
if (!card) {
return;
}
const flush = function () {
if (!pendingTopPagesForMobile || shouldDeferTopPageSortAnimation()) {
return;
}
const data = normalizeTopPageRows(pendingTopPagesForMobile);
const list = document.getElementById('csn-top-list');
const shouldPlayEnter = list && list.getAttribute('data-top-enter-pending') === '1';
pendingTopPagesForMobile = null;
if (shouldPlayEnter) {
// 容器顶部过半后,先让当前“索引顺序/占位”列表进场;
// 不要在过半触发前直接替换成最终排序结果,否则用户看到时已经提前排好了。
list.removeAttribute('data-top-enter-pending');
playTopPageEnterAnimation(list);
window.setTimeout(function () {
enqueueTopPageRender(data);
}, 760);
return;
}
enqueueTopPageRender(data);
};
if (window.IntersectionObserver) {
const observer = new IntersectionObserver(function () {
flush();
}, {
threshold: [0, 0.5, 0.98, 1]
});
observer.observe(card);
}
window.addEventListener('scroll', flush, { passive: true });
window.addEventListener('resize', flush, { passive: true });
}
let topPageSortQueue = [];
let topPageSortTimer = 0;
let pendingTopPageTargetItems = null;
let lastRenderedTopSignature = '';
let lastRenderedTopItems = [];
function getTopPageSignature(items) {
return normalizeTopPageRows(items).map(function (item, index) {
return getTopPageKey(item, index) + ':' + String(item && item.views ? item.views : 0) + ':' + (item && item.pending ? 'p' : 'r');
}).join('|');
}
function getTopPageOrderSignature(items) {
return normalizeTopPageRows(items).map(function (item, index) {
return getTopPageIdentity(item, index);
}).join('|');
}
function enqueueTopPageRender(items) {
if (shouldDeferTopPageSortAnimation()) {
pendingTopPagesForMobile = normalizeTopPageRows(items);
installTopPageVisibilityObserver();
return;
}
const signature = getTopPageSignature(items);
if (signature === lastRenderedTopSignature) {
return;
}
const currentOrderSignature = getTopPageOrderSignature(lastRenderedTopItems);
const targetOrderSignature = getTopPageOrderSignature(items);
// 只有数值变化、排序没变时,直接更新数字和进度条,不走换位队列。
if (currentOrderSignature && currentOrderSignature === targetOrderSignature) {
renderTopPagesNow(items, {
skipReorderAnimation: true,
forceValueUpdate: !!(topPageSortTimer || topPageSortQueue.length),
quietValueUpdate: !!(topPageSortTimer || topPageSortQueue.length)
});
return;
}
// 新数据到来时不要等上一轮排序完整跑完。
// 直接以当前已显示帧为起点重新规划,让新候补可以在上一批条目还在上移时加入。
if (topPageSortTimer || topPageSortQueue.length) {
retargetTopPageSortTowards(items);
return;
}
startTopPageSortTowards(items);
}
function retargetTopPageSortTowards(items) {
if (topPageSortTimer) {
window.clearTimeout(topPageSortTimer);
topPageSortTimer = 0;
}
topPageSortQueue = [];
pendingTopPageTargetItems = null;
startTopPageSortTowards(items);
}
function startTopPageSortTowards(items) {
topPageSortQueue = buildTopPageTransitionFrames(lastRenderedTopItems, items);
if (!topPageSortQueue.length) {
topPageSortQueue = [normalizeTopPageRows(items)];
}
runNextTopPageSort();
}
function runNextTopPageSort() {
if (shouldDeferTopPageSortAnimation()) {
if (topPageSortTimer) {
window.clearTimeout(topPageSortTimer);
topPageSortTimer = 0;
}
if (topPageSortQueue.length) {
pendingTopPagesForMobile = topPageSortQueue.length ? topPageSortQueue[topPageSortQueue.length - 1] : pendingTopPagesForMobile;
}
topPageSortQueue = [];
installTopPageVisibilityObserver();
return;
}
const next = topPageSortQueue.shift();
if (!next) {
topPageSortTimer = 0;
if (!pendingTopPageTargetItems && lastRenderedTopItems && lastRenderedTopItems.length) {
window.setTimeout(function () {
if (shouldDeferTopPageSortAnimation()) {
pendingTopPagesForMobile = lastRenderedTopItems;
installTopPageVisibilityObserver();
return;
}
renderTopPagesNow(lastRenderedTopItems, {
skipReorderAnimation: true,
forceValueUpdate: true,
quietValueUpdate: true
});
}, 120);
}
if (pendingTopPageTargetItems) {
const target = pendingTopPageTargetItems;
pendingTopPageTargetItems = null;
if (getTopPageSignature(target) !== lastRenderedTopSignature) {
startTopPageSortTowards(target);
}
}
return;
}
renderTopPagesNow(next, {
freezeStableValueUpdates: true
});
topPageSortTimer = window.setTimeout(function () {
topPageSortTimer = 0;
runNextTopPageSort();
}, TOP_PAGE_FRAME_DELAY_MS);
}
function renderTopPages(items) {
if (shouldDeferTopPageSortAnimation()) {
pendingTopPagesForMobile = normalizeTopPageRows(items);
installTopPageVisibilityObserver();
const list = document.getElementById('csn-top-list');
if (!list || list.getAttribute('data-top-initialized') !== '1') {
renderTopPagesNow(items, { skipReorderAnimation: true });
if (list) {
list.setAttribute('data-top-enter-pending', '1');
}
}
return;
}
const list = document.getElementById('csn-top-list');
if (!list || list.getAttribute('data-top-initialized') !== '1') {
renderTopPagesNow(items);
return;
}
enqueueTopPageRender(items);
}
function buildTopPageTransitionFrames(currentItems, targetItems) {
const targetRows = normalizeTopPageRows(targetItems);
let currentRows = normalizeTopPageRows(currentItems && currentItems.length ? currentItems : targetRows);
const frames = [];
const maxFrames = 80;
if (getTopPageSignature(currentRows) === getTopPageSignature(targetRows)) {
return frames;
}
function sameOrder(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (getTopPageIdentity(a[i], i) !== getTopPageIdentity(b[i], i)) {
return false;
}
}
return true;
}
function cloneRows(rows) {
return rows.map(function (item) {
if (!item) {
return null;
}
return {
title: item.title,
timestamp: item.timestamp,
views: Number(item.views) || 0,
pending: !!item.pending
};
});
}
function cloneItem(item) {
if (!item) {
return null;
}
return {
title: item.title,
timestamp: item.timestamp,
views: Number(item.views) || 0,
pending: !!item.pending
};
}
while (!sameOrder(currentRows, targetRows) && frames.length < maxFrames) {
const usedIndexes = new Set();
let insertedCandidate = false;
let changed = false;
for (let i = 0; i < targetRows.length; i++) {
const wantedIdentity = getTopPageIdentity(targetRows[i], i);
const currentIdentity = getTopPageIdentity(currentRows[i], i);
if (wantedIdentity === currentIdentity) {
// 同一条目留在原位时,也要更新浏览量和进度条,但不制造换位。
currentRows[i] = targetRows[i];
continue;
}
let foundIndex = -1;
for (let j = i + 1; j < currentRows.length; j++) {
if (getTopPageIdentity(currentRows[j], j) === wantedIdentity) {
foundIndex = j;
break;
}
}
if (foundIndex > i) {
const swapIndex = foundIndex - 1;
// 同一帧允许多个不相邻的条目并行上移;
// 但同一个槽位一帧只动一次,避免条目互相穿模。
if (usedIndexes.has(foundIndex) || usedIndexes.has(swapIndex)) {
continue;
}
const temp = currentRows[swapIndex];
currentRows[swapIndex] = currentRows[foundIndex];
currentRows[foundIndex] = temp;
usedIndexes.add(foundIndex);
usedIndexes.add(swapIndex);
changed = true;
continue;
}
if (!insertedCandidate) {
// 候补仍然只从末位进入。
// 一帧最多加入一个新候补,后续帧再加入下一个;这样不会把末尾两个候补同时拍进去。
currentRows[currentRows.length - 1] = cloneItem(targetRows[i]);
usedIndexes.add(currentRows.length - 1);
insertedCandidate = true;
changed = true;
}
}
if (!changed) {
break;
}
frames.push(cloneRows(currentRows));
}
// 不再强行补一个“最终完整目标帧”。
// 末位候补仍按帧进入;多条已在列表内的条目可以并行上移,但不会一口气跳到最终排序。
return frames;
}
function getTopPageIdentity(item, index) {
if (item && item.title) {
return 'page-' + item.title;
}
return 'placeholder-' + index;
}
function renderTopPagesNow(items, options) {
const list = document.getElementById('csn-top-list');
if (!list) {
return;
}
const rows = normalizeTopPageRows(items);
const maxViews = Math.max.apply(null, rows.map(function (item) {
return item ? Number(item.views) || 0 : 0;
}).concat([1]));
const previousRects = getTopPageRects(list);
const existingNodes = getTopPageNodeMap(list);
const desiredKeys = new Set();
const fragment = document.createDocumentFragment();
rows.forEach(function (item, index) {
const key = getTopPageKey(item, index);
const isNewNode = !existingNodes.has(key);
const node = existingNodes.get(key) || createTopPageNode(key, index);
desiredKeys.add(key);
updateTopPageNode(node, item, index, maxViews, Object.assign({}, options || {}, {
isNewNode: isNewNode
}));
node.setAttribute('data-top-hydrated', '1');
fragment.appendChild(node);
});
Array.from(list.querySelectorAll('.csn-top-item')).forEach(function (node) {
const key = node.getAttribute('data-top-key') || '';
if (!desiredKeys.has(key)) {
floatAndRemoveTopPageNode(list, node, previousRects);
}
});
list.appendChild(fragment);
list.setAttribute('data-top-initialized', '1');
lastRenderedTopItems = rows.map(function (item) {
if (!item) {
return null;
}
return {
title: item.title,
timestamp: item.timestamp,
views: Number(item.views) || 0,
pending: !!item.pending
};
});
lastRenderedTopSignature = getTopPageSignature(lastRenderedTopItems);
if (options && options.skipReorderAnimation) {
Array.from(list.querySelectorAll('.csn-top-item')).forEach(function (node) {
node.classList.remove('csn-top-enter');
node.classList.remove('csn-top-exit');
node.classList.remove('csn-top-moving');
node.style.transform = '';
node.style.opacity = '';
node.style.filter = '';
node.style.transition = '';
});
requestDashboardOverflowScale();
return;
}
animateTopPageReorder(list, previousRects);
requestDashboardOverflowScale();
}
function normalizeTopPageRows(items) {
const rows = (items || []).slice(0, TOP_VIEW_LIMIT);
while (rows.length < TOP_VIEW_LIMIT) {
rows.push(null);
}
return rows;
}
function getTopPageKey(item, index) {
if (!item || !item.title) {
return 'placeholder-' + index;
}
return 'page-' + item.title;
}
function getTopPageRects(list) {
const map = new Map();
Array.from(list.querySelectorAll('.csn-top-item')).forEach(function (node) {
const key = node.getAttribute('data-top-key');
if (key) {
map.set(key, node.getBoundingClientRect());
}
});
return map;
}
function getTopPageNodeMap(list) {
const map = new Map();
Array.from(list.querySelectorAll('.csn-top-item')).forEach(function (node) {
const key = node.getAttribute('data-top-key');
if (key) {
map.set(key, node);
}
});
return map;
}
function floatAndRemoveTopPageNode(list, node, previousRects) {
if (!list || !node) {
return;
}
// v64:不再把退场项改成 absolute 浮层。
// 之前最后两项会看起来并排,就是旧节点浮在列表上,新节点又进入同一行附近造成的视觉重叠。
// 这里直接移除旧节点,让一列布局永远保持干净;排序位移动画仍由保留节点的 FLIP 负责。
if (node.parentNode) {
node.remove();
}
}
function createTopPageNode(key, index) {
const node = document.createElement('div');
node.className = 'csn-top-item csn-top-enter';
node.setAttribute('data-top-key', key);
node.setAttribute('data-row-index', String(index));
node.innerHTML = '' +
'<div class="csn-top-name-row">' +
'<a class="csn-top-name" href="#">条目名称</a>' +
'<span class="csn-view-count" data-raw-value="0" data-target-value="0">0</span>' +
'</div>' +
'<div class="csn-bar-track"><span class="csn-bar" data-current-width="0" data-target-width="0" style="width:0%;"></span></div>';
return node;
}
function shouldUseStaticTopPageCount(index) {
return index >= Math.max(0, TOP_VIEW_LIMIT - 3);
}
function setStaticInlineNumberText(el, value) {
if (!el) {
return;
}
const target = Number(value || 0);
const targetText = formatNumber(target);
el.setAttribute('data-raw-value', String(target));
el.setAttribute('data-display-value', targetText);
el.setAttribute('data-rolling-render-token', 'static:' + String(Date.now()) + ':' + String(Math.random()));
el.classList.remove('csn-number-changing');
el.textContent = targetText;
}
function normalizeStaticInlineNumberText(el, value) {
if (!el) {
return;
}
const target = Number(value || 0);
const targetText = formatNumber(target);
// 倒数三项不保留滚动槽,避免复用节点或旧定时器让数字继续播放动画。
if (el.textContent !== targetText || el.querySelector('.csn-number-wheel')) {
setStaticInlineNumberText(el, target);
}
}
function updateTopPageNode(node, item, index, maxViews, options) {
const title = item && item.title ? item.title : '条目名称';
const href = item && item.title ? mw.util.getUrl(item.title) : '#';
const views = item ? Number(item.views) || 0 : 0;
const percent = views > 0 ? Math.max(2, Math.round((views / maxViews) * 100)) : 0;
const titleLink = node.querySelector('.csn-top-name');
const countEl = node.querySelector('.csn-view-count');
const bar = node.querySelector('.csn-bar');
const freezeStableValueUpdates = options && options.freezeStableValueUpdates && !options.isNewNode && !options.forceValueUpdate;
node.setAttribute('data-row-index', String(index));
if (titleLink) {
titleLink.textContent = title;
titleLink.setAttribute('href', href);
}
if (freezeStableValueUpdates) {
node.setAttribute('data-pending-views', String(views));
node.setAttribute('data-pending-max-views', String(maxViews));
return;
}
if (countEl) {
const oldViews = Number(countEl.getAttribute('data-raw-value') || 0);
if (oldViews !== views) {
if (shouldUseStaticTopPageCount(index)) {
setStaticInlineNumberText(countEl, views);
} else {
animateInlineNumberText(countEl, views);
}
} else if (shouldUseStaticTopPageCount(index)) {
normalizeStaticInlineNumberText(countEl, views);
}
}
if (bar) {
const newPercent = Math.max(0, Math.min(100, percent));
const oldPercent = Number(bar.getAttribute('data-current-width') || 0);
bar.setAttribute('data-target-width', String(newPercent));
bar.setAttribute('data-current-width', String(newPercent));
if (options && options.quietValueUpdate && !options.isNewNode) {
bar.style.transition = 'none';
bar.style.width = newPercent + '%';
window.requestAnimationFrame(function () {
bar.style.transition = '';
});
} else {
if (options && options.forceValueUpdate && Math.abs(oldPercent - newPercent) > 0.5) {
bar.style.transitionDuration = '0.62s';
window.setTimeout(function () {
bar.style.transitionDuration = '';
}, 680);
}
bar.style.width = newPercent + '%';
}
}
node.removeAttribute('data-pending-views');
node.removeAttribute('data-pending-max-views');
}
function playTopPageEnterAnimation(list) {
if (!list) {
return;
}
const nodes = Array.from(list.querySelectorAll('.csn-top-item'));
if (!nodes.length) {
return;
}
nodes.forEach(function (node) {
node.classList.remove('csn-top-exit');
node.classList.remove('csn-top-moving');
node.style.transform = '';
node.style.opacity = '';
node.style.filter = '';
node.style.transition = '';
node.classList.add('csn-top-enter');
});
window.requestAnimationFrame(function () {
window.requestAnimationFrame(function () {
nodes.forEach(function (node) {
node.classList.remove('csn-top-enter');
});
});
});
}
function animateTopPageReorder(list, previousRects) {
Array.from(list.querySelectorAll('.csn-top-item')).forEach(function (node) {
const key = node.getAttribute('data-top-key') || '';
const previous = previousRects.get(key);
const current = node.getBoundingClientRect();
if (previous) {
const dx = previous.left - current.left;
const dy = previous.top - current.top;
if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) {
node.classList.add('csn-top-moving');
node.style.transition = 'none';
node.style.transform = 'translate(' + dx.toFixed(1) + 'px, ' + dy.toFixed(1) + 'px)';
window.requestAnimationFrame(function () {
node.style.transition = '';
node.style.transform = '';
window.setTimeout(function () {
node.classList.remove('csn-top-moving');
}, 700);
});
}
} else {
window.requestAnimationFrame(function () {
node.classList.remove('csn-top-enter');
});
}
});
}
function makeFirstEditedArticlePages(contributions) {
const byTitle = new Map();
contributions.forEach(function (item) {
const title = item.title;
const timestamp = item.timestamp;
if (!title || !timestamp || !isArticleContribution(item)) {
return;
}
const existing = byTitle.get(title);
// 这里必须取“第一次编辑该条目”的时间。
// 浏览量统计定义为:自您首次编辑该条目之后至今的浏览量。
if (!existing || String(timestamp) < String(existing.timestamp)) {
byTitle.set(title, {
title: title,
timestamp: timestamp
});
}
});
return Array.from(byTitle.values()).sort(function (a, b) {
return String(a.timestamp || '').localeCompare(String(b.timestamp || ''));
});
}
function isArticleContribution(item) {
if (typeof item.ns === 'number') {
return item.ns === 0;
}
return String(item.title || '').indexOf(':') === -1 && String(item.title || '').indexOf(':') === -1;
}
async function hydrateViewStatsProgressively(pages) {
if (!pages || !pages.length) {
animateViewsNumberTextWhenReady(0);
renderTopPages([]);
return;
}
const statsMap = new Map();
const cached = getCachedViewStats(pages);
// 先按条目的索引顺序放上去:先显示页面名和 0,
// 读取到浏览量后再更新数值,并按浏览量重新排序。
renderTopPages(pages.slice(0, TOP_VIEW_LIMIT).map(function (page) {
return {
title: page.title,
timestamp: page.timestamp,
views: 0,
pending: true
};
}));
animateViewsNumberTextWhenReady(0);
cached.forEach(function (item) {
statsMap.set(item.title, item);
});
if (cached.length) {
renderViewStats(mergeIndexedPlaceholders(pages, Array.from(statsMap.values())));
}
await streamViewStats(pages, statsMap);
}
async function streamViewStats(pages, statsMap) {
let cursor = 0;
let completed = 0;
let lastRender = 0;
async function worker() {
while (cursor < pages.length) {
const page = pages[cursor++];
if (statsMap.has(page.title)) {
completed++;
continue;
}
try {
const firstEditedAt = parseMediaWikiDate(page.timestamp);
const views = await getViewsAfterEdit(page.title, firstEditedAt);
const item = {
title: page.title,
timestamp: page.timestamp,
views: Number(views || 0)
};
writePageviewCache(page.title, page.timestamp, item.views);
statsMap.set(page.title, item);
} catch (error) {
console.warn('[总览] 浏览量读取失败:', page.title, error);
statsMap.set(page.title, {
title: page.title,
timestamp: page.timestamp,
views: 0
});
}
completed++;
// 按读取完成顺序逐步显示,并排序;节流到约每 80ms 一次,避免 DOM 过度刷新。
const now = performance.now();
if (now - lastRender > 80 || completed <= TOP_VIEW_LIMIT || completed === pages.length) {
lastRender = now;
renderViewStats(mergeIndexedPlaceholders(pages, Array.from(statsMap.values())));
}
}
}
const workers = [];
const count = Math.max(1, Math.min(PAGEVIEW_CONCURRENCY, pages.length));
for (let i = 0; i < count; i++) {
workers.push(worker());
}
await Promise.all(workers);
renderViewStats(mergeIndexedPlaceholders(pages, Array.from(statsMap.values())));
}
function renderViewStats(stats) {
const list = stats || [];
const resolved = list.filter(function (item) {
return item && !item.pending;
}).sort(function (a, b) {
const viewDiff = (Number(b.views) || 0) - (Number(a.views) || 0);
if (viewDiff !== 0) {
return viewDiff;
}
return String(a.title || '').localeCompare(String(b.title || ''));
});
const placeholders = list.filter(function (item) {
return item && item.pending;
});
const normalized = resolved.concat(placeholders);
const totalViews = resolved.reduce(function (sum, item) {
return sum + (Number(item.views) || 0);
}, 0);
animateViewsNumberTextWhenReady(totalViews);
renderTopPages(normalized.slice(0, TOP_VIEW_LIMIT));
}
function mergeIndexedPlaceholders(pages, stats) {
const map = new Map();
(stats || []).forEach(function (item) {
if (item && item.title) {
map.set(item.title, item);
}
});
return (pages || []).map(function (page) {
if (map.has(page.title)) {
return map.get(page.title);
}
return {
title: page.title,
timestamp: page.timestamp,
views: 0,
pending: true
};
});
}
function mergeViewStats() {
const map = new Map();
Array.from(arguments).forEach(function (list) {
(list || []).forEach(function (item) {
if (!item || !item.title) {
return;
}
map.set(item.title, item);
});
});
return Array.from(map.values());
}
function getCachedViewStats(pages) {
const result = [];
pages.forEach(function (page) {
const cached = readPageviewCache(page.title, page.timestamp);
if (cached) {
result.push(cached);
}
});
return result;
}
function getPageviewCacheKey(title, timestamp) {
return PAGEVIEW_CACHE_KEY_PREFIX + encodeURIComponent(String(title || '')) + ':' + String(timestamp || '');
}
function readPageviewCache(title, timestamp) {
try {
const raw = localStorage.getItem(getPageviewCacheKey(title, timestamp));
if (!raw) {
return null;
}
const data = JSON.parse(raw);
if (!data || Date.now() - Number(data.cachedAt || 0) > PAGEVIEW_CACHE_MAX_AGE_MS) {
return null;
}
return {
title: title,
timestamp: timestamp,
views: Number(data.views || 0)
};
} catch (e) {
return null;
}
}
function writePageviewCache(title, timestamp, views) {
try {
localStorage.setItem(getPageviewCacheKey(title, timestamp), JSON.stringify({
views: Number(views || 0),
cachedAt: Date.now()
}));
} catch (e) {}
}
async function getViewStats(pages) {
const stats = [];
let cursor = 0;
async function worker() {
while (cursor < pages.length) {
const page = pages[cursor++];
try {
const firstEditedAt = parseMediaWikiDate(page.timestamp);
const views = await getViewsAfterEdit(page.title, firstEditedAt);
writePageviewCache(page.title, page.timestamp, views);
stats.push({
title: page.title,
timestamp: page.timestamp,
views: views
});
} catch (error) {
console.warn('[总览] 浏览量读取失败:', page.title, error);
stats.push({
title: page.title,
timestamp: page.timestamp,
views: 0
});
}
}
}
const workers = [];
const count = Math.max(1, Math.min(PAGEVIEW_CONCURRENCY, pages.length));
for (let i = 0; i < count; i++) {
workers.push(worker());
}
await Promise.all(workers);
stats.sort(function (a, b) {
const viewDiff = (Number(b.views) || 0) - (Number(a.views) || 0);
if (viewDiff !== 0) {
return viewDiff;
}
return String(a.title || '').localeCompare(String(b.title || ''));
});
return stats;
}
async function getViewsAfterEdit(title, editedAt) {
let start = startOfDay(editedAt || new Date());
if (start < PAGEVIEWS_EARLIEST) {
start = PAGEVIEWS_EARLIEST;
}
const article = encodeURIComponent(String(title || '').replace(/ /g, '_'));
const startStamp = toPageviewsDate(start);
const project = mw.config.get('wgServerName') || 'lib.yinfer.top';
// 加速:优先请求 wikimedia.org + all-agents + 默认延迟日。
// 只有失败时才回退到更慢的多组合尝试。
const preferredEnd = startOfDay(new Date(Date.now() - PAGEVIEWS_INITIAL_END_LAG_DAYS * 86400000));
if (start <= preferredEnd) {
const preferredUrl = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/' +
project + '/all-access/all-agents/' + article + '/daily/' + startStamp + '/' + toPageviewsDate(preferredEnd);
try {
const response = await fetch(preferredUrl, {
credentials: 'omit',
headers: {
Accept: 'application/json'
}
});
if (response.ok) {
const data = await response.json();
const items = Array.isArray(data.items) ? data.items : [];
return items.reduce(function (sum, item) {
return sum + (Number(item.views) || 0);
}, 0);
}
} catch (e) {}
}
const sameOriginBase = mw.config.get('wgServer') + '/api/rest_v1/metrics/pageviews/per-article/';
const wikimediaBase = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/';
const bases = [wikimediaBase, sameOriginBase];
for (let lag = PAGEVIEWS_INITIAL_END_LAG_DAYS; lag <= PAGEVIEWS_MAX_END_LAG_DAYS; lag++) {
const end = startOfDay(new Date(Date.now() - lag * 86400000));
if (start > end) {
continue;
}
const endStamp = toPageviewsDate(end);
for (let a = 0; a < PAGEVIEWS_AGENT_PRIORITY.length; a++) {
const agent = PAGEVIEWS_AGENT_PRIORITY[a];
for (let b = 0; b < bases.length; b++) {
const url = bases[b] +
project + '/all-access/' + agent + '/' + article + '/daily/' + startStamp + '/' + endStamp;
try {
const response = await fetch(url, {
credentials: 'omit',
headers: {
Accept: 'application/json'
}
});
if (!response.ok) {
continue;
}
const data = await response.json();
const items = Array.isArray(data.items) ? data.items : [];
return items.reduce(function (sum, item) {
return sum + (Number(item.views) || 0);
}, 0);
} catch (error) {}
}
}
}
return 0;
}
function sortNewestFirst(a, b) {
return String(b.timestamp || '').localeCompare(String(a.timestamp || ''));
}
function getEarliestContributionDate(contributions) {
if (!contributions || !contributions.length) {
return null;
}
const sorted = contributions.slice().sort(function (a, b) {
return String(a.timestamp || '').localeCompare(String(b.timestamp || ''));
});
return parseMediaWikiDate(sorted[0].timestamp);
}
function parseMediaWikiDate(value) {
if (!value) {
return null;
}
const d = new Date(value);
return Number.isNaN(d.getTime()) ? null : d;
}
function startOfDay(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}
function endOfYear(d) {
return new Date(d.getFullYear(), 11, 31);
}
function startOfWeek(d) {
const day = d.getDay();
const date = startOfDay(d);
date.setDate(date.getDate() - day);
return date;
}
function endOfWeek(d) {
const day = d.getDay();
const date = startOfDay(d);
date.setDate(date.getDate() + (6 - day));
return date;
}
function getPageviewsDisplayEndDate() {
return startOfDay(new Date(Date.now() - PAGEVIEWS_INITIAL_END_LAG_DAYS * 86400000));
}
function toDateKey(d) {
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function toPageviewsDate(d) {
return String(d.getFullYear()) + String(d.getMonth() + 1).padStart(2, '0') + String(d.getDate()).padStart(2, '0') + '00';
}
function formatShortDate(d) {
return String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
function formatMonthDay(d) {
return String(d.getMonth() + 1) + '月' + String(d.getDate()) + '日';
}
function formatFullNumber(value) {
return Math.round(Number(value || 0)).toLocaleString('en-US');
}
function formatNumber(value) {
const n = Number(value || 0);
const abs = Math.abs(n);
if (abs < 100000) {
return Math.round(n).toLocaleString('en-US');
}
return formatCompactNumber(n);
}
function formatCompactNumber(value) {
const n = Number(value || 0);
const abs = Math.abs(n);
const sign = n < 0 ? '-' : '';
if (abs >= 1000000000) {
return sign + trimCompactDecimal(abs / 1000000000) + 'B';
}
if (abs >= 1000000) {
return sign + trimCompactDecimal(abs / 1000000) + 'M';
}
return sign + trimCompactDecimal(abs / 1000) + 'K';
}
function trimCompactDecimal(value) {
if (value >= 100) {
return String(Math.round(value));
}
if (value >= 10) {
return String(Math.round(value * 10) / 10).replace(/\.0$/, '');
}
return String(Math.round(value * 10) / 10).replace(/\.0$/, '');
}
function formatRelativeTime(date) {
if (!date) {
return '时间';
}
const diffMs = Date.now() - date.getTime();
const min = Math.floor(diffMs / 60000);
const hour = Math.floor(min / 60);
const day = Math.floor(hour / 24);
if (min < 1) {
return '刚刚';
}
if (min < 60) {
return min + '分钟前';
}
if (hour < 24) {
return hour + '小时前';
}
if (day < 30) {
return day + '天前';
}
return formatMonthDay(date);
}
function animateInlineNumberText(el, value) {
if (!el) {
return;
}
const target = Number(value || 0);
const previousRaw = el.getAttribute('data-raw-value');
const previousText = previousRaw == null ? (el.textContent || '0') : formatNumber(Number(previousRaw || 0));
const targetText = formatNumber(target);
if (previousText === targetText && el.getAttribute('data-raw-value') === String(target)) {
return;
}
el.setAttribute('data-raw-value', String(target));
renderRollingNumber(el, previousText, targetText);
}
function getNumberAvailableWidth(el) {
if (!el) {
return 1;
}
const card = el.closest('.csn-total-card, .csn-views-card, .csn-card');
const body = el.closest('.csn-stat-body');
const source = body && body.clientWidth ? body : card;
const width = source && source.clientWidth ? source.clientWidth : (el.parentElement && el.parentElement.clientWidth ? el.parentElement.clientWidth : 0);
return Math.max(1, width - 22);
}
function fitBigNumberToContainer(el) {
if (!el || !el.classList || !el.classList.contains('csn-big-number')) {
return;
}
if (!el.getAttribute('data-base-font-size')) {
const computed = window.getComputedStyle(el);
const base = parseFloat(computed.fontSize) || 65;
el.setAttribute('data-base-font-size', String(base));
}
const baseFontSize = Number(el.getAttribute('data-base-font-size') || 65);
el.style.transform = '';
el.style.fontSize = baseFontSize + 'px';
const available = getNumberAvailableWidth(el);
const actual = Math.max(
1,
el.scrollWidth || 0,
el.getBoundingClientRect().width || 0
) + (el.id === 'csn-total-edits' ? 0 : 22);
const scale = Math.min(1, available / actual);
const fittedFontSize = Math.max(28, Math.floor(baseFontSize * scale));
el.style.fontSize = fittedFontSize + 'px';
}
function getComponentAnimationGateElement(el) {
if (!el) {
return null;
}
return el.closest && el.closest('.csn-card') ? el.closest('.csn-card') : el;
}
function animateCompactMetricNumberTextWhenReady(id, value) {
const el = document.getElementById(id);
if (!el) {
return;
}
const target = Number(value || 0);
const token = String(Date.now()) + ':' + String(Math.random());
const gate = getComponentAnimationGateElement(el);
el.setAttribute('data-gated-metric-target', String(target));
el.setAttribute('data-gated-metric-token', token);
runWhenTopPastViewportHalf(gate || el, function () {
if (el.getAttribute('data-gated-metric-token') !== token) {
return;
}
const pending = Number(el.getAttribute('data-gated-metric-target') || target || 0);
el.removeAttribute('data-gated-metric-target');
el.removeAttribute('data-gated-metric-token');
animateCompactMetricNumberText(id, pending);
});
}
function setTotalViewsRawCount(value) {
const raw = Number(value || 0);
const el = document.getElementById('csn-total-views');
totalViewsRawCount = raw;
if (el) {
el.setAttribute('data-full-raw-value', String(raw));
}
return raw;
}
function getTotalViewsRawCount() {
const el = document.getElementById('csn-total-views');
const attr = el ? el.getAttribute('data-full-raw-value') : null;
if (attr != null && attr !== '') {
return Number(attr || 0);
}
return Number(totalViewsRawCount || 0);
}
function animateViewsNumberTextWhenReady(value) {
const el = document.getElementById('csn-total-views');
if (!el) {
return;
}
const target = Number(value || 0);
const token = String(Date.now()) + ':' + String(Math.random());
const gate = getComponentAnimationGateElement(el);
setTotalViewsRawCount(target);
el.setAttribute('data-gated-views-target', String(target));
el.setAttribute('data-gated-views-token', token);
runWhenTopPastViewportHalf(gate || el, function () {
if (el.getAttribute('data-gated-views-token') !== token) {
return;
}
const pending = Number(el.getAttribute('data-gated-views-target') || target || 0);
el.removeAttribute('data-gated-views-target');
el.removeAttribute('data-gated-views-token');
renderViewsNumberTextByMode(pending);
});
}
function cancelViewsDisplayAnimationForModeSwitch(el) {
if (!el) {
return;
}
el.setAttribute('data-views-animation-token', 'mode-switch:' + String(Date.now()) + ':' + String(Math.random()));
el.setAttribute('data-views-animation-active', '0');
el.removeAttribute('data-pending-raw-value');
el.classList.remove('csn-views-number-changing');
}
function renderViewsNumberTextByMode(value, options) {
const raw = value == null ? getTotalViewsRawCount() : Number(value || 0);
if (viewsDisplayMode === 'full') {
animateViewsFullNumberText(raw);
} else {
animateViewsNumberText(raw, {
fromFullMode: !!(options && options.fromMode === 'full')
});
}
}
function animateViewsFullNumberText(value) {
const el = document.getElementById('csn-total-views');
if (!el) {
return;
}
const targetRaw = setTotalViewsRawCount(value == null ? getTotalViewsRawCount() : value);
const token = String(Date.now()) + ':' + String(Math.random());
const previousText = el.getAttribute('data-step-display') ||
el.getAttribute('data-display-value') ||
normalizeRenderedNumberText(el) ||
'0';
const targetText = formatFullNumber(targetRaw);
el.setAttribute('data-views-animation-token', token);
el.setAttribute('data-target-raw-value', String(targetRaw));
el.setAttribute('data-views-animation-active', '1');
el.setAttribute('data-display-value', targetText);
el.setAttribute('data-views-unit', 'full');
el.removeAttribute('data-current-compact-value');
el.removeAttribute('data-current-compact-suffix');
el.removeAttribute('data-pending-raw-value');
el.classList.remove('csn-views-number-changing');
void el.offsetWidth;
el.classList.add('csn-views-number-changing');
renderPlainStepText(el, previousText, targetText, {
changeStartIndex: getTailFlipStartIndex(previousText, targetText)
});
el.setAttribute('data-step-display', targetText);
el.setAttribute('data-current-raw-value', String(targetRaw));
fitPlainViewsNumber(el);
window.setTimeout(function () {
finishViewsAnimation(el, targetRaw, targetText, token, {
unit: 'full'
});
}, VIEWS_PLAIN_FINAL_SETTLE_MS);
}
function getViewsDisplayTextForMode(raw, mode) {
const safeRaw = Number(raw || 0);
return mode === 'full' ? formatFullNumber(safeRaw) : getViewsCompactNumberParts(safeRaw).text;
}
function animateViewsModeCrossfade(raw, fromMode, toMode) {
// 格式切换不再走逐字符翻槽:完整数字和压缩数字长度差太大,逐槽会显得拧巴。
// 这里采用 iOS 小组件感的整体 morph:数字始终在固定中心点,先轻微收缩淡出,再替换文本并回弹淡入。
const el = document.getElementById('csn-total-views');
if (!el) {
return;
}
const safeRaw = setTotalViewsRawCount(raw);
const targetMode = toMode === 'full' ? 'full' : 'compact';
const previousMode = fromMode === 'full' ? 'full' : 'compact';
const fromText = getViewsDisplayTextForMode(safeRaw, previousMode);
const toText = getViewsDisplayTextForMode(safeRaw, targetMode);
const token = String(Date.now()) + ':' + String(Math.random());
cancelViewsDisplayAnimationForModeSwitch(el);
el.setAttribute('data-views-morph-token', token);
el.setAttribute('data-views-animation-active', '1');
el.setAttribute('data-target-raw-value', String(safeRaw));
el.setAttribute('data-raw-value', String(safeRaw));
el.setAttribute('data-current-raw-value', String(safeRaw));
el.setAttribute('data-full-raw-value', String(safeRaw));
el.setAttribute('data-display-value', toText);
el.setAttribute('data-step-display', toText);
el.setAttribute('data-views-unit', targetMode === 'full' ? 'full' : (getViewsCompactNumberParts(safeRaw).suffix || 'plain'));
el.removeAttribute('data-current-compact-value');
el.removeAttribute('data-current-compact-suffix');
el.removeAttribute('data-pending-raw-value');
el.classList.remove('csn-views-number-changing');
if (el.getAttribute('data-base-font-size')) {
el.style.fontSize = el.getAttribute('data-base-font-size') + 'px';
}
el.innerHTML = '' +
'<span class="csn-views-morph-stage csn-views-morph-out">' +
'<span class="csn-views-morph-text">' + escapeHtml(fromText) + '</span>' +
'</span>';
fitPlainViewsNumber(el);
requestViewsNumberFit(el);
window.setTimeout(function () {
if (el.getAttribute('data-views-morph-token') !== token) {
return;
}
el.innerHTML = '' +
'<span class="csn-views-morph-stage csn-views-morph-in">' +
'<span class="csn-views-morph-text">' + escapeHtml(toText) + '</span>' +
'</span>';
fitPlainViewsNumber(el);
requestViewsNumberFit(el);
}, 180);
window.setTimeout(function () {
if (el.getAttribute('data-views-morph-token') !== token) {
return;
}
renderPlainStepStaticText(el, toText);
el.setAttribute('data-raw-value', String(safeRaw));
el.setAttribute('data-current-raw-value', String(safeRaw));
el.setAttribute('data-full-raw-value', String(safeRaw));
el.setAttribute('data-step-display', toText);
el.setAttribute('data-display-value', toText);
el.setAttribute('data-views-unit', targetMode === 'full' ? 'full' : (getViewsCompactNumberParts(safeRaw).suffix || 'plain'));
el.setAttribute('data-views-animation-active', '0');
el.removeAttribute('data-views-morph-token');
el.classList.remove('csn-views-number-changing');
fitPlainViewsNumber(el);
}, 540);
}
function updateViewsCardContent(options) {
const animate = !options || options.animate !== false;
const raw = getTotalViewsRawCount();
const el = document.getElementById('csn-total-views');
if (options && options.forceModeSwitch) {
cancelViewsDisplayAnimationForModeSwitch(el);
}
if (animate && options && options.forceModeSwitch) {
animateViewsModeCrossfade(raw, options.fromMode, viewsDisplayMode);
} else if (animate) {
renderViewsNumberTextByMode(raw, options || {});
} else {
const compact = getViewsCompactNumberParts(raw);
const text = viewsDisplayMode === 'full' ? formatFullNumber(raw) : compact.text;
if (el) {
el.setAttribute('data-raw-value', String(raw));
el.setAttribute('data-current-raw-value', String(raw));
el.setAttribute('data-full-raw-value', String(raw));
el.setAttribute('data-display-value', text);
el.setAttribute('data-step-display', text);
el.setAttribute('data-views-unit', viewsDisplayMode === 'full' ? 'full' : (compact.suffix || 'plain'));
renderPlainStepStaticText(el, text);
fitPlainViewsNumber(el);
}
}
const card = document.querySelector('.csn-views-card');
if (card) {
card.setAttribute('data-views-display-mode', viewsDisplayMode);
card.setAttribute('aria-label', '累计浏览量,点击切换' + (viewsDisplayMode === 'full' ? '压缩显示' : '完整显示'));
card.removeAttribute('title');
}
}
function animateCompactMetricNumberText(id, value) {
const el = document.getElementById(id);
if (!el) {
return;
}
const targetRaw = Number(value || 0);
const previousRaw = Number(el.getAttribute('data-raw-value') || 0);
const targetText = getCompactNumberParts(targetRaw).text;
const previousText = el.getAttribute('data-display-value') || normalizeRenderedNumberText(el) || getCompactNumberParts(previousRaw).text;
el.setAttribute('data-raw-value', String(targetRaw));
el.setAttribute('data-display-value', targetText);
if (previousText === targetText && Number(previousRaw || 0) === Number(targetRaw || 0)) {
renderRollingStaticNumber(el, targetText);
fitPlainMetricNumber(el);
return;
}
const token = String(Date.now()) + ':' + String(Math.random());
el.setAttribute('data-metric-animation-token', token);
el.classList.add('csn-number-changing');
// 总编辑数保持字符槽结构:动画结束后也不回退成普通文本,避免字距突然变掉。
renderRollingNumber(el, previousText, targetText, {
changeStartIndex: getTailFlipStartIndex(previousText, targetText)
});
window.requestAnimationFrame(function () {
fitPlainMetricNumber(el);
});
window.setTimeout(function () {
if (el.getAttribute('data-metric-animation-token') !== token) {
return;
}
renderRollingStaticNumber(el, targetText);
el.classList.remove('csn-number-changing');
fitPlainMetricNumber(el);
}, METRIC_ROLL_FINAL_SETTLE_MS);
}
function normalizeRenderedNumberText(el) {
if (!el) {
return '';
}
const stepDisplay = el.getAttribute('data-step-display');
if (stepDisplay) {
return stepDisplay;
}
const text = String(el.textContent || '').replace(/\s+/g, '').trim();
return text || '';
}
function fitPlainMetricNumber(el) {
if (!el) {
return;
}
if (!el.getAttribute('data-base-font-size')) {
const computed = window.getComputedStyle(el);
el.setAttribute('data-base-font-size', String(parseFloat(computed.fontSize) || 65));
}
const base = Number(el.getAttribute('data-base-font-size') || 65);
el.style.fontSize = base + 'px';
const available = getNumberAvailableWidth(el);
const actual = Math.max(1, el.scrollWidth || el.getBoundingClientRect().width || 1);
if (actual <= available) {
return;
}
const fitted = Math.max(28, Math.floor(base * available / actual));
el.style.fontSize = fitted + 'px';
}
function animateViewsNumberText(value, options) {
const el = document.getElementById('csn-total-views');
if (!el) {
return;
}
const targetRaw = setTotalViewsRawCount(value);
el.setAttribute('data-full-raw-value', String(targetRaw));
if (viewsDisplayMode === 'full') {
animateViewsFullNumberText(targetRaw);
return;
}
const activeTarget = el.getAttribute('data-target-raw-value');
if (el.getAttribute('data-views-animation-active') === '1') {
if (activeTarget === String(targetRaw)) {
return;
}
// 动画播放中只记录最新目标,不中途打断当前字符槽。
// 否则每次 pageview 返回都会重建 DOM,最容易出现裁切和跳帧。
el.setAttribute('data-pending-raw-value', String(targetRaw));
return;
}
const token = String(Date.now()) + ':' + String(Math.random());
el.setAttribute('data-views-animation-token', token);
el.setAttribute('data-target-raw-value', String(targetRaw));
el.setAttribute('data-views-animation-active', '1');
const previousRaw = getCurrentViewsRawValue(el);
const targetCompact = getViewsCompactNumberParts(targetRaw);
const fromFullMode = !!(options && options.fromFullMode);
const previousCompact = fromFullMode && targetCompact.suffix ? {
value: targetCompact.value,
suffix: targetCompact.suffix,
text: targetCompact.text
} : getCurrentViewsCompactParts(el, previousRaw, targetCompact.suffix);
el.setAttribute('data-display-value', targetCompact.text);
el.setAttribute('data-views-unit', targetCompact.suffix || 'plain');
// 缩写状态下,按缩写单位递增显示:
// 例如目标是 1.4M,就固定用 M 作为单位,从 0.1M / 当前 M 数值递增到 1.4M。
if (targetCompact.suffix) {
animateViewsCompactUnit(el, previousCompact, targetCompact, targetRaw, token, {
fromFullMode: fromFullMode
});
return;
}
animateViewsPlainInteger(el, previousRaw, targetRaw, token);
}
function getCurrentViewsRawValue(el) {
const currentRaw = el.getAttribute('data-current-raw-value');
if (currentRaw != null && currentRaw !== '') {
return Number(currentRaw || 0);
}
const raw = el.getAttribute('data-raw-value');
if (raw != null && raw !== '') {
return Number(raw || 0);
}
return 0;
}
function getCurrentViewsCompactParts(el, rawValue, targetSuffix) {
const valueAttr = el.getAttribute('data-current-compact-value');
const suffixAttr = el.getAttribute('data-current-compact-suffix') || '';
if (valueAttr != null && valueAttr !== '' && suffixAttr) {
return {
value: Number(valueAttr || 0),
suffix: suffixAttr,
text: formatViewsCompactParts(Number(valueAttr || 0), suffixAttr)
};
}
// 不预先把普通数字折算成目标单位;真正进入 K/M/B 时,第一帧要整串翻动。
return getViewsCompactNumberParts(rawValue);
}
function rawToCompactUnitValue(rawValue, suffix) {
const n = Math.abs(Number(rawValue || 0));
if (suffix === 'B') {
return n / 1000000000;
}
if (suffix === 'M') {
return n / 1000000;
}
if (suffix === 'K') {
return n / 1000;
}
return Number(rawValue || 0);
}
function compactUnitValueToRaw(value, suffix) {
const n = Number(value || 0);
if (suffix === 'B') {
return n * 1000000000;
}
if (suffix === 'M') {
return n * 1000000;
}
if (suffix === 'K') {
return n * 1000;
}
return n;
}
function isViewsAnimationTokenAlive(el, token) {
return el && el.getAttribute('data-views-animation-token') === token;
}
function finishViewsAnimation(el, targetRaw, targetText, token, options) {
if (!isViewsAnimationTokenAlive(el, token)) {
return;
}
const unit = options && options.unit ? options.unit : (getViewsCompactNumberParts(targetRaw).suffix || 'plain');
setTotalViewsRawCount(targetRaw);
renderPlainStepStaticText(el, targetText);
el.setAttribute('data-raw-value', String(targetRaw));
el.setAttribute('data-current-raw-value', String(targetRaw));
el.setAttribute('data-full-raw-value', String(targetRaw));
el.setAttribute('data-step-display', targetText);
el.setAttribute('data-display-value', targetText);
el.setAttribute('data-views-unit', unit);
el.removeAttribute('data-current-compact-value');
el.removeAttribute('data-current-compact-suffix');
el.setAttribute('data-views-animation-active', '0');
el.classList.remove('csn-views-number-changing');
fitPlainViewsNumber(el);
const pendingRaw = el.getAttribute('data-pending-raw-value');
if (pendingRaw != null && pendingRaw !== '' && Number(pendingRaw) !== Number(targetRaw || 0)) {
el.removeAttribute('data-pending-raw-value');
setTotalViewsRawCount(Number(pendingRaw || 0));
window.setTimeout(function () {
renderViewsNumberTextByMode(getTotalViewsRawCount());
}, 45);
} else {
el.removeAttribute('data-pending-raw-value');
}
}
function animateViewsCompactUnit(el, previousCompact, targetCompact, targetRaw, token, options) {
setTotalViewsRawCount(targetRaw);
const fromFullMode = !!(options && options.fromFullMode);
const suffix = targetCompact.suffix;
const target = roundViewsCompactStep(targetCompact.value, suffix);
const enteringCompactUnit = !previousCompact || previousCompact.suffix !== suffix;
let from = enteringCompactUnit ? 0 : roundViewsCompactStep(previousCompact.value, suffix);
if (!from && target > 0) {
from = getViewsCompactStartValue(target, suffix);
}
const direction = target >= from ? 1 : -1;
const steps = buildViewsCompactStepValues(from, target, direction, suffix);
let index = 0;
el.classList.remove('csn-views-number-changing');
if (fromFullMode && el.getAttribute('data-base-font-size')) {
el.style.fontSize = el.getAttribute('data-base-font-size') + 'px';
}
void el.offsetWidth;
el.classList.add('csn-views-number-changing');
fitPlainViewsNumber(el);
function nextStep() {
if (!isViewsAnimationTokenAlive(el, token)) {
return;
}
const current = steps[index];
const text = formatViewsCompactParts(current, suffix);
const previousText = fromFullMode && index === 0 ?
text :
(el.getAttribute('data-step-display') || previousCompact.text || normalizeRenderedNumberText(el) || '');
const isUnitEntranceFrame = enteringCompactUnit && index === 0;
const isFullToCompactFrame = fromFullMode && index === 0;
// 进入 K/M/B 压缩显示时整串翻槽;从完整数字返回压缩数字时,只使用压缩槽位,不继承完整数字的长槽位宽度。
renderPlainStepText(el, previousText, text, {
forceAll: isUnitEntranceFrame || isFullToCompactFrame,
changeStartIndex: (isUnitEntranceFrame || isFullToCompactFrame) ? 0 : getTailFlipStartIndex(previousText, text),
unitEnter: isUnitEntranceFrame || isFullToCompactFrame,
stepDurationMs: isUnitEntranceFrame || isFullToCompactFrame ? VIEWS_COMPACT_UNIT_ENTER_ANIMATION_MS : VIEWS_COMPACT_STEP_ANIMATION_MS
});
el.setAttribute('data-step-display', text);
el.setAttribute('data-display-value', text);
el.setAttribute('data-current-compact-value', String(current));
el.setAttribute('data-current-compact-suffix', suffix);
el.setAttribute('data-current-raw-value', String(compactUnitValueToRaw(current, suffix)));
index++;
if (index < steps.length) {
window.setTimeout(nextStep, isUnitEntranceFrame ? VIEWS_COMPACT_UNIT_ENTER_DELAY_MS : VIEWS_COMPACT_STEP_DELAY_MS);
} else {
window.setTimeout(function () {
finishViewsAnimation(el, targetRaw, targetCompact.text, token);
}, VIEWS_COMPACT_FINAL_SETTLE_MS);
}
}
nextStep();
}
function roundViewsCompactStep(value, suffix) {
const n = Number(value || 0);
if (suffix === 'K') {
return Math.round(n / 100) * 100;
}
return Math.round(n);
}
function getViewsCompactStepSize(suffix) {
return suffix === 'K' ? 100 : 1;
}
function getViewsCompactStartValue(target, suffix) {
if (target <= 0) {
return 0;
}
return Math.min(getViewsCompactStepSize(suffix), target);
}
function buildViewsCompactStepValues(from, target, direction, suffix) {
const result = [];
const safeDirection = direction >= 0 ? 1 : -1;
const baseStep = getViewsCompactStepSize(suffix);
let current = roundViewsCompactStep(from, suffix);
const roundedTarget = roundViewsCompactStep(target, suffix);
result.push(current);
while ((safeDirection > 0 && current < roundedTarget) || (safeDirection < 0 && current > roundedTarget)) {
let step = baseStep;
if (result.length > 48) {
const remaining = Math.abs(roundedTarget - current);
step = Math.max(baseStep, Math.round(remaining / 18 / baseStep) * baseStep);
}
current = roundViewsCompactStep(current + step * safeDirection, suffix);
if ((safeDirection > 0 && current > roundedTarget) || (safeDirection < 0 && current < roundedTarget)) {
current = roundedTarget;
}
if (result[result.length - 1] !== current) {
result.push(current);
}
if (result.length > 72) {
if (result[result.length - 1] !== roundedTarget) {
result.push(roundedTarget);
}
break;
}
}
return result;
}
function renderPlainStepText(el, previousText, targetText, options) {
const previous = String(previousText || '');
const target = String(targetText || '');
const max = Math.max(previous.length, target.length);
const from = previous.padStart(max, ' ');
const to = target.padStart(max, ' ');
const parts = [];
const forceAll = !!(options && options.forceAll);
const changeStartIndex = options && typeof options.changeStartIndex === 'number' ? options.changeStartIndex : -1;
const unitEnter = !!(options && options.unitEnter);
for (let i = 0; i < max; i++) {
const oldChar = from.charAt(i);
const newChar = to.charAt(i);
const changed = forceAll ? newChar !== ' ' :
changeStartIndex >= 0 ? i >= changeStartIndex && (oldChar !== ' ' || newChar !== ' ') : oldChar !== newChar;
const visibleOld = oldChar === ' ' ? '' : oldChar;
const visibleNew = newChar === ' ' ? '' : newChar;
const slotClass = getStepCharClass(visibleNew || visibleOld);
if (!visibleNew && !visibleOld) {
continue;
}
if (!changed) {
parts.push(
'<span class="csn-step-char ' + slotClass + '">' +
'<span class="csn-step-char-track" style="transform: translate(-50%, 0);">' +
'<span>' + escapeHtml(visibleNew) + '</span>' +
'</span>' +
'</span>'
);
continue;
}
const slotDelay = Math.min(unitEnter ? 90 : 70, i * (unitEnter ? 14 : 10));
const stepDuration = Number(options && options.stepDurationMs ? options.stepDurationMs : 840);
parts.push(
'<span class="csn-step-char csn-step-char-changing ' + slotClass + '" style="--csn-slot-delay:' + slotDelay + 'ms;--csn-step-duration:' + stepDuration + 'ms;">' +
'<span class="csn-step-char-flip csn-step-char-from">' + escapeHtml(visibleOld) + '</span>' +
'<span class="csn-step-char-flip csn-step-char-to">' + escapeHtml(visibleNew) + '</span>' +
'</span>'
);
}
el.innerHTML = '<span class="csn-step-number' + (unitEnter ? ' csn-step-number-unit-enter' : '') + '">' + parts.join('') + '</span>';
requestViewsNumberFit(el);
}
function requestViewsNumberFit(el) {
if (!el || el.id !== 'csn-total-views') {
return;
}
window.requestAnimationFrame(function () {
fitPlainViewsNumber(el);
});
}
function renderPlainStepStaticText(el, targetText) {
renderPlainStepText(el, targetText, targetText, { forceAll: false, unitEnter: false });
}
function getStepCharClass(ch) {
if (ch === '.') {
return 'csn-step-char-dot';
}
if (ch === ',') {
return 'csn-step-char-comma';
}
if (/[KMB]/.test(ch)) {
return 'csn-step-char-suffix';
}
return '';
}
function animateViewsPlainInteger(el, previousRaw, targetRaw, token) {
setTotalViewsRawCount(targetRaw);
const previousText = el.getAttribute('data-step-display') || normalizeRenderedNumberText(el) || '0';
const targetText = formatNumber(targetRaw);
if (previousText === targetText) {
finishViewsAnimation(el, targetRaw, targetText, token);
return;
}
el.classList.remove('csn-views-number-changing');
void el.offsetWidth;
el.classList.add('csn-views-number-changing');
renderPlainStepText(el, previousText, targetText, {
changeStartIndex: getTailFlipStartIndex(previousText, targetText)
});
el.setAttribute('data-step-display', targetText);
el.setAttribute('data-current-raw-value', String(targetRaw));
fitPlainViewsNumber(el);
window.setTimeout(function () {
finishViewsAnimation(el, targetRaw, targetText, token);
}, VIEWS_PLAIN_FINAL_SETTLE_MS);
}
function getViewsCompactNumberParts(value) {
const n = Number(value || 0);
const abs = Math.abs(n);
const sign = n < 0 ? '-' : '';
// 累计浏览量不再使用小数点:100K、200K、1400K 这样走,避免“.”槽位打乱节奏。
if (abs >= 1000000000) {
const valueB = Math.max(1, Math.round(abs / 1000000000));
return {
value: valueB,
suffix: 'B',
text: sign + valueB.toLocaleString('en-US') + 'B'
};
}
if (abs >= 10000000) {
const valueM = Math.max(1, Math.round(abs / 1000000));
return {
value: valueM,
suffix: 'M',
text: sign + valueM.toLocaleString('en-US') + 'M'
};
}
if (abs >= 100000) {
const valueK = Math.max(100, Math.round(abs / 1000 / 100) * 100);
return {
value: valueK,
suffix: 'K',
text: sign + valueK.toLocaleString('en-US') + 'K'
};
}
return {
value: n,
suffix: '',
text: Math.round(n).toLocaleString('en-US')
};
}
function formatViewsCompactParts(value, suffix) {
const n = Math.round(Number(value || 0));
return n.toLocaleString('en-US') + suffix;
}
function getCompactNumberParts(value) {
const n = Number(value || 0);
const abs = Math.abs(n);
const sign = n < 0 ? '-' : '';
if (abs >= 1000000000) {
return {
value: abs / 1000000000,
suffix: 'B',
text: sign + trimCompactDecimal(abs / 1000000000) + 'B'
};
}
if (abs >= 1000000) {
return {
value: abs / 1000000,
suffix: 'M',
text: sign + trimCompactDecimal(abs / 1000000) + 'M'
};
}
if (abs >= 100000) {
return {
value: abs / 1000,
suffix: 'K',
text: sign + trimCompactDecimal(abs / 1000) + 'K'
};
}
return {
value: n,
suffix: '',
text: Math.round(n).toLocaleString('en-US')
};
}
function formatCompactParts(value, suffix) {
return trimCompactDecimal(value) + suffix;
}
function fitPlainViewsNumber(el) {
if (!el) {
return;
}
if (!el.getAttribute('data-base-font-size')) {
const computed = window.getComputedStyle(el);
el.setAttribute('data-base-font-size', String(parseFloat(computed.fontSize) || 65));
}
const base = Number(el.getAttribute('data-base-font-size') || 65);
el.style.fontSize = base + 'px';
const available = getNumberAvailableWidth(el);
const inner = el.querySelector ? (el.querySelector('.csn-views-morph-text') || el.querySelector('.csn-step-number')) : null;
const innerWidth = inner && inner.getBoundingClientRect ? inner.getBoundingClientRect().width : 0;
const rectWidth = el.getBoundingClientRect ? el.getBoundingClientRect().width : 0;
const contentWidth = innerWidth || el.scrollWidth || 0;
const actual = Math.max(1, contentWidth || rectWidth || 0);
if (actual <= available) {
return;
}
const fitted = Math.max(28, Math.floor(base * available / actual));
el.style.fontSize = fitted + 'px';
}
function animateNumberText(id, value) {
const el = document.getElementById(id);
if (!el) {
return;
}
const target = formatNumber(value);
const previous = el.getAttribute('data-display-value') || el.textContent || '0';
el.setAttribute('data-raw-value', String(Number(value || 0)));
el.setAttribute('data-display-value', target);
el.classList.add('csn-number-changing');
renderRollingNumber(el, previous, target);
window.requestAnimationFrame(function () {
fitBigNumberToContainer(el);
});
window.setTimeout(function () {
el.classList.remove('csn-number-changing');
renderRollingStaticNumber(el, target);
fitBigNumberToContainer(el);
}, 980);
}
function renderRollingStaticNumber(el, text) {
const target = normalizeRollingText(text);
const parts = [];
for (let i = 0; i < target.length; i++) {
parts.push(createRollingSlot(target.charAt(i), target.charAt(i), i, false));
}
el.innerHTML = '<span class="csn-number-wheel">' + parts.join('') + '</span>';
el.setAttribute('data-display-value', target);
}
function renderRollingNumber(el, previousText, targetText, options) {
const previous = normalizeRollingText(previousText);
const target = normalizeRollingText(targetText);
const parts = [];
const previousOffset = previous.length - target.length;
const forceAll = !!(options && options.forceAll);
const changeStartIndex = options && typeof options.changeStartIndex === 'number' ? options.changeStartIndex : -1;
// 关键:只按目标值长度生成槽位。
// 旧值较长时,不再生成前面的空白占位槽,避免切换到 1M / 100K 时撑宽并被裁切。
for (let i = 0; i < target.length; i++) {
const fromIndex = i + previousOffset;
const fromChar = fromIndex >= 0 && fromIndex < previous.length ? previous.charAt(fromIndex) : '';
const toChar = target.charAt(i);
const changed = forceAll ? !!(fromChar || toChar) :
changeStartIndex >= 0 ? i >= changeStartIndex && !!(fromChar || toChar) : fromChar !== toChar;
parts.push(createRollingSlot(fromChar, toChar, i, changed));
}
const rollingToken = String(Date.now()) + ':' + String(Math.random());
el.setAttribute('data-rolling-render-token', rollingToken);
el.innerHTML = '<span class="csn-number-wheel">' + parts.join('') + '</span>';
// 刚生成 DOM 后立刻适配一次,避免动画第一帧裁切。
fitBigNumberToContainer(el);
window.requestAnimationFrame(function () {
if (el.getAttribute('data-rolling-render-token') !== rollingToken) {
return;
}
fitBigNumberToContainer(el);
el.querySelectorAll('.csn-number-slot[data-changed="1"]').forEach(function (slot) {
slot.classList.add('csn-number-rolling');
});
window.setTimeout(function () {
if (el.getAttribute('data-rolling-render-token') !== rollingToken) {
return;
}
// 动画结束后仍保留字符槽,但去掉旧字符层,避免下缘/上缘残影。
renderRollingStaticNumber(el, target);
fitBigNumberToContainer(el);
fitPlainMetricNumber(el);
}, ROLLING_SLOT_SETTLE_MS);
});
}
function createRollingSlot(fromChar, toChar, index, changed) {
const safeFrom = fromChar === ' ' ? '' : fromChar;
const safeTo = toChar === ' ' ? '' : toChar;
const visibleChar = changed ? safeFrom : safeTo;
if (!safeTo && !safeFrom) {
return '';
}
const slotClass = getRollingSlotClass(safeTo || safeFrom);
const delay = Math.min(180, index * 22);
if (!changed) {
return '' +
'<span class="csn-number-slot ' + slotClass + '" data-changed="0">' +
'<span class="csn-number-strip" data-changed="0" style="transition:none; transform: translate(-50%, 0);">' +
'<span>' + escapeHtml(visibleChar) + '</span>' +
'</span>' +
'</span>';
}
return '' +
'<span class="csn-number-slot ' + slotClass + '" data-changed="1" style="--csn-slot-delay:' + delay + 'ms;">' +
'<span class="csn-number-flip csn-number-flip-from">' + escapeHtml(safeFrom) + '</span>' +
'<span class="csn-number-flip csn-number-flip-to">' + escapeHtml(safeTo) + '</span>' +
'</span>';
}
function getRollingSlotClass(ch) {
if (ch === ',') {
return 'csn-number-comma';
}
if (/[KMB]/.test(ch)) {
return 'csn-number-suffix';
}
return '';
}
function normalizeRollingText(value) {
return String(value == null ? '0' : value).trim() || '0';
}
function getTailFlipStartIndex(previousText, targetText) {
const previous = normalizeRollingText(previousText);
const target = normalizeRollingText(targetText);
if (!previous || !target || previous === target) {
return -1;
}
if (previous.length !== target.length) {
return 0;
}
for (let i = 0; i < target.length; i++) {
if (previous.charAt(i) !== target.charAt(i)) {
return i;
}
}
return -1;
}
function setText(id, value) {
const el = document.getElementById(id);
if (el) {
el.textContent = value;
}
}
function escapeHtml(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function escapeAttr(value) {
return escapeHtml(value);
}
})();