-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
405 lines (338 loc) · 13.6 KB
/
script.js
File metadata and controls
405 lines (338 loc) · 13.6 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
// Ссылки строятся на основе реальных <a> из статического HTML-fallback (#static-fallback).
// Это даёт SEO/GEO-видимость без JS и позволяет JS переиспользовать те же URL.
const bookLinks = {};
const socialLinks = {};
// Порядок книг в интерактивном меню (совпадает с порядком в HTML-fallback).
const booksMain = [];
const echoLine = document.getElementById("echo-line");
const errorMessage = document.getElementById("error-message");
const historyLog = document.getElementById("history-log");
const backNav = document.getElementById("back-nav");
const staticFallback = document.getElementById("static-fallback");
let state = 0;
let initialSequenceComplete = false;
let username = "integrant";
let activeTimers = [];
let isLoadingSequence = false;
let isNavigating = false;
const ERROR_TYPES = {
CRITICAL: '#ff0055',
WARNING: '#ffaa00',
INFO: '#44aaff'
};
function collectLinksFromFallback() {
if (!staticFallback) return;
const bookAnchors = staticFallback.querySelectorAll('a.book-item[data-book]');
bookAnchors.forEach((a) => {
const name = a.getAttribute('data-book');
const href = a.getAttribute('href');
if (name && href) {
bookLinks[name] = href;
if (!booksMain.includes(name)) booksMain.push(name);
}
});
const socialAnchors = staticFallback.querySelectorAll('a.social-item[data-social]');
socialAnchors.forEach((a) => {
const name = a.getAttribute('data-social');
const href = a.getAttribute('href');
if (name && href) {
socialLinks[name] = href;
}
});
}
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function safeSetTimeout(callback, delay) {
const timerId = setTimeout(() => {
const index = activeTimers.indexOf(timerId);
if (index > -1) {
activeTimers.splice(index, 1);
}
callback();
}, delay);
activeTimers.push(timerId);
return timerId;
}
function clearAllTimers() {
activeTimers.forEach(timerId => clearTimeout(timerId));
activeTimers = [];
}
function skipLoadingSequence(reason = 'click') {
if (isLoadingSequence) {
isLoadingSequence = false;
clearAllTimers();
echoLine.style.opacity = 1;
initialSequenceComplete = true;
listMenu();
if (reason === 'escape') {
addToHistory('> загрузка пропущена по клавише Escape');
} else {
addToHistory('> загрузка пропущена по клику');
}
}
}
function typeMessage(text, callback, speed = 80) {
clearAllTimers();
echoLine.style.opacity = 1;
echoLine.textContent = "";
let index = 0;
function typeChar() {
if (index < text.length) {
echoLine.textContent += text.charAt(index);
index++;
const randomSpeed = speed + Math.floor(Math.random() * 40 - 20);
safeSetTimeout(typeChar, randomSpeed);
} else if (callback) {
safeSetTimeout(callback, 500);
}
}
typeChar();
}
function addToHistory(message, type = 'info') {
if (!historyLog.style.opacity || historyLog.style.opacity === '0') {
historyLog.style.opacity = 1;
}
const timestamp = new Date().toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
const entryColor = type === 'error' ? '#ff5555' : (type === 'warning' ? '#ffaa00' : '#999');
const logEntry = document.createElement('div');
logEntry.style.color = entryColor;
logEntry.textContent = `[${timestamp}] ${message}`;
historyLog.appendChild(logEntry);
historyLog.scrollTop = historyLog.scrollHeight;
}
function openBookLink(bookName) {
if (isNavigating) return;
isNavigating = true;
safeSetTimeout(() => { isNavigating = false; }, 300);
const url = bookLinks[bookName];
if (url) {
window.open(url, url.startsWith('https://againte.gratis') ? '_self' : '_blank');
addToHistory(`> переход: ${bookName} → ${url}`);
} else {
errorMessage.textContent = 'Ссылка не найдена';
errorMessage.style.color = ERROR_TYPES.CRITICAL;
errorMessage.style.opacity = 1;
addToHistory(`> попытка: ${bookName} — ссылка отсутствует`, 'error');
safeSetTimeout(() => {
errorMessage.style.opacity = 0;
safeSetTimeout(() => errorMessage.textContent = "", 300);
}, 2000);
}
}
function openSocialLink(socialName) {
if (isNavigating) return;
isNavigating = true;
safeSetTimeout(() => { isNavigating = false; }, 300);
const url = socialLinks[socialName];
if (url) {
window.open(url, '_blank');
addToHistory(`> переход: ${socialName} → ${url}`);
return;
}
errorMessage.textContent = 'Ошибка перехода';
errorMessage.style.color = ERROR_TYPES.WARNING;
errorMessage.style.opacity = 1;
addToHistory(`> попытка перехода: ${socialName} — сервис недоступен`, 'warning');
safeSetTimeout(() => {
errorMessage.style.opacity = 0;
safeSetTimeout(() => {
errorMessage.textContent = "";
}, 300);
}, 2000);
}
function listSocials() {
backNav.style.opacity = 1;
// Рендерим через настоящие <a>, чтобы ссылка оставалась ссылкой (кликабельна, открывается в новой вкладке, копируется).
const container = document.createElement('div');
container.className = 'content-container';
const title = document.createElement('div');
title.style.marginBottom = '10px';
title.innerHTML = '<strong># Соцсети:</strong>';
container.appendChild(title);
Object.keys(socialLinks).forEach((name) => {
const a = document.createElement('a');
a.className = 'social-item';
a.href = socialLinks[name];
a.setAttribute('data-social', name);
a.setAttribute('role', 'link');
a.setAttribute('aria-label', `Перейти в ${name}`);
a.setAttribute('rel', 'noopener');
a.setAttribute('target', '_blank');
a.textContent = `- ${name}`;
container.appendChild(a);
});
echoLine.textContent = '';
echoLine.appendChild(container);
echoLine.style.opacity = 1;
state = 12;
addToHistory('> открыт раздел: Соцсети');
}
function listMenu() {
backNav.style.opacity = 0;
const container = document.createElement('div');
container.className = 'menu-container';
container.innerHTML =
"[ Выберите раздел ]<br><br>" +
"<div class='menu-item' data-action='books' role='button' tabindex='0' aria-label='Перейти к разделу книг'>↳ [ 1 ] Книги </div>" +
"<div class='menu-item' data-action='socials' role='button' tabindex='0' aria-label='Перейти к разделу соцсетей'>↳ [ 2 ] Соцсети</div>";
echoLine.textContent = '';
echoLine.appendChild(container);
echoLine.style.opacity = 1;
state = 10;
if (initialSequenceComplete) {
addToHistory('> отображено главное меню');
}
}
function handleBack() {
if (state === 11 || state === 12) {
addToHistory('> возврат к главному меню');
listMenu();
}
}
function listBooks() {
backNav.style.opacity = 1;
const container = document.createElement('div');
container.className = 'content-container';
const title = document.createElement('div');
title.style.marginBottom = '10px';
title.innerHTML = '<strong># Книги:</strong>';
container.appendChild(title);
booksMain.forEach((book) => {
const href = bookLinks[book] || '#';
const a = document.createElement('a');
a.className = 'book-item';
a.href = href;
a.setAttribute('data-book', book);
a.setAttribute('role', 'link');
a.setAttribute('aria-label', `Открыть книгу ${book}`);
a.textContent = ` - ${book}`;
container.appendChild(a);
});
echoLine.textContent = '';
echoLine.appendChild(container);
echoLine.style.opacity = 1;
state = 11;
addToHistory('> открыт раздел: Книги');
}
function startLoadingSequence() {
isLoadingSequence = true;
initialSequenceComplete = true;
typeMessage(">> signal accepted.", () => {
typeMessage(">> initializing interface...", () => {
safeSetTimeout(() => {
typeMessage(">> идентификация: посетитель", () => {
safeSetTimeout(() => {
typeMessage(`:: инициализация завершена — добро пожаловать, ${username}`, () => {
safeSetTimeout(() => {
isLoadingSequence = false;
listMenu();
addToHistory('> сессия началась');
}, 500);
});
}, 800);
});
}, 1200);
});
});
}
function initPage() {
// Сначала собираем ссылки из статического HTML (единственный источник правды).
collectLinksFromFallback();
// Плавный старт терминала — без блокирующих операций, ссылки в DOM уже есть и кликабельны.
safeSetTimeout(() => {
echoLine.style.opacity = 1;
echoLine.textContent = ":: awaiting signal...";
}, 1000);
// Обработчик для кнопки "Назад"
backNav.addEventListener('click', handleBack);
backNav.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleBack();
}
});
// Event delegation — единый обработчик для всех интерактивных элементов
echoLine.addEventListener('click', (e) => {
const menuItem = e.target.closest('.menu-item');
if (menuItem) {
const action = menuItem.getAttribute('data-action');
if (action === 'books') listBooks();
else if (action === 'socials') listSocials();
return;
}
const bookItem = e.target.closest('.book-item');
if (bookItem) {
// Это реальный <a> с href — пусть браузер обрабатывает переход сам,
// но мы записываем его в history-log.
const name = bookItem.getAttribute('data-book');
if (name) addToHistory(`> переход: ${name} → ${bookItem.getAttribute('href')}`);
return;
}
const socialItem = e.target.closest('.social-item');
if (socialItem) {
const name = socialItem.getAttribute('data-social');
if (name) addToHistory(`> переход: ${name} → ${socialItem.getAttribute('href')}`);
return;
}
});
echoLine.addEventListener('keydown', (e) => {
if (e.key !== 'Enter' && e.key !== ' ') return;
const menuItem = e.target.closest('.menu-item');
if (menuItem) {
e.preventDefault();
const action = menuItem.getAttribute('data-action');
if (action === 'books') listBooks();
else if (action === 'socials') listSocials();
return;
}
// Для <a.book-item> и <a.social-item> Enter по умолчанию вызывает переход —
// никаких preventDefault не нужно.
});
document.body.addEventListener("click", (e) => {
// Не перехватывать клики по интерактивным элементам внутри echoLine и по статическому fallback-меню
if (e.target.closest('#echo-line .menu-item, #echo-line .book-item, #echo-line .social-item, #back-nav, #static-fallback a')) return;
if (state === 0 && !initialSequenceComplete) {
startLoadingSequence();
} else if (isLoadingSequence) {
skipLoadingSequence('click');
}
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && (state === 11 || state === 12)) {
handleBack();
}
if (state === 10) {
if (event.key === '1') {
listBooks();
} else if (event.key === '2') {
listSocials();
}
}
if (event.key === 'Backspace' && (state === 11 || state === 12)) {
handleBack();
event.preventDefault();
}
if (isLoadingSequence && event.key === 'Escape') {
skipLoadingSequence('escape');
event.preventDefault();
}
});
window.addEventListener('beforeunload', () => {
clearAllTimers();
});
}
window.listBooks = listBooks;
window.listSocials = listSocials;
window.handleBack = handleBack;
window.openBookLink = openBookLink;
window.openSocialLink = openSocialLink;
document.addEventListener('DOMContentLoaded', initPage);
if (document.readyState === 'interactive' || document.readyState === 'complete') {
initPage();
}