-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
422 lines (345 loc) · 11.3 KB
/
script.js
File metadata and controls
422 lines (345 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
const THEME_STORAGE_KEY = 'sr-theme';
const THEME_META_COLORS = {
dark: '#090b13',
light: '#f7f9ff'
};
const root = document.documentElement;
const themeToggles = document.querySelectorAll('[data-theme-toggle]');
const themeColorMeta = document.querySelector('meta[name="theme-color"]');
const systemThemeQuery = window.matchMedia ? window.matchMedia('(prefers-color-scheme: light)') : null;
function getStoredTheme() {
try {
return localStorage.getItem(THEME_STORAGE_KEY);
} catch (error) {
return null;
}
}
function getPreferredTheme() {
const storedTheme = getStoredTheme();
if (storedTheme === 'light' || storedTheme === 'dark') {
return storedTheme;
}
return systemThemeQuery?.matches ? 'light' : 'dark';
}
function updateThemeToggleState(theme) {
const nextTheme = theme === 'light' ? 'dark' : 'light';
const iconClass = nextTheme === 'light' ? 'fa-sun' : 'fa-moon';
const text = nextTheme === 'light' ? '浅色' : '深色';
themeToggles.forEach(button => {
const iconNode = button.querySelector('.theme-toggle__icon');
const textNode = button.querySelector('.theme-toggle__text');
button.setAttribute('aria-label', `切换到${text}模式`);
button.setAttribute('title', `切换到${text}模式`);
button.setAttribute('aria-pressed', String(theme === 'light'));
if (iconNode) {
iconNode.classList.remove('fa-sun', 'fa-moon');
iconNode.classList.add(iconClass);
}
if (textNode) textNode.textContent = text;
});
}
function applyTheme(theme, options = {}) {
const { persist = false } = options;
root.setAttribute('data-theme', theme);
updateThemeToggleState(theme);
if (themeColorMeta) {
themeColorMeta.setAttribute('content', THEME_META_COLORS[theme] || THEME_META_COLORS.dark);
}
if (persist) {
try {
localStorage.setItem(THEME_STORAGE_KEY, theme);
} catch (error) {
// Ignore storage errors and continue.
}
}
}
applyTheme(root.getAttribute('data-theme') || getPreferredTheme());
themeToggles.forEach(button => {
button.addEventListener('click', () => {
const currentTheme = root.getAttribute('data-theme') || getPreferredTheme();
const nextTheme = currentTheme === 'light' ? 'dark' : 'light';
applyTheme(nextTheme, { persist: true });
});
});
if (systemThemeQuery) {
const handleSystemThemeChange = event => {
if (getStoredTheme()) return;
applyTheme(event.matches ? 'light' : 'dark');
};
if (typeof systemThemeQuery.addEventListener === 'function') {
systemThemeQuery.addEventListener('change', handleSystemThemeChange);
} else if (typeof systemThemeQuery.addListener === 'function') {
systemThemeQuery.addListener(handleSystemThemeChange);
}
}
const navToggle = document.querySelector('[data-nav-toggle]');
const nav = document.getElementById('primary-nav');
const header = document.querySelector('[data-header]');
const hero = document.getElementById('home');
const copyrightContent = document.getElementById('copyright');
const setNavOpenState = isOpen => {
if (!nav) return;
nav.classList.toggle('is-open', isOpen);
if (navToggle) {
navToggle.setAttribute('aria-expanded', String(isOpen));
}
};
const closeNav = () => {
setNavOpenState(false);
};
if (navToggle && nav) {
navToggle.addEventListener('click', () => {
const expanded = navToggle.getAttribute('aria-expanded') === 'true';
setNavOpenState(!expanded);
});
nav.querySelectorAll('a').forEach(link => {
link.addEventListener('click', closeNav);
});
document.addEventListener('click', event => {
const target = event.target;
if (!(target instanceof Node)) return;
if (window.innerWidth < 840 && !nav.contains(target) && !navToggle.contains(target)) {
closeNav();
}
});
window.addEventListener('resize', () => {
if (window.innerWidth >= 840) {
nav.classList.remove('is-open');
navToggle.setAttribute('aria-expanded', 'false');
}
});
}
const handleScroll = () => {
if (!header) return;
header.classList.toggle('is-scrolled', window.scrollY > 12);
};
document.addEventListener('scroll', handleScroll, { passive: true });
handleScroll();
if (hero && window.matchMedia('(prefers-reduced-motion: no-preference)').matches) {
hero.addEventListener('pointermove', event => {
const rect = hero.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
hero.style.setProperty('--hero-pointer-x', `${x}px`);
hero.style.setProperty('--hero-pointer-y', `${y}px`);
});
hero.addEventListener('pointerleave', () => {
hero.style.setProperty('--hero-pointer-x', '50%');
hero.style.setProperty('--hero-pointer-y', '35%');
});
}
const currentYear = new Date().getFullYear();
if (copyrightContent) {
copyrightContent.innerText = `© ${currentYear} SR思锐 团队 保留所有权利.`;
}
// Advertisement System
const adSection = document.getElementById('advertisement');
const adContent = document.getElementById('ad-content');
const adWrapper = adSection?.querySelector('.ad-wrapper');
const adCloseBtn = adSection?.querySelector('.ad-close');
const adConfig = {
enabled: true,
apiEndpoint: '/api/ads',
expiryDate: new Date('2026-02-27T23:59:59+08:00'),
fallbackAd: {
id: 'sponsor-gift-coludai',
type: 'iframe',
priority: 'high',
url: 'https://gift.coludai.cn',
title: '赞助商 - Gift Coludai',
content: '感谢赞助商的支持',
startDate: new Date('2026-01-01T00:00:00+08:00'),
endDate: new Date('2026-02-27T23:59:59+08:00')
}
};
function shouldShowAd(ad) {
const now = new Date();
if (!adConfig.enabled) return false;
if (now > adConfig.expiryDate) return false;
if (ad.startDate && now < ad.startDate) return false;
if (ad.endDate && now > ad.endDate) return false;
try {
const closedAds = JSON.parse(sessionStorage.getItem('closedAds') || '[]');
if (Array.isArray(closedAds) && closedAds.includes(ad.id)) return false;
} catch (error) {
// Ignore storage failures and continue.
}
return true;
}
function renderAd(ad) {
if (!adContent || !adWrapper) return;
if (adSection) {
adSection.dataset.currentAdId = ad.id;
}
adContent.innerHTML = '';
adContent.className = 'ad-content';
adWrapper.setAttribute('data-priority', ad.priority);
switch (ad.type) {
case 'iframe':
renderIframeAd(ad);
break;
case 'banner':
renderBannerAd(ad);
break;
case 'card':
renderCardAd(ad);
break;
default:
console.warn('Unknown ad type:', ad.type);
}
}
function renderIframeAd(ad) {
if (!adContent) return;
adContent.classList.add('ad-type-iframe');
const iframe = document.createElement('iframe');
iframe.src = ad.url;
iframe.title = ad.title || '赞助商内容';
iframe.setAttribute('loading', 'lazy');
iframe.setAttribute('sandbox', 'allow-scripts allow-forms allow-popups');
adContent.appendChild(iframe);
}
function renderBannerAd(ad) {
if (!adContent) return;
adContent.classList.add('ad-type-banner');
if (!ad.imageUrl) {
console.warn(`Banner ad (ID: ${ad.id}) missing imageUrl, skipping render`);
return;
}
const link = document.createElement('a');
link.href = ad.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
const img = document.createElement('img');
img.src = ad.imageUrl;
img.alt = ad.title || '赞助商广告';
img.loading = 'lazy';
link.appendChild(img);
adContent.appendChild(link);
}
function renderCardAd(ad) {
if (!adContent) return;
adContent.classList.add('ad-type-card');
const cardDiv = document.createElement('div');
cardDiv.className = 'ad-card';
if (ad.imageUrl) {
const img = document.createElement('img');
img.src = ad.imageUrl;
img.alt = ad.title || '赞助商';
img.loading = 'lazy';
cardDiv.appendChild(img);
}
const contentDiv = document.createElement('div');
contentDiv.className = 'ad-card-content';
const title = document.createElement('h3');
title.textContent = ad.title || '赞助商';
contentDiv.appendChild(title);
const description = document.createElement('p');
description.textContent = ad.content || ad.description || '';
contentDiv.appendChild(description);
const link = document.createElement('a');
link.href = ad.url;
link.className = 'btn btn-primary';
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.textContent = '了解更多';
const icon = document.createElement('i');
icon.className = 'fas fa-arrow-right';
icon.setAttribute('aria-hidden', 'true');
link.appendChild(icon);
contentDiv.appendChild(link);
cardDiv.appendChild(contentDiv);
adContent.appendChild(cardDiv);
}
async function fetchAdsFromBackend() {
if (!adConfig.apiEndpoint) {
return [adConfig.fallbackAd];
}
try {
const response = await fetch(adConfig.apiEndpoint, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
signal: AbortSignal.timeout(5000)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (!data.success || !Array.isArray(data.data)) {
throw new Error('Invalid API response format');
}
if (data.data.length === 0) {
return [adConfig.fallbackAd];
}
return data.data.map(ad => ({
...ad,
startDate: ad.startDate ? new Date(ad.startDate) : null,
endDate: ad.endDate ? new Date(ad.endDate) : null
}));
} catch (error) {
console.error('Failed to fetch ads from API:', error);
return [adConfig.fallbackAd];
}
}
function sortAdsByPriority(ads) {
const priorityOrder = { high: 3, medium: 2, low: 1 };
return ads.slice().sort((a, b) => {
const aPriority = priorityOrder[a.priority] || 0;
const bPriority = priorityOrder[b.priority] || 0;
return bPriority - aPriority;
});
}
async function initAdSystem() {
if (!adSection) return;
try {
const ads = await fetchAdsFromBackend();
const visibleAds = ads.filter(ad => shouldShowAd(ad));
const sortedAds = sortAdsByPriority(visibleAds);
if (sortedAds.length > 0) {
renderAd(sortedAds[0]);
adSection.classList.add('is-visible');
}
} catch (error) {
console.error('Failed to initialize ad system:', error);
}
if (adCloseBtn) {
adCloseBtn.addEventListener('click', () => {
const adId = adSection?.dataset.currentAdId;
const hideAdSection = () => {
adSection?.classList.remove('is-visible');
};
try {
if (typeof window === 'undefined' || !window.sessionStorage) {
hideAdSection();
return;
}
const storedValue = sessionStorage.getItem('closedAds');
let closedAds = [];
if (storedValue) {
try {
const parsed = JSON.parse(storedValue);
if (Array.isArray(parsed)) {
closedAds = parsed;
}
} catch (error) {
closedAds = [];
}
}
if (adId && !closedAds.includes(adId)) {
closedAds.push(adId);
sessionStorage.setItem('closedAds', JSON.stringify(closedAds));
}
} catch (error) {
// Ignore storage errors and just hide the ad.
} finally {
hideAdSection();
}
});
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initAdSystem);
} else {
initAdSystem();
}