-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
379 lines (343 loc) · 19.6 KB
/
Copy pathindex.html
File metadata and controls
379 lines (343 loc) · 19.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
<!doctype html>
<html lang="ru" data-theme="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1.0, user-scalable=no" />
<meta name="theme-color" content="#0E2034" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<title>Релокация · Companion</title>
<meta name="description" content="Когнитивный экзоскелет для семейной релокации. Mobile-first PWA." />
<link rel="manifest" href="/manifest.json" />
<!-- PWA icons (Phase 6 #30) -->
<link rel="icon" type="image/svg+xml" href="/icons/favicon.svg" />
<link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/icons/apple-touch-icon.png" />
<meta name="apple-mobile-web-app-title" content="Релокация" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Lora:ital,wght@0,400;0,500;0,600;1,400;1,500&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<!-- Design System foundation (Sprint 9 Phase 1): семантические токены + a11y baseline. Подключается ДО styles.css чтобы var(--text-*)/var(--space-*)/etc были доступны во всём CSS. -->
<link rel="stylesheet" href="app/tokens.css">
<link rel="stylesheet" href="app/styles.css">
</head>
<body>
<!-- ═══════════════════════════════════════════════════════════════
RC_LOG · глобальная система диагностики и логирования.
Должна выполняться ПЕРЕД любыми другими скриптами чтобы
ловить все ошибки с самого начала. Хранится в localStorage,
экспортируется через UI или window.RC_LOG.export().
═══════════════════════════════════════════════════════════════ -->
<script>
(function() {
var STORAGE_KEY = 'rc2027:logs';
var MAX_ENTRIES = 200;
var SESSION_ID = Math.random().toString(36).slice(2, 10);
function loadStored() {
try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || []; }
catch(e) { return []; }
}
var entries = loadStored();
function persist() {
try {
if (entries.length > MAX_ENTRIES) entries = entries.slice(-MAX_ENTRIES);
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
} catch(e) { /* QuotaExceeded — игнор */ }
}
function add(level, channel, msg, data) {
var entry = {
t: Date.now(),
iso: new Date().toISOString(),
level: level, // 'info' | 'warn' | 'error' | 'sw' | 'boot' | 'user'
ch: channel, // источник: 'window' | 'sw' | 'react' | 'babel' | 'script' | 'user-action'
msg: String(msg).slice(0, 500),
data: data ? (typeof data === 'string' ? data.slice(0, 500) : data) : undefined,
v: window.APP_VERSION || null,
sid: SESSION_ID,
url: location.pathname + location.search
};
entries.push(entry);
persist();
if (level === 'error') {
// Дублируем в console чтобы было видно при подключении devtools
try { console.warn('[RC_LOG]', channel, msg, data); } catch(e) {}
}
}
window.RC_LOG = {
SESSION_ID: SESSION_ID,
add: add,
info: function(ch, msg, data) { add('info', ch, msg, data); },
warn: function(ch, msg, data) { add('warn', ch, msg, data); },
error: function(ch, msg, data) { add('error', ch, msg, data); },
sw: function(msg, data) { add('sw', 'sw', msg, data); },
user: function(msg, data) { add('user', 'user-action', msg, data); },
boot: function(msg, data) { add('boot', 'boot', msg, data); },
all: function() { return entries.slice(); },
clear: function() { entries = []; localStorage.removeItem(STORAGE_KEY); },
export: function() {
var lines = entries.map(function(e) {
var data = e.data ? ' ' + (typeof e.data === 'object' ? JSON.stringify(e.data) : e.data) : '';
return e.iso + ' [' + e.level.toUpperCase() + '] (' + e.ch + ') ' + e.msg + data + ' {v:' + (e.v||'?') + ' sid:' + e.sid + ' url:' + e.url + '}';
});
return lines.join('\n');
}
};
add('boot', 'boot', 'session start', { ua: navigator.userAgent.slice(0, 200), ts: Date.now() });
// ловим всё что может пойти не так
window.addEventListener('error', function(e) {
if (e.target && e.target.tagName) {
// ресурсная ошибка (script, img, link)
var tag = e.target.tagName.toLowerCase();
var src = e.target.src || e.target.href || '?';
add('error', 'resource', 'failed to load ' + tag, src);
} else {
add('error', 'window', e.message || 'unknown error', {
file: e.filename ? e.filename.split('/').pop() : '?',
line: e.lineno || 0,
col: e.colno || 0
});
}
}, true); // capture phase = ловим resource errors
window.addEventListener('unhandledrejection', function(e) {
var reason = e.reason;
add('error', 'promise', 'unhandled rejection',
reason && reason.message ? reason.message : String(reason).slice(0, 200));
});
// Sprint 11 Phase 4 — Web Vitals в RC_LOG. Без внешних зависимостей,
// через PerformanceObserver. Метрики: FCP, LCP, CLS, INP (если доступно).
// Видно в Profile → Диагностика, отправка наружу — Sprint 13 (consent-only).
function recordVital(name, value, extra) {
add('info', 'perf', name + ': ' + Math.round(value) + 'ms', extra);
}
if (typeof PerformanceObserver === 'function') {
try {
// FCP — первый paint видимого контента
new PerformanceObserver(function(list) {
for (var e of list.getEntries()) {
if (e.name === 'first-contentful-paint') recordVital('FCP', e.startTime);
}
}).observe({ type: 'paint', buffered: true });
// LCP — Largest Contentful Paint. Записываем последнее значение при
// visibilitychange (когда юзер уходит со страницы или после load).
var lcpValue = 0;
new PerformanceObserver(function(list) {
var entries = list.getEntries();
lcpValue = entries[entries.length - 1].startTime;
}).observe({ type: 'largest-contentful-paint', buffered: true });
addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden' && lcpValue) {
recordVital('LCP', lcpValue);
lcpValue = 0; // не дублировать
}
}, { once: false });
// CLS — Cumulative Layout Shift. Сумма всех layout shifts.
var clsValue = 0;
new PerformanceObserver(function(list) {
for (var e of list.getEntries()) {
if (!e.hadRecentInput) clsValue += e.value;
}
}).observe({ type: 'layout-shift', buffered: true });
addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden' && clsValue > 0) {
add('info', 'perf', 'CLS: ' + clsValue.toFixed(3));
clsValue = 0;
}
}, { once: false });
// INP — Interaction to Next Paint (proxy через event timing)
new PerformanceObserver(function(list) {
for (var e of list.getEntries()) {
if (e.duration > 16) { // только заметные задержки
recordVital('INP', e.duration, { event: e.name });
}
}
}).observe({ type: 'event', buffered: true, durationThreshold: 40 });
} catch (e) {
add('warn', 'perf', 'web-vitals observer unavailable', e.message);
}
}
// SW-события (если поддерживается)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', function(e) {
add('sw', 'sw', 'message from SW', e.data);
});
}
// beforeinstallprompt ловим РАНО — он срабатывает до монтирования React,
// и если слушатель повешен позже (в хуке), событие теряется. Сохраняем
// в глобал, хук useInstallPrompt читает отсюда + подписывается на listeners.
window.__deferredInstallPrompt = null;
window.__installPromptListeners = new Set();
window.addEventListener('beforeinstallprompt', function(e) {
e.preventDefault();
window.__deferredInstallPrompt = e;
add('info', 'pwa', 'beforeinstallprompt captured');
window.__installPromptListeners.forEach(function(fn) { try { fn(); } catch(_) {} });
});
window.addEventListener('appinstalled', function() {
window.__deferredInstallPrompt = null;
add('info', 'pwa', 'appinstalled');
window.__installPromptListeners.forEach(function(fn) { try { fn(); } catch(_) {} });
});
// Видимость страницы — для контекста
document.addEventListener('visibilitychange', function() {
add('info', 'window', 'visibility ' + document.visibilityState);
});
})();
</script>
<div id="root"></div>
<noscript>
<div style="padding:24px;font-family:system-ui;color:#E8EEF5;background:#0E2034;min-height:100vh;">
<h1>Релокация · Companion</h1>
<p>Для работы нужен JavaScript. Включите его в настройках браузера.</p>
</div>
</noscript>
<!-- Logs viewer: /?logs=1 — показать весь RC_LOG с кнопкой копирования
в любой момент (не только при поломке). Для отладки на устройствах. -->
<script>
(function() {
if (new URLSearchParams(location.search).get('logs') !== '1') return;
if (!window.RC_LOG) return;
function esc(s){ return String(s).replace(/[&<>]/g,function(c){return {'&':'&','<':'<','>':'>'}[c];}); }
var all = window.RC_LOG.all();
var errs = all.filter(function(e){ return e.level === 'error'; });
var h = '<div style="padding:16px;font-family:system-ui;color:#E8EEF5;background:#0E2034;min-height:100vh;line-height:1.5;">';
h += '<h2 style="margin:0 0 4px">Логи приложения</h2>';
h += '<p style="font-size:12px;color:#A9B8CA;margin:0 0 12px">' + all.length + ' событий, ' + errs.length + ' ошибок · session ' + window.RC_LOG.SESSION_ID + '</p>';
h += '<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px">';
h += '<button id="lv-copy" style="padding:10px 16px;background:#FF6B47;color:#0E2034;border:none;border-radius:8px;font-weight:600;font-size:13px">Скопировать всё</button>';
h += '<a href="/" style="padding:10px 16px;background:#1F3556;color:#E8EEF5;text-decoration:none;border-radius:8px;font-weight:600;font-size:13px">← В приложение</a>';
h += '</div>';
h += '<pre style="font-size:10px;font-family:monospace;background:#0B1A2C;padding:12px;border-radius:8px;color:#A9B8CA;white-space:pre-wrap;word-break:break-word;max-height:70vh;overflow:auto;margin:0">' + esc(window.RC_LOG.export()) + '</pre>';
h += '</div>';
document.body.innerHTML = h;
var btn = document.getElementById('lv-copy');
btn.onclick = function() {
var text = window.RC_LOG.export();
var done = function(){ btn.textContent = '✓ Скопировано'; setTimeout(function(){ btn.textContent = 'Скопировать всё'; }, 2000); };
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(done, function() {
var ta=document.createElement('textarea'); ta.value=text; document.body.appendChild(ta); ta.select();
try{document.execCommand('copy');}catch(e){} document.body.removeChild(ta); done();
});
} else {
var ta=document.createElement('textarea'); ta.value=text; document.body.appendChild(ta); ta.select();
try{document.execCommand('copy');}catch(e){} document.body.removeChild(ta); done();
}
};
})();
</script>
<!-- Kill-switch: /?reset=1 — насильно снести SW + caches + reload.
Используется когда старая версия SW застряла и отдаёт сломанный кэш. -->
<script>
(function() {
var p = new URLSearchParams(location.search);
if (p.get('reset') !== '1') return;
document.body.innerHTML = '<div style="padding:24px;font-family:system-ui;color:#E8EEF5;background:#0E2034;min-height:100vh;"><h2>Сбрасываем кэш…</h2><p>Подождите 2-3 секунды.</p></div>';
var jobs = [];
if ('serviceWorker' in navigator) {
jobs.push(navigator.serviceWorker.getRegistrations().then(function(regs) {
return Promise.all(regs.map(function(r) { return r.unregister(); }));
}));
}
if ('caches' in window) {
jobs.push(caches.keys().then(function(keys) {
return Promise.all(keys.map(function(k) { return caches.delete(k); }));
}));
}
Promise.all(jobs).finally(function() {
setTimeout(function() { location.replace('/'); }, 800);
});
})();
</script>
<!-- Boot watchdog: если через 6 секунд #root пуст — показать диагностику.
Включает кнопки «Копировать лог» (RC_LOG) и «Сбросить и перезагрузить». -->
<script>
(function() {
function esc(s) { return String(s).replace(/[&<>]/g, function(c){return {'&':'&','<':'<','>':'>'}[c];}); }
function showDiagnostic() {
var root = document.getElementById('root');
if (root && root.children.length > 0) return;
if (new URLSearchParams(location.search).get('reset') === '1') return;
var sw = 'serviceWorker' in navigator
? (navigator.serviceWorker.controller ? 'есть controller (' + (navigator.serviceWorker.controller.state || 'unknown') + ')' : 'нет controller')
: 'не поддерживается';
var html = '<div style="padding:16px;font-family:system-ui,sans-serif;color:#E8EEF5;background:#0E2034;min-height:100vh;line-height:1.5;">';
html += '<h2 style="color:#FF6B47;margin:0 0 4px">Приложение не запустилось</h2>';
html += '<p style="font-size:11px;color:#6B7E96;margin:0 0 16px">session: ' + (window.RC_LOG ? window.RC_LOG.SESSION_ID : '?') + '</p>';
html += '<p style="font-size:13px;color:#A9B8CA;margin:0 0 6px">Состояние:</p>';
html += '<ul style="font-size:12px;font-family:monospace;background:#0B1A2C;padding:10px 20px;border-radius:8px;color:#A9B8CA;margin:0 0 14px;">';
html += '<li>APP_VERSION: ' + (window.APP_VERSION || '✗ не задана (бандл не выполнился)') + '</li>';
html += '<li>React: ' + (typeof React !== 'undefined' ? 'v' + React.version : '✗ не загружен') + '</li>';
html += '<li>ReactDOM: ' + (typeof ReactDOM !== 'undefined' ? 'OK' : '✗ не загружен') + '</li>';
html += '<li>SW: ' + sw + '</li>';
html += '<li>Cache API: ' + (window.caches ? 'OK' : 'нет') + '</li>';
html += '<li>readyState: ' + document.readyState + '</li>';
html += '<li>online: ' + navigator.onLine + '</li>';
html += '</ul>';
if (window.RC_LOG) {
var all = window.RC_LOG.all();
var errs = all.filter(function(e){ return e.level === 'error'; });
if (errs.length) {
html += '<p style="font-size:13px;color:#FF6B47;margin:0 0 6px">Ошибки (' + errs.length + '):</p>';
html += '<ul style="font-size:11px;font-family:monospace;color:#FF6B47;background:#0B1A2C;padding:10px 20px;border-radius:8px;margin:0 0 14px;">';
errs.slice(-8).forEach(function(e) {
var d = e.data ? ' — ' + (typeof e.data === 'string' ? e.data : JSON.stringify(e.data)).slice(0, 120) : '';
html += '<li>[' + e.ch + '] ' + esc(e.msg + d) + '</li>';
});
html += '</ul>';
}
html += '<p style="font-size:13px;color:#A9B8CA;margin:0 0 6px">Последние события (' + all.length + ' всего):</p>';
html += '<ul style="font-size:10px;font-family:monospace;background:#0B1A2C;padding:10px 20px;border-radius:8px;color:#A9B8CA;margin:0 0 14px;max-height:200px;overflow:auto;">';
all.slice(-10).forEach(function(e) {
var time = e.iso.slice(11, 19);
html += '<li>' + time + ' [' + e.level + '/' + e.ch + '] ' + esc(e.msg) + '</li>';
});
html += '</ul>';
}
html += '<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:16px">';
html += '<button id="rc-copy" style="padding:10px 16px;background:#1F3556;color:#E8EEF5;border:1px solid #2C4A75;border-radius:8px;font-weight:600;font-size:13px;cursor:pointer">Скопировать лог</button>';
html += '<a href="/?reset=1" style="padding:10px 16px;background:#FF6B47;color:#0E2034;text-decoration:none;border-radius:8px;font-weight:600;font-size:13px">Сбросить и перезагрузить</a>';
html += '</div>';
html += '<p style="font-size:11px;color:#6B7E96;margin:18px 0 0;">Сделай скриншот и пришли разработчику — это поможет починить.</p>';
html += '</div>';
document.body.innerHTML = html;
var btn = document.getElementById('rc-copy');
if (btn && window.RC_LOG) {
btn.onclick = function() {
var text = window.RC_LOG.export();
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(function() {
btn.textContent = '✓ Скопировано';
setTimeout(function(){ btn.textContent = 'Скопировать лог'; }, 2000);
}, function() { fallbackCopy(text, btn); });
} else { fallbackCopy(text, btn); }
};
}
}
function fallbackCopy(text, btn) {
var ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed'; ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); btn.textContent = '✓ Скопировано'; }
catch(e) { btn.textContent = '✗ Не получилось'; }
document.body.removeChild(ta);
setTimeout(function(){ btn.textContent = 'Скопировать лог'; }, 2000);
}
setTimeout(showDiagnostic, 6000);
})();
</script>
<!-- Self-hosted React/ReactDOM (same-origin) — НЕ зависим от unpkg.com.
Критично для РФ-сетей где внешние CDN троттлятся/блокируются. -->
<script src="/vendor/react.production.min.js"></script>
<script src="/vendor/react-dom.production.min.js"></script>
<!-- Sprint 7: предкомпилированный бандл (esbuild). Заменяет Babel Standalone
+ ~27 отдельных script-тегов. Источник: app/**, src/data/**.
Пересборка: npm run build. НЕ редактировать dist/ вручную. -->
<script src="/dist/app.bundle.js"></script>
<!-- Sprint 11 Phase 1: qna.js (база знаний, 310 KB gzip) грузится ОТДЕЛЬНО
и лениво (defer = после парсинга HTML и бандла, не блокирует первый рендер).
Chat/QnA-экраны рендерят skeleton пока window.QNA_SAMPLE не доступен. -->
<script src="/src/data/qna.js" defer></script>
</body>
</html>