Обновить окно ошибки запуска UI

This commit is contained in:
AidarKC
2026-11-16 21:14:05 +03:00
parent d9fdaf1930
commit a86a380dc7
5 changed files with 216 additions and 38 deletions
+106 -36
View File
@@ -39,7 +39,7 @@
}());
</script>
<script>
window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
window.__SHINE_BUILD_HASH__ = '20261116-boot-error-ui-v1';
window.__SHINE_CLIENT_VERSION__ = '1.20.9';
</script>
<script>
@@ -301,8 +301,7 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
const shell = document.createElement('div');
shell.id = menuId;
shell.className = 'modal-shell boot-error-menu-shell';
// Красная строка BOOT ERROR имеет z-index 999999. Меню ошибки должно
// всегда находиться поверх неё, не меняя слои остальных модальных окон.
// Меню диагностики должно быть над аварийным экраном.
shell.style.zIndex = '1000000';
shell.innerHTML = `
<div class="modal-backdrop" data-action="close"></div>
@@ -368,6 +367,8 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
if (!ok) {
throw new Error('Не удалось отправить ошибку в лог на сервере');
}
setState({ ...(getState() || {}), sentToServer: true });
updateBootOverlay();
showFeedback('Ошибка отправлена в лог на сервере');
} catch (error) {
showFeedback(error?.message || 'Не удалось отправить ошибку в лог на сервере', 'error');
@@ -393,6 +394,55 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
console.warn('boot error menu failed', error);
}
};
// Краткая безопасная причина для скриншота. Исходный stack и произвольный
// текст исключения доступны в меню диагностики, но не на публичном экране.
const explainBootFailure = (state) => {
const message = String(state.message || '');
const reason = String(state.reasonType || '');
if (/failed to (fetch|load|import)|module script|importing a module|networkerror|loading chunk/i.test(message)) {
return 'Не удалось загрузить модуль приложения.';
}
if (/syntaxerror|unexpected token|unexpected identifier|unexpected end of input/i.test(`${reason} ${message}`)) {
return 'Ошибка синтаксиса JavaScript.';
}
if (/referenceerror|is not defined/i.test(`${reason} ${message}`)) {
return 'Отсутствует необходимая функция или переменная.';
}
if (/typeerror|cannot read properties|is not a function/i.test(`${reason} ${message}`)) {
return 'Ошибка выполнения JavaScript (TypeError).';
}
if (state.kind === 'unhandled_rejection') {
return 'Не удалось завершить операцию при запуске.';
}
return 'Техническая ошибка при запуске приложения.';
};
const bootSourceHint = (state) => {
let filename = '';
try {
const path = new URL(String(state.sourceUrl || ''), window.location.origin).pathname;
const candidate = path.split('/').pop() || '';
if (/^[a-zA-Z0-9_.-]{1,80}$/.test(candidate)) filename = candidate;
} catch {}
const line = Number.isSafeInteger(state.lineNumber) && state.lineNumber > 0
? state.lineNumber : null;
return filename ? `Источник: ${filename}${line ? `:${line}` : ''}` : '';
};
const updateBootOverlay = () => {
const el = document.getElementById('boot-error-overlay');
const state = getState();
if (!el || !state) return;
const cause = el.querySelector('[data-boot-error="cause"]');
const source = el.querySelector('[data-boot-error="source"]');
const status = el.querySelector('[data-boot-error="status"]');
if (cause) cause.textContent = `Причина: ${explainBootFailure(state)}`;
if (source) {
source.textContent = bootSourceHint(state);
source.hidden = !source.textContent;
}
if (status) status.textContent = state.sentToServer === true
? 'Отчёт об ошибке принят сервером.'
: 'Отправка отчёта не подтверждена. Пришлите скриншот этого окна.';
};
const show = (title, text, extra = {}) => {
try {
const reportState = {
@@ -405,49 +455,68 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
columnNumber: Number.isFinite(extra.columnNumber) ? extra.columnNumber : (Number.isFinite(extra.colno) ? extra.colno : null),
reasonType: safeString(extra.reasonType || '', 64),
clientTs: Number.isFinite(extra.clientTs) ? extra.clientTs : Date.now(),
sentToServer: false,
};
setState(reportState);
let el = document.getElementById('boot-error-overlay');
if (!el) {
el = document.createElement('pre');
const light = document.documentElement.dataset.theme === 'light';
const surface = light ? '#ffffff' : '#1c1f27';
const text = light ? '#20222c' : '#f1f1f5';
const secondary = light ? '#666977' : '#a8abb8';
const border = light ? '#dedee5' : '#303440';
const accent = light ? '#4d447c' : '#b8aef5';
const accentText = light ? '#ffffff' : '#211c34';
el = document.createElement('div');
el.id = 'boot-error-overlay';
el.style.position = 'fixed';
el.style.left = '8px';
el.style.right = '8px';
el.style.bottom = '8px';
el.style.maxHeight = '40vh';
el.style.overflow = 'auto';
el.style.padding = '10px';
el.style.margin = '0';
el.style.background = 'rgba(120, 0, 0, 0.92)';
el.style.color = '#fff';
el.style.fontSize = '12px';
el.style.lineHeight = '1.4';
el.style.zIndex = '999999';
el.style.whiteSpace = 'pre-wrap';
el.style.cursor = 'pointer';
el.style.userSelect = 'none';
el.style.webkitUserSelect = 'none';
el.style.touchAction = 'manipulation';
el.setAttribute('role', 'button');
el.setAttribute('tabindex', '0');
el.setAttribute('aria-haspopup', 'dialog');
el.setAttribute('role', 'alert');
el.setAttribute('aria-label', 'Ошибка запуска приложения');
// Стили встроены специально: аварийный экран виден даже без CSS.
el.style.cssText = 'position:fixed;inset:0;z-index:999999;box-sizing:border-box;display:flex;align-items:center;justify-content:center;padding:20px;background:rgba(0,0,0,.48);visibility:visible;font-family:system-ui,-apple-system,sans-serif;';
const card = document.createElement('section');
card.style.cssText = `box-sizing:border-box;width:min(100%,440px);max-height:calc(100dvh - 40px);overflow:auto;padding:22px;border:1px solid var(--border-subtle,${border});border-radius:14px;background:var(--surface,${surface});color:var(--text-primary,${text});box-shadow:0 14px 42px rgba(0,0,0,.20);`;
const heading = document.createElement('strong');
heading.textContent = 'Не удалось запустить SHiNE';
heading.style.cssText = 'display:block;font-size:18px;line-height:1.4;font-weight:600;margin-bottom:10px;';
const intro = document.createElement('p');
intro.textContent = 'При загрузке возникла ошибка. Попробуйте обновить страницу.';
intro.style.cssText = 'margin:0 0 12px;font-size:14px;line-height:1.5;';
const cause = document.createElement('p');
cause.dataset.bootError = 'cause';
cause.style.cssText = `margin:0 0 4px;font-size:13px;line-height:1.5;color:var(--text-secondary,${secondary});overflow-wrap:anywhere;`;
const source = document.createElement('p');
source.dataset.bootError = 'source';
source.style.cssText = `margin:0 0 12px;font-size:12px;line-height:1.5;color:var(--text-secondary,${secondary});overflow-wrap:anywhere;`;
const status = document.createElement('p');
status.dataset.bootError = 'status';
status.style.cssText = `margin:0 0 18px;font-size:12px;line-height:1.5;color:var(--text-secondary,${secondary});`;
const actions = document.createElement('div');
actions.style.cssText = 'display:flex;flex-wrap:wrap;gap:10px;';
const button = (label, primary) => {
const result = document.createElement('button');
result.type = 'button';
result.textContent = label;
result.style.cssText = `flex:1 1 130px;min-height:42px;padding:10px;border:1px solid var(--border-control,${border});border-radius:10px;font:inherit;font-size:14px;font-weight:600;cursor:pointer;background:${primary ? `var(--accent,${accent})` : `var(--surface,${surface})`};color:${primary ? `var(--on-accent,${accentText})` : `var(--text-primary,${text})`};`;
return result;
};
const retry = button('Обновить страницу', true);
retry.addEventListener('click', () => window.location.reload());
const details = button('Подробности', false);
details.addEventListener('click', openMenu);
actions.append(retry, details);
card.append(heading, intro, cause, source, status, actions);
el.appendChild(card);
document.body.appendChild(el);
el.addEventListener('click', openMenu);
el.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
openMenu();
}
});
}
el.textContent = `[BOOT ERROR] ${title}\n${String(text || '')}`;
el.setAttribute('aria-label', `${title}. Нажмите, чтобы открыть меню действий.`);
el.title = 'Нажмите, чтобы открыть меню действий';
} catch {}
updateBootOverlay();
} catch (error) {
console.warn('boot error overlay failed', error);
}
};
window.addEventListener('error', (e) => {
// После запуска приложения ошибки обрабатывает единый client-error-reporter.
if (window.__SHINE_APP_ERROR_HANDLERS_READY__ === true) return;
// Предупреждение браузера о переносе замеров ResizeObserver на следующий кадр – не ошибка
if (/^ResizeObserver loop/.test(String(e?.message || ''))) return;
show('window.error', `${e?.message || ''}\n${e?.filename || ''}:${e?.lineno || ''}:${e?.colno || ''}`, {
@@ -461,6 +530,7 @@ window.__SHINE_BUILD_HASH__ = '20261116-client-error-reporting-v1';
});
});
window.addEventListener('unhandledrejection', (e) => {
if (window.__SHINE_APP_ERROR_HANDLERS_READY__ === true) return;
const reason = e?.reason;
show('unhandledrejection', reason?.stack || reason?.message || String(reason || 'unknown'), {
kind: 'unhandled_rejection',