переиспользует готовый клиентский tableToExcel (настоящий .xlsx, не HTML-в-.xls). Итог сметы — в имени листа. Браузер-verified (Blob 7КБ, корректный MIME xlsx). APP_VERSION 2026-07-17p.
1630 lines
92 KiB
HTML
1630 lines
92 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Сметный ИИ-ассистент</title>
|
||
<style>
|
||
:root {
|
||
--bg: #f4efe9; --bg-card: #ffffff; --bg-input: #ffffff; --bg-sunken: #faf7f3;
|
||
--text: #2b2926; --text-muted: #6b6258; --text-light: #948a7d;
|
||
--border: #ddd0bf; --border-light: #ece4d9;
|
||
--accent: #c0453a; --accent-hover: #a5392f; --accent-active: #8f3128; --accent-light: rgba(192,69,58,.08);
|
||
--user-bg: #2b2926; --user-text: #fbf9f6;
|
||
--ai-bg: #ffffff; --ai-border: #ece4d9;
|
||
--file-bg: #f4efe9; --file-border: #ddd0bf;
|
||
--error-bg: #fff1f2; --error-border: #fecdd3;
|
||
--system-bg: #efe9e1; --system-text: #847a6d;
|
||
--ok: #1f6f43; --ok-hover: #18603a;
|
||
--shadow-sm: 0 1px 2px rgba(43,41,38,.05);
|
||
--shadow-md: 0 6px 24px rgba(43,41,38,.09);
|
||
--focus-ring: 0 0 0 3px rgba(192,69,58,.28);
|
||
--radius-sm: 7px; --radius: 10px; --radius-lg: 16px;
|
||
/* spacing scale (4px rhythm) */
|
||
--s1: .25rem; --s2: .5rem; --s3: .75rem; --s4: 1rem; --s5: 1.5rem; --s6: 2rem;
|
||
}
|
||
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; background: var(--bg); height: 100vh; display: flex; flex-direction: column; color: var(--text); line-height: 1.55; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
|
||
|
||
/* Видимый фокус для клавиатуры — Ководство: состояния обязательны */
|
||
:focus-visible { outline: none; box-shadow: var(--focus-ring); border-radius: var(--radius-sm); }
|
||
button { font-family: inherit; }
|
||
/* Только для скринридеров (срез 2.1): визуально скрыто, доступно ассистивным технологиям */
|
||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
|
||
.skip-link { position: absolute; left: -999px; top: 0; z-index: 200; background: var(--accent); color: #fff; padding: .5rem .9rem; border-radius: 0 0 var(--radius) 0; }
|
||
.skip-link:focus { left: 0; }
|
||
::selection { background: rgba(192,69,58,.18); }
|
||
|
||
/* Тихий скроллбар */
|
||
* { scrollbar-width: thin; scrollbar-color: var(--border) transparent; }
|
||
*::-webkit-scrollbar { width: 10px; height: 10px; }
|
||
*::-webkit-scrollbar-thumb { background: var(--border); border-radius: 6px; border: 3px solid transparent; background-clip: padding-box; }
|
||
*::-webkit-scrollbar-thumb:hover { background: var(--text-light); background-clip: padding-box; }
|
||
*::-webkit-scrollbar-track { background: transparent; }
|
||
|
||
/* Login */
|
||
#login-screen { display: flex; align-items: center; justify-content: center; height: 100vh; background: linear-gradient(135deg, #f5f0eb 0%, #ede5db 100%); }
|
||
#login-form { background: var(--bg-card); padding: 2.5rem 2rem; border-radius: var(--radius-lg); box-shadow: var(--shadow-md); width: 340px; }
|
||
#login-form h2 { margin-bottom: .3rem; text-align: center; font-size: 1.4rem; font-weight: 700; color: var(--text); }
|
||
#login-form .subtitle { text-align: center; color: var(--text-muted); font-size: .85rem; margin-bottom: 1.5rem; display: block; }
|
||
#login-form input { width: 100%; padding: .7rem .9rem; margin-bottom: .7rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .95rem; transition: border-color .2s; outline: none; background: var(--bg); }
|
||
#login-form input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||
#login-form button { width: 100%; padding: .75rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; transition: background .2s; margin-top: .3rem; }
|
||
#login-form button:hover { background: var(--accent-hover); }
|
||
#login-form button:active { background: var(--accent-active); transform: translateY(1px); }
|
||
#login-error { color: #e03131; font-size: .8rem; margin-bottom: .5rem; display: none; text-align: center; }
|
||
|
||
/* Chat */
|
||
#chat-screen { display: none; flex-direction: column; height: 100vh; }
|
||
#header { background: var(--bg-card); padding: .6rem 1.4rem; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; box-shadow: var(--shadow-sm); }
|
||
#header h1 { font-size: 1rem; font-weight: 650; color: var(--text); letter-spacing: -.012em; }
|
||
.header-actions { display: flex; gap: .4rem; }
|
||
.header-actions button { padding: .38rem .8rem; background: transparent; border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: .78rem; color: var(--text-muted); font-weight: 500; transition: all .15s; }
|
||
.header-actions button:hover { background: var(--bg); border-color: var(--accent); color: var(--accent); }
|
||
.header-actions button:active { transform: translateY(1px); }
|
||
|
||
#messages { flex: 1; overflow-y: auto; padding: 1.2rem 1.6rem; display: flex; flex-direction: column; gap: .7rem; width: 100%; }
|
||
.msg { max-width: 85%; padding: .8rem 1.1rem; border-radius: var(--radius-lg); line-height: 1.6; white-space: pre-wrap; word-break: break-word; font-size: .9rem; box-shadow: var(--shadow-sm); position: relative; }
|
||
.msg-time { display: block; font-size: .65rem; color: var(--text-muted, #999); margin-bottom: .3rem; opacity: .7; }
|
||
.msg-user { align-self: flex-end; background: var(--user-bg); color: var(--user-text); border-bottom-right-radius: 4px; }
|
||
.msg-ai { align-self: flex-start; background: var(--ai-bg); border: 1px solid var(--ai-border); border-bottom-left-radius: 4px; }
|
||
|
||
.copy-btn { display: block; margin-top: .5rem; margin-left: auto; background: transparent; border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: .7rem; padding: .2rem .6rem; color: var(--text-light); width: fit-content; transition: all .15s; }
|
||
.copy-btn:hover { background: var(--bg); color: var(--text-muted); border-color: var(--text-light); }
|
||
.msg-user .copy-btn { border-color: rgba(255,255,255,.25); color: rgba(255,255,255,.6); }
|
||
.msg-user .copy-btn:hover { background: rgba(255,255,255,.15); color: rgba(255,255,255,.9); }
|
||
.copy-btn.copied { background: #d3f9d8; border-color: #69db7c; color: #2b8a3e; }
|
||
|
||
.msg-tool { align-self: flex-start; background: #fffbeb; border: 1px solid #fde68a; font-size: .78rem; font-family: 'SF Mono', Menlo, monospace; color: #92400e; box-shadow: none; }
|
||
.msg-file { align-self: flex-start; background: var(--file-bg); border: 1px solid var(--file-border); font-size: .85rem; }
|
||
.msg-file a { color: #16a34a; text-decoration: none; font-weight: 500; }
|
||
.msg-file a:hover { text-decoration: underline; }
|
||
.dl-btn { display: block; width: fit-content; margin: .35rem 0 0; padding: .45rem .8rem; background: #16a34a; color: #fff !important; border-radius: var(--radius); font-weight: 600; }
|
||
.dl-btn:hover { background: #15803d; text-decoration: none !important; }
|
||
.msg-error { align-self: center; background: var(--error-bg); border: 1px solid var(--error-border); color: #e03131; font-size: .85rem; box-shadow: none; }
|
||
.retry-btn { display: inline-block; margin-top: .5rem; background: transparent; border: 1px solid #e03131; border-radius: 6px; cursor: pointer; font-size: .78rem; padding: .25rem .7rem; color: #e03131; transition: all .15s; }
|
||
.retry-btn:hover { background: rgba(224,49,49,.08); }
|
||
:root[data-theme="dark"] .retry-btn { border-color: #ff8585; color: #ff8585; }
|
||
.jump-latest { position: fixed; right: 24px; bottom: 100px; width: 40px; height: 40px; border-radius: 50%; border: 1px solid var(--border); background: var(--bg); color: var(--text); cursor: pointer; font-size: 1.15rem; line-height: 1; display: none; align-items: center; justify-content: center; box-shadow: 0 2px 10px rgba(0,0,0,.18); z-index: 50; }
|
||
.jump-latest:hover { background: var(--bg-hover, var(--border)); }
|
||
.fb-form { display: flex; flex-direction: column; gap: .4rem; margin-top: .5rem; padding: .5rem; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); max-width: 360px; }
|
||
.fb-cats { display: flex; gap: .4rem; }
|
||
.fb-cat { flex: 1; font-size: .75rem; padding: .25rem; border: 1px solid var(--border); border-radius: 6px; background: transparent; color: var(--text); cursor: pointer; }
|
||
.fb-cat.sel { border-color: #4c5b9a; background: rgba(76,91,154,.12); }
|
||
.fb-text { font-size: .8rem; padding: .4rem; border: 1px solid var(--border); border-radius: 6px; resize: vertical; min-height: 48px; background: var(--bg); color: var(--text); font-family: inherit; }
|
||
.fb-actions { display: flex; gap: .4rem; }
|
||
.fb-send, .fb-cancel { font-size: .78rem; padding: .25rem .7rem; border-radius: 6px; cursor: pointer; border: 1px solid var(--border); background: transparent; color: var(--text); }
|
||
.fb-send { background: #4c5b9a; color: #fff; border-color: transparent; }
|
||
#send-btn.is-stop { background: #b3402e; }
|
||
#send-btn.is-stop:hover { background: #9a3626; }
|
||
.onboarding { max-width: 640px; margin: 2rem auto; padding: 1.5rem; text-align: center; }
|
||
.ob-title { font-size: 1.35rem; font-weight: 700; color: var(--text); margin-bottom: .4rem; }
|
||
.ob-sub { font-size: .95rem; color: var(--text-light); margin-bottom: 1.1rem; }
|
||
.ob-chips { display: flex; flex-wrap: wrap; gap: .5rem; justify-content: center; }
|
||
.ob-chip { font-size: .88rem; padding: .5rem .85rem; border: 1.5px solid var(--border); border-radius: 999px; background: var(--bg-sunken); color: var(--text); cursor: pointer; transition: border-color .15s, background .15s; }
|
||
.ob-chip:hover { border-color: var(--accent); background: var(--bg-card); }
|
||
#quick-actions { display: flex; flex-wrap: wrap; gap: .4rem; margin-top: .5rem; justify-content: center; }
|
||
#quick-actions.hide { display: none; }
|
||
.qa-chip { font-size: .8rem; padding: .35rem .7rem; border: 1px solid var(--border); border-radius: 999px; background: var(--bg-sunken); color: var(--text-muted); cursor: pointer; transition: border-color .15s, color .15s; }
|
||
.qa-chip:hover { border-color: var(--accent); color: var(--accent); }
|
||
.est-panel { align-self: stretch; max-width: 100%; margin: .5rem 0; border: 1px solid var(--border); border-radius: 10px; background: var(--bg-card); overflow: hidden; }
|
||
.est-head { padding: .6rem .9rem; font-weight: 700; font-size: .95rem; color: var(--text); background: var(--bg-sunken); border-bottom: 1px solid var(--border); }
|
||
.est-scroll { overflow-x: auto; }
|
||
.est-table { width: 100%; border-collapse: collapse; font-size: .82rem; }
|
||
.est-table th, .est-table td { padding: .35rem .55rem; border-bottom: 1px solid var(--border-light, var(--border)); text-align: left; color: var(--text); vertical-align: top; }
|
||
.est-table th { position: sticky; top: 0; background: var(--bg-sunken); color: var(--text-muted); font-weight: 600; white-space: nowrap; }
|
||
.est-table td.num, .est-table th:nth-child(n+5) { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||
.est-table tr.est-unresolved td { background: var(--error-bg); }
|
||
.est-totals { padding: .5rem .9rem; border-top: 1px solid var(--border); }
|
||
.est-tot-row { display: flex; justify-content: space-between; gap: 1rem; font-size: .85rem; padding: .12rem 0; color: var(--text-muted); }
|
||
.est-tot-row .num { font-variant-numeric: tabular-nums; }
|
||
.est-tot-strong { font-weight: 700; color: var(--text); font-size: .95rem; }
|
||
.est-warn { padding: .5rem .9rem; border-top: 1px solid var(--border); background: var(--error-bg); color: var(--error-text, var(--text)); font-size: .8rem; display: flex; flex-direction: column; gap: .25rem; }
|
||
.ka-sub { padding: .3rem .9rem; font-size: .72rem; color: var(--text-muted); font-family: monospace; border-bottom: 1px solid var(--border-light, var(--border)); word-break: break-all; }
|
||
.est-table tr.ka-winner td { background: var(--accent-light); font-weight: 600; }
|
||
.est-actions { padding: .5rem .9rem; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; }
|
||
.est-dl { font-size: .82rem; padding: .35rem .8rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-sunken); color: var(--text); cursor: pointer; }
|
||
.est-dl:hover { border-color: var(--accent); color: var(--accent); }
|
||
.msg-system { align-self: center; background: var(--system-bg); border: none; font-size: .8rem; color: var(--system-text); box-shadow: none; padding: .4rem .8rem; }
|
||
.typing { align-self: flex-start; color: var(--text-light); font-style: italic; font-size: .85rem; padding: .4rem 0; }
|
||
|
||
/* Markdown rendered content */
|
||
.msg-ai { white-space: normal; max-width: 96%; }
|
||
.msg-ai h1, .msg-ai h2, .msg-ai h3, .msg-ai h4 { margin: .6rem 0 .3rem; font-size: .95rem; font-weight: 700; color: var(--text); }
|
||
.msg-ai h2 { font-size: 1rem; }
|
||
.msg-ai h3 { font-size: .95rem; }
|
||
.msg-ai h4 { font-size: .9rem; color: var(--text-muted); }
|
||
.msg-ai p { margin: .3rem 0; }
|
||
.msg-ai ul, .msg-ai ol { margin: .3rem 0 .3rem 1.2rem; }
|
||
.msg-ai li { margin: .15rem 0; }
|
||
.msg-ai strong { font-weight: 600; }
|
||
.msg-ai hr { border: none; border-top: 1px solid var(--border-light); margin: .6rem 0; }
|
||
.msg-ai .table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; margin: .5rem 0; border: 1px solid var(--border); border-radius: 8px; }
|
||
.msg-ai table { border-collapse: collapse; margin: 0; font-size: .82rem; width: auto; min-width: 100%; }
|
||
.msg-ai th, .msg-ai td { border: 1px solid var(--border-light); padding: .35rem .6rem; text-align: left; vertical-align: top; white-space: normal; max-width: 360px; }
|
||
.msg-ai th { background: var(--bg); font-weight: 600; position: sticky; top: 0; }
|
||
.msg-ai td.num, .msg-ai th.num { white-space: nowrap; text-align: right; font-variant-numeric: tabular-nums; }
|
||
.msg-ai tbody tr:nth-child(even) { background: rgba(0,0,0,.022); }
|
||
.msg-table-bar { display: flex; justify-content: flex-end; margin: .5rem 0 -.2rem; }
|
||
.msg-table-bar button { background: var(--ok); color: #fff; border: none; border-radius: var(--radius-sm); cursor: pointer; font-size: .72rem; padding: .3rem .75rem; font-weight: 600; transition: background .15s, transform .05s; }
|
||
.msg-table-bar button:hover { background: var(--ok-hover); }
|
||
.msg-table-bar button:active { transform: translateY(1px); }
|
||
.msg-ai code { background: #f5f0eb; padding: .1rem .3rem; border-radius: 3px; font-size: .85em; font-family: 'SF Mono', Menlo, monospace; }
|
||
.msg-ai pre { background: #2c2c2c; color: #f5f0eb; padding: .6rem; border-radius: 6px; overflow-x: auto; margin: .4rem 0; }
|
||
.msg-ai pre code { background: none; padding: 0; color: inherit; }
|
||
.msg-ai blockquote { border-left: 3px solid var(--accent); padding-left: .8rem; color: var(--text-muted); margin: .3rem 0; }
|
||
|
||
/* Input */
|
||
#input-area { background: var(--bg-card); border-top: 1px solid var(--border); padding: .8rem 1rem; box-shadow: 0 -2px 8px rgba(0,0,0,.03); }
|
||
#input-area > div { width: 100%; }
|
||
#drop-zone { border: 2px dashed transparent; border-radius: var(--radius); transition: all .2s; padding: .3rem; }
|
||
#drop-zone.dragover { border-color: var(--accent); background: var(--accent-light); }
|
||
#file-list { display: flex; gap: .3rem; flex-wrap: wrap; margin-bottom: .3rem; }
|
||
.file-badge { background: #ede5db; color: #2c2c2c; padding: .25rem .6rem; border-radius: 6px; font-size: .75rem; display: flex; align-items: center; gap: .3rem; font-weight: 500; }
|
||
.file-badge .remove { cursor: pointer; color: #e03131; font-weight: bold; }
|
||
#input-row { display: flex; gap: .5rem; align-items: flex-end; }
|
||
#msg-input { flex: 1; padding: .65rem .9rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .95rem; resize: none; min-height: 44px; max-height: 150px; font-family: inherit; line-height: 1.5; outline: none; transition: border-color .15s, box-shadow .15s; background: var(--bg-sunken); color: var(--text); }
|
||
#msg-input::placeholder { color: var(--text-light); }
|
||
#msg-input:focus { border-color: var(--accent); background: var(--bg-card); box-shadow: var(--focus-ring); }
|
||
#send-btn { padding: .65rem 1.3rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); cursor: pointer; font-size: .95rem; font-weight: 600; white-space: nowrap; transition: background .15s, transform .05s; }
|
||
#send-btn:hover { background: var(--accent-hover); }
|
||
#send-btn:active { background: var(--accent-active); transform: translateY(1px); }
|
||
#send-btn:disabled { background: var(--border); color: var(--bg-card); cursor: not-allowed; transform: none; }
|
||
#file-btn { padding: .65rem .7rem; background: var(--bg-sunken); border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: 1.1rem; line-height: 1; transition: all .15s; }
|
||
#file-btn:hover { border-color: var(--accent); background: var(--accent-light); }
|
||
#file-btn:active { transform: translateY(1px); }
|
||
|
||
/* Layout with left chat sidebar (Claude-desktop style) */
|
||
.app-layout { flex: 1; display: flex; min-height: 0; }
|
||
.sidebar { width: 264px; flex-shrink: 0; background: var(--bg-card); border-right: 1px solid var(--border); display: flex; flex-direction: column; }
|
||
.sidebar-head { padding: .7rem; border-bottom: 1px solid var(--border-light); }
|
||
.new-chat-btn { width: 100%; padding: .6rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .85rem; font-weight: 600; cursor: pointer; transition: background .15s, transform .05s; }
|
||
.new-chat-btn:hover { background: var(--accent-hover); }
|
||
.new-chat-btn:active { background: var(--accent-active); transform: translateY(1px); }
|
||
.chat-list { flex: 1; overflow-y: auto; padding: .4rem; }
|
||
.chat-list-empty { padding: 1rem .7rem; color: var(--text-muted); font-size: .78rem; text-align: center; }
|
||
.chat-item { position: relative; padding: .5rem .65rem .5rem .8rem; border-radius: var(--radius-sm); cursor: pointer; margin-bottom: .1rem; transition: background .12s; }
|
||
.chat-item:hover { background: var(--bg); }
|
||
.chat-item.active { background: var(--accent-light); }
|
||
.chat-item.active::before { content: ""; position: absolute; left: 0; top: 6px; bottom: 6px; width: 3px; border-radius: 3px; background: var(--accent); }
|
||
.chat-item.active .ci-title { color: var(--accent); font-weight: 600; }
|
||
#chat-search { width: 100%; margin-top: .5rem; padding: .4rem .6rem; border: 1.5px solid var(--border); border-radius: var(--radius-sm); font-size: .85rem; background: var(--bg-sunken); color: var(--text); outline: none; }
|
||
#chat-search:focus { border-color: var(--accent); }
|
||
.ci-actions { position: absolute; right: .35rem; top: .35rem; display: none; gap: .1rem; }
|
||
.chat-item:hover .ci-actions, .chat-item:focus-within .ci-actions { display: flex; }
|
||
.ci-act { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: pointer; font-size: .8rem; line-height: 1; padding: .18rem .3rem; color: var(--text-muted); }
|
||
.ci-act:hover { color: var(--accent); border-color: var(--accent); }
|
||
.ci-rename { width: 100%; padding: .2rem .35rem; border: 1.5px solid var(--accent); border-radius: var(--radius-sm); font-size: .85rem; font-family: inherit; background: var(--bg-card); color: var(--text); outline: none; }
|
||
.ci-title { font-size: .82rem; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.ci-date { font-size: .66rem; color: var(--text-muted); margin-top: .12rem; }
|
||
.main-col { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||
#sidebar-toggle { display: none; padding: .35rem .6rem; background: transparent; border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: .95rem; color: var(--text-muted); margin-right: .5rem; }
|
||
.sidebar-backdrop { display: none; }
|
||
@media (max-width: 720px) {
|
||
.sidebar { position: fixed; left: 0; top: 0; bottom: 0; z-index: 60; transform: translateX(-100%); transition: transform .2s; box-shadow: var(--shadow-md); }
|
||
.sidebar.open { transform: translateX(0); }
|
||
#sidebar-toggle { display: inline-block; padding: .5rem .7rem; min-width: 44px; min-height: 44px; } /* тач-таргет ≥44px */
|
||
.sidebar-backdrop.show { display: block; position: fixed; inset: 0; background: rgba(0,0,0,.3); z-index: 55; }
|
||
/* Срез 2.2: шапка не переполняется на узком экране — заголовок компактнее, кнопки прокручиваются */
|
||
#header h1 { font-size: 1.05rem; }
|
||
.header-actions { flex-wrap: nowrap; overflow-x: auto; -webkit-overflow-scrolling: touch; gap: .3rem; padding: 3px 2px; scroll-padding-inline: 3px; }
|
||
.header-actions button { white-space: nowrap; flex: 0 0 auto; }
|
||
#messages { padding-left: .7rem; padding-right: .7rem; }
|
||
.msg { max-width: 92%; }
|
||
.onboarding { margin: 1.2rem auto; padding: 1rem; }
|
||
}
|
||
|
||
/* ===== Тёмная тема (Ководство: тёплый «не-чёрный» фон, «не-белый» текст, */
|
||
/* акцент чуть подсвечен для контраста; переключатель + системное предпочтение) ===== */
|
||
html { color-scheme: light; }
|
||
:root[data-theme="dark"] {
|
||
color-scheme: dark;
|
||
--bg: #16140f; --bg-card: #211d17; --bg-input: #262019; --bg-sunken: #1b1813;
|
||
--text: #ece4d7; --text-muted: #a89c8a; --text-light: #7d7263;
|
||
--border: #3a332a; --border-light: #2a251e;
|
||
--accent: #d9695c; --accent-hover: #e58074; --accent-active: #c2564a; --accent-light: rgba(217,105,92,.16);
|
||
--user-bg: #39322a; --user-text: #f2ece2;
|
||
--ai-bg: #211d17; --ai-border: #2f2820;
|
||
--file-bg: #211d17; --file-border: #3a332a;
|
||
--error-bg: #3a1f1d; --error-border: #5e2b27;
|
||
--system-bg: #211d17; --system-text: #a89c8a;
|
||
--ok: #3fa066; --ok-hover: #4cb074;
|
||
--shadow-sm: 0 1px 2px rgba(0,0,0,.4);
|
||
--shadow-md: 0 10px 30px rgba(0,0,0,.55);
|
||
--focus-ring: 0 0 0 3px rgba(217,105,92,.42);
|
||
}
|
||
/* Места с захардкоженным цветом — переопределяем только в тёмной (light не трогаем) */
|
||
:root[data-theme="dark"] #login-screen { background: linear-gradient(135deg, #1b1813 0%, #131009 100%); }
|
||
:root[data-theme="dark"] #login-error,
|
||
:root[data-theme="dark"] .msg-error { color: #ff8585; }
|
||
:root[data-theme="dark"] .msg-tool { background: #2a2410; border-color: #4a3f1a; color: #ecc879; }
|
||
:root[data-theme="dark"] .msg-file a { color: #5fc27e; }
|
||
:root[data-theme="dark"] .file-badge { background: #2a2620; color: #ece4d7; }
|
||
:root[data-theme="dark"] .file-badge .remove { color: #ff8585; }
|
||
:root[data-theme="dark"] .copy-btn.copied { background: #1e3a25; border-color: #2f6b40; color: #86dca0; }
|
||
:root[data-theme="dark"] .msg-ai code { background: #2a2620; color: #ece4d7; }
|
||
:root[data-theme="dark"] .msg-ai pre { background: #0e0c09; color: #ece4d7; }
|
||
:root[data-theme="dark"] .msg-ai tbody tr:nth-child(even) { background: rgba(255,255,255,.045); }
|
||
:root[data-theme="dark"] #input-area { box-shadow: 0 -2px 10px rgba(0,0,0,.35); }
|
||
#theme-toggle { font-size: .95rem; line-height: 1; padding: .38rem .62rem; }
|
||
</style>
|
||
<script>
|
||
/* Тема ДО первой отрисовки — без мигания (FOUC).
|
||
Приоритет: сохранённый выбор → системное предпочтение → светлая. */
|
||
(function () {
|
||
try {
|
||
var t = localStorage.getItem('theme');
|
||
if (t !== 'dark' && t !== 'light') {
|
||
t = (window.matchMedia && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
|
||
}
|
||
document.documentElement.setAttribute('data-theme', t);
|
||
} catch (e) {}
|
||
})();
|
||
</script>
|
||
</head>
|
||
<body>
|
||
|
||
<!-- Живёт на уровне body (не в скрытом #chat-screen), иначе часть скринридеров не
|
||
регистрирует live-регион и озвучка недоступна до логина (Fable Ф2). -->
|
||
<div id="sr-status" class="sr-only" aria-live="polite" aria-atomic="true"></div>
|
||
|
||
<!-- Login Screen -->
|
||
<div id="login-screen" style="display:none">
|
||
<form id="login-form" onsubmit="return doLogin(event)">
|
||
<h2>Сметный ИИ</h2>
|
||
<span class="subtitle">Профессиональный ассистент</span>
|
||
<div id="login-error" role="alert"></div>
|
||
<input type="text" id="login-user" placeholder="Email или логин" aria-label="Email или логин" autocomplete="username" required>
|
||
<input type="password" id="login-pass" placeholder="Пароль" aria-label="Пароль" autocomplete="current-password" required>
|
||
<button type="submit">Войти</button>
|
||
<p style="text-align:center;margin-top:.8rem;font-size:.85rem;color:var(--text-muted)">Нет аккаунта? Попросите приглашение у администратора</p>
|
||
</form>
|
||
</div>
|
||
|
||
<!-- Chat Screen -->
|
||
<div id="chat-screen" style="display:none">
|
||
<a href="#msg-input" class="skip-link">Перейти к вводу сообщения</a>
|
||
<div class="sidebar-backdrop" id="sidebar-backdrop" onclick="closeSidebar()"></div>
|
||
<div class="app-layout">
|
||
<aside class="sidebar" id="sidebar" aria-label="Список диалогов">
|
||
<div class="sidebar-head">
|
||
<button class="new-chat-btn" onclick="newChat()">+ Новый чат</button>
|
||
<input id="chat-search" type="search" placeholder="Поиск по чатам" aria-label="Поиск по чатам" oninput="renderSessions()">
|
||
</div>
|
||
<nav class="chat-list" id="chat-list" aria-label="Ваши диалоги"></nav>
|
||
</aside>
|
||
<div class="main-col">
|
||
<div id="header" role="banner">
|
||
<div style="display:flex;align-items:center">
|
||
<button id="sidebar-toggle" onclick="toggleSidebar()" title="Чаты" aria-label="Открыть список диалогов" aria-expanded="false" aria-controls="sidebar">☰</button>
|
||
<h1>Сметный ИИ-ассистент</h1>
|
||
</div>
|
||
<div class="header-actions">
|
||
<button id="btn-admin" style="display:none" onclick="window.open('/admin','_blank')">Админ</button>
|
||
<!-- Депрекированы 2026-05-07 (этап 5 — депрекация отдельных страниц).
|
||
Функционал доступен через чат + hybrid MCP. Endpoints в main.py
|
||
не тронуты — старые URL работают, кнопки можно вернуть в одну строку.
|
||
<button onclick="window.open('/batch3','_blank')">Пакетная</button>
|
||
<button onclick="window.open('/ssr','_blank')">ССР</button>
|
||
<button onclick="window.open('/wizard','_blank')">Агрегатор</button>
|
||
<button onclick="window.open('/generate','_blank')">Генерация</button>
|
||
<button onclick="window.open('/reference','_blank')">Справочники</button>
|
||
<button onclick="window.open('/check','_blank')">Проверка</button>
|
||
-->
|
||
<button id="theme-toggle" onclick="toggleTheme()" title="Светлая / тёмная тема" aria-label="Переключить тему">☾</button>
|
||
<button onclick="newChat()">Новый диалог</button>
|
||
<button onclick="listFiles()">Файлы</button>
|
||
<button onclick="logout()">Выйти</button>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- role=log имеет неявный aria-live=polite; глушим его (aria-live=off), иначе стрим-перерисовка
|
||
innerHTML на каждый чанк зачитывала бы весь растущий ответ. Объявления — через #sr-status. -->
|
||
<div id="messages" role="log" aria-live="off" aria-label="История сообщений"></div>
|
||
|
||
<div id="input-area" role="region" aria-label="Ввод сообщения">
|
||
<div id="drop-zone">
|
||
<div id="file-list"></div>
|
||
<div id="input-row">
|
||
<button id="file-btn" onclick="document.getElementById('file-input').click()" title="Прикрепить файл" aria-label="Прикрепить файл">📎</button>
|
||
<textarea id="msg-input" placeholder="Напишите сообщение..." rows="1" aria-label="Сообщение" onkeydown="handleKey(event)"></textarea>
|
||
<button id="send-btn" onclick="onSendClick()">Отправить</button>
|
||
</div>
|
||
</div>
|
||
<div id="quick-actions" aria-label="Быстрые действия">
|
||
<button type="button" class="qa-chip" data-q="Проверь загруженную смету на ошибки">Проверить смету</button>
|
||
<button type="button" class="qa-chip" data-q="Сделай конъюнктурный анализ (форму) по материалу: ">Конъюнктурный анализ</button>
|
||
<button type="button" class="qa-chip" data-q="Проверь смету перед экспертизой — к чему придерётся ГГЭ">Перед экспертизой</button>
|
||
</div>
|
||
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
||
<div style="text-align:center;margin-top:4px"><a href="/static/security.html" target="_blank" style="font-size:.65rem;color:var(--text-muted);opacity:.4;text-decoration:none">О безопасности сервиса</a><span class="app-version" style="font-size:.65rem;color:var(--text-muted);opacity:.4;margin-left:.6rem"></span><span class="data-version" title="Период, на который актуальны цены корпусной базы" style="font-size:.65rem;color:var(--text-muted);opacity:.4;margin-left:.6rem"></span></div>
|
||
</div>
|
||
</div><!-- /.main-col -->
|
||
</div><!-- /.app-layout -->
|
||
</div>
|
||
|
||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.1.7/dist/purify.min.js" integrity="sha384-XQqX/4yiUGu+oyr87jvWzRuqBUK/adrY0DunhL+tID9m/9dwSpV8h9Fk/Sg6ifVQ" crossorigin="anonymous"></script>
|
||
<script src="https://cdn.jsdelivr.net/npm/tus-js-client@4.3.1/dist/tus.min.js" integrity="sha384-UlHjK3F7TCQCEUpnoa1ohMbP2oaWB3Aypv4gMo511vaZ86uUZ0Zv7UzZ0J1zRUT1" crossorigin="anonymous"></script>
|
||
<script>
|
||
// Configure marked for safe rendering
|
||
if (typeof marked !== 'undefined') {
|
||
marked.setOptions({ breaks: true, gfm: true });
|
||
}
|
||
|
||
// --- Тема (светлая/тёмная) ---
|
||
function applyThemeIcon() {
|
||
var b = document.getElementById('theme-toggle');
|
||
if (b) b.textContent = document.documentElement.getAttribute('data-theme') === 'dark' ? '☀' : '☾';
|
||
}
|
||
function toggleTheme() {
|
||
var next = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
|
||
document.documentElement.setAttribute('data-theme', next);
|
||
try { localStorage.setItem('theme', next); } catch (e) {}
|
||
applyThemeIcon();
|
||
}
|
||
applyThemeIcon();
|
||
|
||
// --- Версия UI из единого источника (main.py APP_VERSION → /api/version) ---
|
||
fetch('/api/version').then(function (r) { return r.json(); }).then(function (d) {
|
||
document.querySelectorAll('.app-version').forEach(function (el) { el.textContent = 'v.' + d.version; });
|
||
}).catch(function () {});
|
||
|
||
// Индикатор свежести данных: на какой ценовой период актуальна корпусная база.
|
||
fetch('/api/data-version').then(function (r) { return r.json(); }).then(function (d) {
|
||
if (!d.newest_period) return;
|
||
document.querySelectorAll('.data-version').forEach(function (el) { el.textContent = 'цены: ' + d.newest_period; });
|
||
}).catch(function () {});
|
||
|
||
function renderMarkdown(text) {
|
||
// Санитайзим вывод модели перед innerHTML: вырезаем onerror/onclick/javascript:
|
||
// и прочие XSS-векторы, сохраняя таблицы/ссылки/форматирование. Требуем оба
|
||
// (marked+DOMPurify); если хоть один не загрузился (CDN недоступен) — безопасный
|
||
// фолбэк с экранированием, чтобы не отрендерить непроверенный HTML.
|
||
if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
|
||
try { return DOMPurify.sanitize(marked.parse(text)); } catch(e) {}
|
||
}
|
||
return text.replace(/</g, '<').replace(/\n/g, '<br>');
|
||
}
|
||
|
||
// Числовая ячейка сметы: «1 234,56», «0,02», «110%», «—», «-». Учитываем
|
||
// неразрывные/узкие пробелы как разделители тысяч.
|
||
function isNumericCell(s) {
|
||
const t = (s || '').replace(/[\s ]/g, '').trim();
|
||
if (!t || t === '—' || t === '-') return true; // пустые/прочерки не ломают колонку
|
||
return /\d/.test(t) && /^[\d.,%+\-–]+$/.test(t);
|
||
}
|
||
|
||
// Пост-обработка таблиц в AI-ответе: горизонтальный скролл, числовые колонки
|
||
// (числа в одну строку, выравнивание вправо) и кнопка выгрузки в Excel.
|
||
// Идемпотентна — повторный вызов на уже обработанной таблице ничего не делает.
|
||
function enhanceTables(container) {
|
||
const tables = container.querySelectorAll('table');
|
||
tables.forEach(table => {
|
||
if (table.closest('.table-wrap')) return; // уже обёрнута
|
||
// классификация колонок: колонка числовая, если все её data-ячейки числовые
|
||
const rows = [...table.rows];
|
||
const bodyRows = rows.slice(1); // первая строка — шапка
|
||
const colCount = Math.max(...rows.map(r => r.cells.length));
|
||
for (let c = 0; c < colCount; c++) {
|
||
const cells = bodyRows.map(r => r.cells[c]).filter(Boolean);
|
||
if (cells.length && cells.every(td => isNumericCell(td.textContent))) {
|
||
cells.forEach(td => td.classList.add('num'));
|
||
const th = rows[0] && rows[0].cells[c];
|
||
if (th) th.classList.add('num');
|
||
}
|
||
}
|
||
// заголовок для Excel — ближайший предшествующий заголовок markdown (до обёртки)
|
||
let title = '';
|
||
for (let p = table.previousElementSibling; p; p = p.previousElementSibling) {
|
||
if (p.tagName === 'TABLE') break;
|
||
if (/^H[1-6]$/.test(p.tagName) && p.textContent.trim()) { title = p.textContent.trim().slice(0, 120); break; }
|
||
}
|
||
const wrap = document.createElement('div');
|
||
wrap.className = 'table-wrap';
|
||
table.parentNode.insertBefore(wrap, table);
|
||
wrap.appendChild(table);
|
||
// панель с кнопкой выгрузки
|
||
const bar = document.createElement('div');
|
||
bar.className = 'msg-table-bar';
|
||
const btn = document.createElement('button');
|
||
btn.textContent = '⤓ Скачать в Excel';
|
||
btn.onclick = () => tableToExcel(table, 'смета.xlsx', title);
|
||
bar.appendChild(btn);
|
||
wrap.parentNode.insertBefore(bar, wrap);
|
||
});
|
||
}
|
||
|
||
// --- Генерация НАСТОЯЩЕГО .xlsx (OOXML zip) без внешних библиотек. ---
|
||
// Трюк «HTML c расширением .xls» открывался как простыня тегов в Numbers/
|
||
// LibreOffice — это сырой zip с правильными XML-частями, открывается везде.
|
||
function _crc32(bytes) {
|
||
if (!_crc32.t) {
|
||
const t = new Uint32Array(256);
|
||
for (let n = 0; n < 256; n++) {
|
||
let c = n;
|
||
for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
|
||
t[n] = c >>> 0;
|
||
}
|
||
_crc32.t = t;
|
||
}
|
||
let crc = 0xFFFFFFFF;
|
||
for (let i = 0; i < bytes.length; i++) crc = _crc32.t[(crc ^ bytes[i]) & 0xFF] ^ (crc >>> 8);
|
||
return (crc ^ 0xFFFFFFFF) >>> 0;
|
||
}
|
||
// Сборка zip без сжатия (метод store) — валидный архив, Excel/Numbers открывают.
|
||
function _zipStore(files) {
|
||
const enc = new TextEncoder();
|
||
const u16 = n => [n & 0xFF, (n >>> 8) & 0xFF];
|
||
const u32 = n => [n & 0xFF, (n >>> 8) & 0xFF, (n >>> 16) & 0xFF, (n >>> 24) & 0xFF];
|
||
const local = [], central = [];
|
||
let offset = 0;
|
||
for (const f of files) {
|
||
const nameB = enc.encode(f.name);
|
||
const crc = _crc32(f.bytes), sz = f.bytes.length;
|
||
const lh = [].concat(u32(0x04034b50), u16(20), u16(0), u16(0), u16(0), u16(0),
|
||
u32(crc), u32(sz), u32(sz), u16(nameB.length), u16(0));
|
||
local.push(new Uint8Array(lh), nameB, f.bytes);
|
||
const ch = [].concat(u32(0x02014b50), u16(20), u16(20), u16(0), u16(0), u16(0), u16(0),
|
||
u32(crc), u32(sz), u32(sz), u16(nameB.length), u16(0), u16(0), u16(0), u16(0),
|
||
u32(0), u32(offset));
|
||
central.push(new Uint8Array(ch), nameB);
|
||
offset += lh.length + nameB.length + sz;
|
||
}
|
||
let cSize = 0; for (const c of central) cSize += c.length;
|
||
const end = [].concat(u32(0x06054b50), u16(0), u16(0), u16(files.length), u16(files.length),
|
||
u32(cSize), u32(offset), u16(0));
|
||
const parts = [...local, ...central, new Uint8Array(end)];
|
||
let total = 0; for (const p of parts) total += p.length;
|
||
const out = new Uint8Array(total); let pos = 0;
|
||
for (const p of parts) { out.set(p, pos); pos += p.length; }
|
||
return out;
|
||
}
|
||
function _colName(i) { let s = ''; i++; while (i > 0) { const m = (i - 1) % 26; s = String.fromCharCode(65 + m) + s; i = Math.floor((i - 1) / 26); } return s; }
|
||
function _xmlEsc(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }
|
||
// Строгое число: «1 234,56», «0,045», «-5». Шифры «01-02-056-02» (дефисы),
|
||
// «100 м3», «110%» — НЕ числа, остаются текстом.
|
||
function _asNumber(s) {
|
||
const t = s.replace(/[\s\u00a0\u202f\u2009\u2007]/g, '').replace(',', '.');
|
||
return /^-?\d+(\.\d+)?$/.test(t) ? t : null;
|
||
}
|
||
// Тип колонки по тексту шапки: денежная / количественная / номер / прочая.
|
||
function _colKind(h) {
|
||
h = (h || '').toLowerCase();
|
||
if (/№|п\/п/.test(h)) return 'idx';
|
||
if (/руб|стоим|цена|сумм|итог|всего/.test(h)) return 'money';
|
||
if (/кол|объ[её]м/.test(h)) return 'qty';
|
||
return 'auto';
|
||
}
|
||
// Оформление «как в ГРАНД-Смете»: шрифты, серая шапка, рамки, форматы чисел.
|
||
// Индексы cellXfs: 0 default,1 шапка,2 текст,3 деньги,4 кол-во,5 итог-число,
|
||
// 6 итог-текст,7 титул,8 номер-по-центру.
|
||
const _XLSX_STYLES =
|
||
'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
|
||
'<numFmts count="2"><numFmt numFmtId="164" formatCode="#,##0.00"/><numFmt numFmtId="165" formatCode="0.######"/></numFmts>' +
|
||
'<fonts count="3">' +
|
||
'<font><sz val="9"/><name val="Arial"/></font>' +
|
||
'<font><b/><sz val="9"/><name val="Arial"/></font>' +
|
||
'<font><b/><sz val="11"/><name val="Arial"/></font>' +
|
||
'</fonts>' +
|
||
'<fills count="3">' +
|
||
'<fill><patternFill patternType="none"/></fill>' +
|
||
'<fill><patternFill patternType="gray125"/></fill>' +
|
||
'<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/><bgColor indexed="64"/></patternFill></fill>' +
|
||
'</fills>' +
|
||
'<borders count="2">' +
|
||
'<border><left/><right/><top/><bottom/><diagonal/></border>' +
|
||
'<border><left style="thin"><color rgb="FF808080"/></left><right style="thin"><color rgb="FF808080"/></right><top style="thin"><color rgb="FF808080"/></top><bottom style="thin"><color rgb="FF808080"/></bottom><diagonal/></border>' +
|
||
'</borders>' +
|
||
'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
|
||
'<cellXfs count="9">' +
|
||
'<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' +
|
||
'<xf numFmtId="0" fontId="1" fillId="2" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center" wrapText="1"/></xf>' +
|
||
'<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="top" wrapText="1"/></xf>' +
|
||
'<xf numFmtId="164" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>' +
|
||
'<xf numFmtId="165" fontId="0" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>' +
|
||
'<xf numFmtId="164" fontId="1" fillId="0" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>' +
|
||
'<xf numFmtId="0" fontId="1" fillId="0" borderId="1" xfId="0" applyFont="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center" wrapText="1"/></xf>' +
|
||
'<xf numFmtId="0" fontId="2" fillId="0" borderId="0" xfId="0" applyFont="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>' +
|
||
'<xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>' +
|
||
'</cellXfs>' +
|
||
'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
|
||
'</styleSheet>';
|
||
|
||
function tableToExcel(table, filename, title) {
|
||
const enc = new TextEncoder();
|
||
const rows = [...table.rows].map(tr => [...tr.cells].map(td =>
|
||
td.textContent.replace(/[\u00a0\u202f\u2009\u2007]/g, ' ').trim()));
|
||
if (!rows.length) return;
|
||
const nCols = Math.max(...rows.map(r => r.length));
|
||
const header = rows[0] || [];
|
||
const kinds = [], widths = [];
|
||
for (let c = 0; c < nCols; c++) {
|
||
kinds[c] = _colKind(header[c]);
|
||
let mx = 6;
|
||
for (const r of rows) if (r[c]) mx = Math.max(mx, r[c].length);
|
||
widths[c] = Math.min(50, Math.max(6, mx + 2));
|
||
}
|
||
const base = title ? 1 : 0; // строка-титул сверху
|
||
let rowsXml = '';
|
||
if (title) rowsXml += `<row r="1"><c r="A1" t="inlineStr" s="7"><is><t xml:space="preserve">${_xmlEsc(title)}</t></is></c></row>`;
|
||
rows.forEach((cells, ri) => {
|
||
const rr = ri + 1 + base;
|
||
const isHeader = ri === 0;
|
||
const isTotal = !isHeader && cells.some(t => /итог|всего|подыто/i.test(t));
|
||
let cellsXml = '';
|
||
for (let c = 0; c < nCols; c++) {
|
||
const ref = _colName(c) + rr;
|
||
const text = cells[c] || '';
|
||
const num = isHeader ? null : _asNumber(text);
|
||
let s;
|
||
if (isHeader) s = 1;
|
||
else if (num !== null) s = isTotal ? 5 : (kinds[c] === 'money' ? 3 : kinds[c] === 'idx' ? 8 : 4);
|
||
else s = isTotal ? 6 : 2;
|
||
if (num !== null) cellsXml += `<c r="${ref}" s="${s}"><v>${num}</v></c>`;
|
||
else if (text) cellsXml += `<c r="${ref}" t="inlineStr" s="${s}"><is><t xml:space="preserve">${_xmlEsc(text)}</t></is></c>`;
|
||
else cellsXml += `<c r="${ref}" s="${s}"/>`;
|
||
}
|
||
rowsXml += `<row r="${rr}">${cellsXml}</row>`;
|
||
});
|
||
const lastCol = _colName(nCols - 1);
|
||
const colsXml = '<cols>' + widths.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`).join('') + '</cols>';
|
||
const freeze = base + 1; // закрепить титул(если есть)+шапку
|
||
const viewsXml = `<sheetViews><sheetView workbookViewId="0"><pane ySplit="${freeze}" topLeftCell="A${freeze + 1}" activePane="bottomLeft" state="frozen"/><selection pane="bottomLeft"/></sheetView></sheetViews>`;
|
||
const mergeXml = title ? `<mergeCells count="1"><mergeCell ref="A1:${lastCol}1"/></mergeCells>` : '';
|
||
const X = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
|
||
const sheetXml = X + '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
|
||
viewsXml + colsXml + '<sheetData>' + rowsXml + '</sheetData>' + mergeXml + '</worksheet>';
|
||
const files = [
|
||
{name: '[Content_Types].xml', bytes: enc.encode(X +
|
||
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
|
||
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
||
'<Default Extension="xml" ContentType="application/xml"/>' +
|
||
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
|
||
'<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' +
|
||
'<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>')},
|
||
{name: '_rels/.rels', bytes: enc.encode(X +
|
||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>')},
|
||
{name: 'xl/workbook.xml', bytes: enc.encode(X +
|
||
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||
'<sheets><sheet name="Смета" sheetId="1" r:id="rId1"/></sheets></workbook>')},
|
||
{name: 'xl/_rels/workbook.xml.rels', bytes: enc.encode(X +
|
||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' +
|
||
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')},
|
||
{name: 'xl/styles.xml', bytes: enc.encode(X + _XLSX_STYLES)},
|
||
{name: 'xl/worksheets/sheet1.xml', bytes: enc.encode(sheetXml)},
|
||
];
|
||
const blob = new Blob([_zipStore(files)], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url; a.download = filename;
|
||
document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||
}
|
||
|
||
|
||
// Лёгкая типографика прозы AI (Ководство): м²/м³, знак умножения, тире.
|
||
// СТРОГО минует таблицы и код — там шифры расценок (01-01-001), их дефисы
|
||
// и числа трогать нельзя. Идемпотентна (² не матчит 2 повторно).
|
||
const SKIP_TYPO = 'table, code, pre, .msg-table-bar, .msg-time, .copy-btn';
|
||
function typografAI(root) {
|
||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
||
acceptNode: n => (n.parentElement && n.parentElement.closest(SKIP_TYPO))
|
||
? NodeFilter.FILTER_REJECT
|
||
: (n.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT),
|
||
});
|
||
const nodes = [];
|
||
for (let n = walker.nextNode(); n; n = walker.nextNode()) nodes.push(n);
|
||
for (const n of nodes) {
|
||
n.nodeValue = n.nodeValue
|
||
.replace(/(\d)\s?м2(?![\wа-я²³])/gi, '$1 м²')
|
||
.replace(/(\d)\s?м3(?![\wа-я²³])/gi, '$1 м³')
|
||
.replace(/(\d)\s?[xх]\s?(\d)/g, '$1×$2') // 50x100 → 50×100
|
||
.replace(/ - /g, ' — '); // дефис-разделитель → тире
|
||
}
|
||
}
|
||
|
||
// Внешние ссылки в ответах ассистента (источники веб-поиска) открываем в новой
|
||
// вкладке, чтобы не увести пользователя из чата. rel — против tabnabbing.
|
||
function externalizeLinks(root) {
|
||
root.querySelectorAll('a[href]').forEach(a => {
|
||
const h = a.getAttribute('href') || '';
|
||
if (/^(https?:)?\/\//i.test(h)) {
|
||
a.target = '_blank';
|
||
a.rel = 'noopener noreferrer';
|
||
}
|
||
});
|
||
}
|
||
|
||
const API = '';
|
||
let token = localStorage.getItem('token');
|
||
let pendingFiles = [];
|
||
let streaming = false;
|
||
let abortCtrl = null; // срез 1.3: прерывание текущего ответа
|
||
let streamStartedAt = 0;
|
||
function setSendMode(streamingNow) {
|
||
const b = document.getElementById('send-btn');
|
||
if (!b) return;
|
||
b.disabled = false;
|
||
b.textContent = streamingNow ? 'Стоп' : 'Отправить';
|
||
b.classList.toggle('is-stop', streamingNow);
|
||
}
|
||
// Клик по кнопке: отправка или стоп. Стоп с задержкой 400мс, чтобы случайный
|
||
// двойной клик по «Отправить» не убивал только что отправленный запрос.
|
||
function onSendClick() {
|
||
if (streaming) { if (abortCtrl && (performance.now() - streamStartedAt) > 400) abortCtrl.abort(); }
|
||
else sendMessage();
|
||
}
|
||
// Озвучка событий скринридеру (срез 2.1): #messages как role=log не делаем live,
|
||
// иначе стрим-перерисовка спамит SR всем растущим текстом. Вместо — точечный live-регион.
|
||
function srAnnounce(t) {
|
||
const el = document.getElementById('sr-status');
|
||
if (!el) return;
|
||
clearTimeout(el._t); // не терять объявление при быстрой серии вызовов
|
||
el.textContent = '';
|
||
el._t = setTimeout(() => { el.textContent = t; }, 30); // clear→set форсит повторное объявление
|
||
}
|
||
// crypto.randomUUID работает только в secure context (HTTPS / localhost),
|
||
// под голым HTTP по IP его нет — используем fallback
|
||
function genUUID() {
|
||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
|
||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
||
const r = Math.random() * 16 | 0;
|
||
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
|
||
});
|
||
}
|
||
// Session continuity: reuse last tabId from localStorage
|
||
// New session only via "Новый чат" button or ?tab=UUID
|
||
const urlTab = new URLSearchParams(window.location.search).get('tab');
|
||
let tabId = urlTab || localStorage.getItem('tabId') || genUUID();
|
||
localStorage.setItem('tabId', tabId);
|
||
|
||
function checkAdmin() {
|
||
try {
|
||
if (!token) return;
|
||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||
if (payload.role === 'admin') {
|
||
document.getElementById('btn-admin').style.display = '';
|
||
}
|
||
} catch(e) {}
|
||
}
|
||
|
||
// --- Init ---
|
||
// Validate token on page load (don't trust localStorage blindly)
|
||
(async () => {
|
||
if (!token) { showLogin(); return; }
|
||
try {
|
||
const r = await fetch(API + '/api/history?limit=1', {headers: {'Authorization': 'Bearer ' + token}});
|
||
if (r.ok) { checkAdmin(); showChat(); return; }
|
||
} catch {}
|
||
// Access token expired — try refresh
|
||
if (await tryRefreshToken()) { checkAdmin(); showChat(); }
|
||
else { logout(); showLogin(); }
|
||
})();
|
||
|
||
function showLogin() {
|
||
document.getElementById('login-screen').style.display = 'flex';
|
||
document.getElementById('chat-screen').style.display = 'none';
|
||
}
|
||
function showChat() {
|
||
document.getElementById('login-screen').style.display = 'none';
|
||
document.getElementById('chat-screen').style.display = 'flex';
|
||
document.getElementById('msg-input').focus();
|
||
loadHistory();
|
||
loadSessions();
|
||
}
|
||
|
||
// --- Auth ---
|
||
async function doLogin(e) {
|
||
e.preventDefault();
|
||
const user = document.getElementById('login-user').value;
|
||
const pass = document.getElementById('login-pass').value;
|
||
try {
|
||
const r = await fetch(API + '/api/login', {
|
||
method: 'POST',
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: JSON.stringify({username: user, password: pass})
|
||
});
|
||
if (!r.ok) throw new Error();
|
||
const data = await r.json();
|
||
token = data.token;
|
||
localStorage.setItem('token', token);
|
||
if (data.refresh_token) localStorage.setItem('refresh_token', data.refresh_token);
|
||
checkAdmin();
|
||
showChat(); // loadHistory сам покажет онбординг на пустом чате
|
||
} catch {
|
||
const le = document.getElementById('login-error');
|
||
le.textContent = ''; // очистка+переустановка гарантирует объявление role=alert
|
||
le.style.display = 'block';
|
||
setTimeout(() => { le.textContent = 'Неверный логин или пароль'; }, 30);
|
||
}
|
||
return false;
|
||
}
|
||
async function tryRefreshToken() {
|
||
const rt = localStorage.getItem('refresh_token');
|
||
if (!rt) return false;
|
||
try {
|
||
const r = await fetch(API + '/api/refresh', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({refresh_token: rt})});
|
||
if (!r.ok) return false;
|
||
const data = await r.json();
|
||
token = data.token;
|
||
localStorage.setItem('token', token);
|
||
return true;
|
||
} catch { return false; }
|
||
}
|
||
function logout() {
|
||
token = null;
|
||
localStorage.removeItem('refresh_token');
|
||
localStorage.removeItem('token');
|
||
showLogin();
|
||
}
|
||
function authHeaders() {
|
||
return {'Authorization': 'Bearer ' + token, 'X-Tab-Id': tabId};
|
||
}
|
||
async function authFetch(url, opts={}) {
|
||
let r = await fetch(url, {...opts, headers: {...(opts.headers||{}), ...authHeaders()}});
|
||
if (r.status === 401) {
|
||
const refreshed = await tryRefreshToken();
|
||
if (refreshed) r = await fetch(url, {...opts, headers: {...(opts.headers||{}), ...authHeaders()}});
|
||
else { logout(); showLogin(); }
|
||
}
|
||
return r;
|
||
}
|
||
|
||
// --- Messages ---
|
||
const msgs = document.getElementById('messages');
|
||
// Умный автоскролл: скроллим к низу только если пользователь уже «у дна» (иначе
|
||
// он читает выше — не дёргаем). Кнопка «↓» возвращает вниз.
|
||
function isPinned() { return msgs.scrollHeight - msgs.scrollTop - msgs.clientHeight < 80; }
|
||
function scrollIfPinned() { if (isPinned()) { msgs.scrollTop = msgs.scrollHeight; } else { jumpBtn.style.display = 'flex'; } }
|
||
const jumpBtn = document.createElement('button');
|
||
jumpBtn.className = 'jump-latest'; jumpBtn.textContent = '↓';
|
||
jumpBtn.title = 'К последнему'; jumpBtn.setAttribute('aria-label', 'К последнему сообщению');
|
||
jumpBtn.style.display = 'none';
|
||
jumpBtn.onclick = () => { msgs.scrollTop = msgs.scrollHeight; jumpBtn.style.display = 'none'; };
|
||
document.body.appendChild(jumpBtn);
|
||
msgs.addEventListener('scroll', () => { jumpBtn.style.display = isPinned() ? 'none' : 'flex'; });
|
||
|
||
// Онбординг (срез 1.2): приветствие + примеры-подсказки на пустом чате.
|
||
// Клик по подсказке подставляет её в поле ввода. Убирается при первом сообщении.
|
||
const ONBOARD_EXAMPLES = [
|
||
'Проверь смету на ошибки',
|
||
'Найди расценку ГЭСН по описанию работ',
|
||
'Что такое накладные расходы и сметная прибыль?',
|
||
'Сделай конъюнктурный анализ по прайсу',
|
||
];
|
||
function showOnboarding() {
|
||
if (document.getElementById('onboarding')) return;
|
||
if (msgs.querySelector('.msg-user, .msg-ai')) return; // уже есть реальный диалог
|
||
const box = document.createElement('div');
|
||
box.id = 'onboarding';
|
||
box.className = 'onboarding';
|
||
const h = document.createElement('div');
|
||
h.className = 'ob-title';
|
||
h.textContent = 'Чем помочь со сметой?';
|
||
const sub = document.createElement('div');
|
||
sub.className = 'ob-sub';
|
||
sub.textContent = 'Задайте вопрос, прикрепите файл сметы или начните с примера:';
|
||
box.appendChild(h); box.appendChild(sub);
|
||
const chips = document.createElement('div');
|
||
chips.className = 'ob-chips';
|
||
ONBOARD_EXAMPLES.forEach(ex => {
|
||
const c = document.createElement('button');
|
||
c.type = 'button'; c.className = 'ob-chip'; c.textContent = ex;
|
||
c.onclick = () => {
|
||
const inp = document.getElementById('msg-input');
|
||
inp.value = ex; inp.focus();
|
||
inp.dispatchEvent(new Event('input')); // авто-высота textarea
|
||
};
|
||
chips.appendChild(c);
|
||
});
|
||
box.appendChild(chips);
|
||
msgs.appendChild(box);
|
||
}
|
||
|
||
function addMsg(type, text, ts) {
|
||
const ob = document.getElementById('onboarding'); if (ob) ob.remove(); // любое сообщение убирает приветствие
|
||
const div = document.createElement('div');
|
||
div.className = 'msg msg-' + type;
|
||
if (type === 'error') div.setAttribute('role', 'alert'); // единый канал озвучки ошибок (assertive)
|
||
// Timestamp
|
||
const time = document.createElement('span');
|
||
time.className = 'msg-time';
|
||
const d = ts ? new Date(ts < 1e12 ? ts * 1000 : ts) : new Date();
|
||
time.textContent = d.toLocaleString('ru-RU', {day:'2-digit',month:'2-digit',year:'2-digit',hour:'2-digit',minute:'2-digit'});
|
||
div.appendChild(time);
|
||
// Store raw text for copy and streaming
|
||
div._rawText = text;
|
||
if (type === 'ai') {
|
||
div.innerHTML = renderMarkdown(text);
|
||
div.prepend(time);
|
||
enhanceTables(div);
|
||
typografAI(div);
|
||
externalizeLinks(div);
|
||
} else {
|
||
div.textContent = text;
|
||
div.prepend(time);
|
||
}
|
||
if (type !== 'system') {
|
||
const btn = document.createElement('button');
|
||
btn.className = 'copy-btn';
|
||
btn.textContent = 'Копировать';
|
||
btn.onclick = () => {
|
||
navigator.clipboard.writeText(div._rawText || div.textContent);
|
||
btn.textContent = 'Скопировано';
|
||
btn.classList.add('copied');
|
||
setTimeout(() => { btn.textContent = 'Копировать'; btn.classList.remove('copied'); }, 1500);
|
||
};
|
||
div.appendChild(btn);
|
||
}
|
||
if (type === 'ai') {
|
||
const rep = document.createElement('button');
|
||
rep.className = 'copy-btn report-btn';
|
||
rep.textContent = 'Сообщить об ошибке';
|
||
rep.onclick = () => openFeedbackForm(rep, div._rawText || '');
|
||
div.appendChild(rep);
|
||
}
|
||
msgs.appendChild(div);
|
||
scrollIfPinned();
|
||
return div;
|
||
}
|
||
function addTyping() {
|
||
const div = document.createElement('div');
|
||
div.className = 'typing';
|
||
div.id = 'typing-indicator';
|
||
div.textContent = 'Claude думает...';
|
||
msgs.appendChild(div);
|
||
scrollIfPinned();
|
||
return div;
|
||
}
|
||
function removeTyping() {
|
||
const el = document.getElementById('typing-indicator');
|
||
if (el) el.remove();
|
||
}
|
||
|
||
// --- File Upload ---
|
||
const dropZone = document.getElementById('drop-zone');
|
||
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('dragover'); });
|
||
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
|
||
dropZone.addEventListener('drop', e => {
|
||
e.preventDefault();
|
||
dropZone.classList.remove('dragover');
|
||
handleFiles(e.dataTransfer.files);
|
||
});
|
||
|
||
function handleFiles(fileList) {
|
||
for (const f of fileList) pendingFiles.push(f);
|
||
renderFileList();
|
||
}
|
||
function renderFileList() {
|
||
const fl = document.getElementById('file-list');
|
||
fl.innerHTML = '';
|
||
pendingFiles.forEach((f, i) => {
|
||
const badge = document.createElement('span');
|
||
badge.className = 'file-badge';
|
||
badge.textContent = f.name + ' ';
|
||
const rm = document.createElement('span');
|
||
rm.className = 'remove';
|
||
rm.textContent = '×';
|
||
rm.onclick = () => removeFile(i);
|
||
badge.appendChild(rm);
|
||
fl.appendChild(badge);
|
||
});
|
||
}
|
||
function removeFile(i) { pendingFiles.splice(i, 1); renderFileList(); }
|
||
|
||
// Access token (24h) can expire mid-upload of a multi-GB file; refresh just
|
||
// before it lapses so long uploads don't 401 halfway through.
|
||
function jwtExpSoon() {
|
||
try {
|
||
const p = JSON.parse(atob(token.split('.')[1]));
|
||
return (p.exp * 1000) < (Date.now() + 120000);
|
||
} catch { return false; }
|
||
}
|
||
|
||
// Resumable upload of one file via the tus protocol. Survives network drops and
|
||
// page reloads (tus-js-client stores the upload URL and resumes from the offset
|
||
// the server already has). Resolves {name, ok, status}.
|
||
function uploadOne(file, onPct, fresh) {
|
||
return new Promise((resolve) => {
|
||
const upload = new tus.Upload(file, {
|
||
endpoint: API + '/api/tus',
|
||
chunkSize: 8 * 1024 * 1024,
|
||
retryDelays: [0, 3000, 5000, 10000, 20000],
|
||
removeFingerprintOnSuccess: true,
|
||
metadata: { filename: file.name, tab_id: tabId },
|
||
async onBeforeRequest(req) {
|
||
if (jwtExpSoon()) await tryRefreshToken();
|
||
req.setHeader('Authorization', 'Bearer ' + token);
|
||
req.setHeader('X-Tab-Id', tabId);
|
||
},
|
||
onShouldRetry(err) {
|
||
const s = err.originalResponse ? err.originalResponse.getStatus() : 0;
|
||
if (s === 401) return !!localStorage.getItem('refresh_token');
|
||
return s === 0 || s === 429 || s >= 500;
|
||
},
|
||
onProgress(sent, total) { onPct(Math.floor(sent / total * 100)); },
|
||
onSuccess() { resolve({ name: file.name, ok: true }); },
|
||
onError(error) {
|
||
const s = error.originalResponse ? error.originalResponse.getStatus() : 0;
|
||
if (s === 401) { logout(); resolve({ name: file.name, ok: false, status: s }); return; }
|
||
// A stale resumed upload can wedge on 404/409 — abandon it and retry once cleanly.
|
||
if (!fresh && (s === 404 || s === 409)) { resolve(uploadOne(file, onPct, true)); return; }
|
||
resolve({ name: file.name, ok: false, status: s });
|
||
},
|
||
});
|
||
if (fresh) {
|
||
upload.start(); // clean upload, skip resuming any stored partial
|
||
} else {
|
||
upload.findPreviousUploads().then((prev) => {
|
||
if (prev.length) upload.resumeFromPreviousUpload(prev[0]);
|
||
upload.start();
|
||
});
|
||
}
|
||
});
|
||
}
|
||
|
||
function uploadErrText(s) {
|
||
if (s === 400) return 'тип не поддерживается — нужны zip, xlsx, xls, xlsm, ods, pdf, doc, docx, csv, txt, xml, json, yaml, gge, esw, ges, smr, smt, rar, 7z и их многотомные части (.z01…, .001…, .r00…)';
|
||
if (s === 413) return 'слишком большой (максимум 3 ГБ на файл — большой архив разбейте на тома, они соберутся сами)';
|
||
if (s === 507) return 'на сервере не хватает места';
|
||
return 'ошибка загрузки (код ' + s + ')';
|
||
}
|
||
|
||
let uploadingActive = false;
|
||
async function uploadFiles() {
|
||
if (typeof tus === 'undefined') return uploadFilesLegacy(); // CDN blocked → degrade
|
||
if (uploadingActive) return []; // ignore re-entry (double-click)
|
||
uploadingActive = true;
|
||
const fileBtn = document.getElementById('file-btn');
|
||
const sendBtn = document.getElementById('send-btn');
|
||
if (fileBtn) fileBtn.disabled = true;
|
||
if (sendBtn) sendBtn.disabled = true;
|
||
try {
|
||
const files = pendingFiles.slice();
|
||
const prog = files.map(f => ({ name: f.name, pct: 0 }));
|
||
const fl = document.getElementById('file-list');
|
||
const render = () => {
|
||
fl.innerHTML = '';
|
||
prog.forEach(p => {
|
||
const b = document.createElement('span');
|
||
b.className = 'file-badge';
|
||
b.textContent = `${p.name} — ${p.pct}%`;
|
||
fl.appendChild(b);
|
||
});
|
||
};
|
||
render();
|
||
const results = [];
|
||
for (let i = 0; i < files.length; i++) {
|
||
results.push(await uploadOne(files[i], (pct) => { prog[i].pct = pct; render(); }));
|
||
}
|
||
pendingFiles = [];
|
||
renderFileList();
|
||
const failed = results.filter(r => !r.ok && r.status !== 401);
|
||
if (failed.length) {
|
||
addMsg('error', 'Не загружены — ' + failed.map(r => `${r.name} (${uploadErrText(r.status)})`).join('; '));
|
||
}
|
||
return results.filter(r => r.ok).map(r => r.name);
|
||
} finally {
|
||
uploadingActive = false;
|
||
if (fileBtn) fileBtn.disabled = false;
|
||
if (sendBtn) sendBtn.disabled = false;
|
||
}
|
||
}
|
||
|
||
// Fallback for when the tus client isn't available (e.g. CDN unreachable).
|
||
async function uploadFilesLegacy() {
|
||
const uploaded = [];
|
||
for (const f of pendingFiles) {
|
||
const fd = new FormData();
|
||
fd.append('file', f);
|
||
const r = await authFetch(API + '/api/upload', { method: 'POST', body: fd });
|
||
if (r.ok) uploaded.push((await r.json()).filename);
|
||
}
|
||
pendingFiles = [];
|
||
renderFileList();
|
||
return uploaded;
|
||
}
|
||
|
||
// --- Send Message ---
|
||
function handleKey(e) {
|
||
// Enter отправляет, но НИКОГДА не прерывает идущий ответ (стоп — только кнопкой).
|
||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (!streaming) sendMessage(); }
|
||
}
|
||
|
||
// Честный текст ошибки по HTTP-статусу: констатируем факт + одно действие,
|
||
// не выдумываем причину (CLAUDE.md). Никогда не показываем голый «Ошибка: 500».
|
||
function httpErrText(status) {
|
||
if (status === 429) return 'Слишком много запросов — подождите минуту и повторите.';
|
||
if (status === 413) return 'Слишком большой запрос — сократите сообщение.';
|
||
if (status === 400) return 'Запрос отклонён (возможно, слишком длинное сообщение).';
|
||
if (status >= 500) return 'Сервис не ответил (код ' + status + '). Можно повторить.';
|
||
return 'Не удалось отправить (код ' + status + ').';
|
||
}
|
||
|
||
// Ошибка с кнопкой «Повторить» — текст пользователя не теряется, повтор не дублирует пузырь.
|
||
function addErrorRetry(msg, retryText) {
|
||
const div = addMsg('error', msg); // addMsg сам ставит role=alert (assertive-озвучка) для type=error
|
||
const btn = document.createElement('button');
|
||
btn.textContent = 'Повторить';
|
||
btn.className = 'retry-btn';
|
||
btn.onclick = () => { if (streaming) return; div.remove(); runChat(retryText); };
|
||
div.appendChild(btn);
|
||
}
|
||
|
||
// Инлайн-форма фидбека вместо prompt(): категория + текст, Esc закрывает, фокус в поле.
|
||
function openFeedbackForm(btn, answerText) {
|
||
// isConnected: если стрим-перерисовка снесла старую форму — разрешаем открыть заново
|
||
// (иначе флаг «открыто» застревал бы навсегда, см. срез 1.5 fix).
|
||
if (btn._fbForm && btn._fbForm.isConnected) return;
|
||
const form = document.createElement('div');
|
||
form.className = 'fb-form';
|
||
btn._fbForm = form;
|
||
form.innerHTML =
|
||
'<div class="fb-cats">' +
|
||
'<button type="button" class="fb-cat" data-c="Ответ неверный">Ответ неверный</button>' +
|
||
'<button type="button" class="fb-cat" data-c="Другое">Другое</button></div>' +
|
||
'<textarea class="fb-text" placeholder="Что не так? (можно кратко)" aria-label="Комментарий"></textarea>' +
|
||
'<div class="fb-actions"><button type="button" class="fb-send">Отправить</button>' +
|
||
'<button type="button" class="fb-cancel">Отмена</button></div>';
|
||
btn.after(form);
|
||
const ta = form.querySelector('.fb-text');
|
||
let cat = '';
|
||
form.querySelectorAll('.fb-cat').forEach(c => c.onclick = () => {
|
||
form.querySelectorAll('.fb-cat').forEach(x => x.classList.remove('sel'));
|
||
c.classList.add('sel'); cat = c.dataset.c; ta.focus();
|
||
});
|
||
const close = () => { form.remove(); };
|
||
form.querySelector('.fb-cancel').onclick = close;
|
||
ta.addEventListener('keydown', e => { if (e.key === 'Escape') close(); });
|
||
const sendBtnFb = form.querySelector('.fb-send');
|
||
sendBtnFb.onclick = async () => {
|
||
if (sendBtnFb.disabled) return; // не плодить дубли POST при двойном клике
|
||
sendBtnFb.disabled = true;
|
||
const comment = (cat ? cat + ': ' : '') + ta.value.trim();
|
||
try {
|
||
const r = await authFetch('/api/feedback', {
|
||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||
body: JSON.stringify({comment: comment, answer: answerText})});
|
||
close();
|
||
btn.textContent = r.ok ? 'Спасибо, отправлено' : 'Ошибка отправки';
|
||
if (r.ok) btn.classList.add('copied');
|
||
} catch (e) { close(); btn.textContent = 'Ошибка отправки'; }
|
||
setTimeout(() => { btn.textContent = 'Сообщить об ошибке'; btn.classList.remove('copied'); }, 2200);
|
||
};
|
||
ta.focus();
|
||
}
|
||
|
||
async function sendMessage() {
|
||
if (streaming) return; // стоп — только через кнопку (onSendClick)
|
||
if (uploadingActive) return; // идёт загрузка файла — не плодить параллельные отправки
|
||
const input = document.getElementById('msg-input');
|
||
let text = input.value.trim();
|
||
if (!text && pendingFiles.length === 0) return;
|
||
|
||
// Upload files first
|
||
let uploaded = [];
|
||
if (pendingFiles.length > 0) {
|
||
uploaded = await uploadFiles();
|
||
if (uploaded.length > 0) {
|
||
const fileNote = 'Загружены файлы: ' + uploaded.join(', ');
|
||
addMsg('file', fileNote);
|
||
if (!text) text = 'Я загрузил файлы: ' + uploaded.join(', ') + '. Покажи их содержимое.';
|
||
else text = 'Файлы в рабочей директории: ' + uploaded.join(', ') + '\n\n' + text;
|
||
}
|
||
}
|
||
|
||
addMsg('user', text);
|
||
input.value = '';
|
||
input.style.height = 'auto';
|
||
await runChat(text);
|
||
}
|
||
|
||
async function runChat(text) {
|
||
if (streaming) return; // единая защита от параллельного запуска (retry/двойная отправка)
|
||
streaming = true;
|
||
const myCtrl = new AbortController();
|
||
abortCtrl = myCtrl;
|
||
streamStartedAt = performance.now();
|
||
setSendMode(true);
|
||
addTyping();
|
||
let aiDiv = null;
|
||
|
||
try {
|
||
const r = await fetch(API + '/api/chat', {
|
||
method: 'POST',
|
||
headers: {...authHeaders(), 'Content-Type': 'application/json'},
|
||
body: JSON.stringify({message: text}),
|
||
signal: myCtrl.signal,
|
||
});
|
||
|
||
if (r.status === 401) { logout(); return; }
|
||
if (!r.ok) { removeTyping(); addErrorRetry(httpErrText(r.status), text); return; }
|
||
|
||
removeTyping();
|
||
let aiText = '';
|
||
const reader = r.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let buffer = '';
|
||
|
||
while (true) {
|
||
const {done, value} = await reader.read();
|
||
if (done) break;
|
||
buffer += decoder.decode(value, {stream: true});
|
||
|
||
const lines = buffer.split('\n');
|
||
buffer = lines.pop();
|
||
|
||
let eventType = '';
|
||
for (const line of lines) {
|
||
if (line.startsWith('event: ')) {
|
||
eventType = line.slice(7);
|
||
} else if (line.startsWith('data: ')) {
|
||
const data = JSON.parse(line.slice(6));
|
||
if (eventType === 'text') {
|
||
if (!aiDiv) {
|
||
aiDiv = addMsg('ai', '');
|
||
}
|
||
aiText += data.text;
|
||
aiDiv._rawText = aiText;
|
||
// Re-render markdown, сохраняя время и ВСЕ контрол-кнопки
|
||
// (копирование + «сообщить об ошибке» — обе .copy-btn).
|
||
const ctrlBtns = Array.from(aiDiv.querySelectorAll('.copy-btn'));
|
||
const timeEl = aiDiv.querySelector('.msg-time');
|
||
aiDiv.innerHTML = renderMarkdown(aiText);
|
||
if (timeEl) aiDiv.prepend(timeEl);
|
||
ctrlBtns.forEach(b => aiDiv.appendChild(b));
|
||
scrollIfPinned();
|
||
} else if (eventType === 'tool') {
|
||
// Статус агента (срез 1.6): человеко-понятная подпись вместо сырого имени тула
|
||
const toolNames = {Bash: 'Считаю...', Read: 'Читаю файл...', Write: 'Готовлю файл...', Edit: 'Редактирую смету...', Glob: 'Ищу файлы...', Grep: 'Ищу в файлах...', WebSearch: 'Ищу в интернете...', WebFetch: 'Читаю страницу...', TodoWrite: 'Планирую шаги...'};
|
||
let label = toolNames[data.tool];
|
||
if (!label) {
|
||
const t = String(data.tool || '');
|
||
if (t.includes('verify')) label = 'Проверяю смету...';
|
||
else if (t.includes('find') || t.includes('search') || t.includes('corpus') || t.includes('price')) label = 'Ищу в базе смет...';
|
||
else if (t.startsWith('mcp__')) label = 'Работаю с данными сметы...';
|
||
else label = 'Обрабатываю...';
|
||
}
|
||
removeTyping();
|
||
addTyping().textContent = label;
|
||
} else if (eventType === 'done') {
|
||
removeTyping();
|
||
// Always show final result if we haven't shown text yet
|
||
if (!aiText && data.result) {
|
||
aiDiv = addMsg('ai', data.result);
|
||
}
|
||
} else if (eventType === 'files') {
|
||
// Агент подготовил файлы — кнопки скачивания прямо в чате
|
||
if (data.files && data.files.length) addFilesMsg(data.files);
|
||
} else if (eventType === 'estimate') {
|
||
// Структурированная смета — панель с таблицей (срез 6.1, JS НЕ считает)
|
||
if (data && data.positions) addEstimatePanel(data);
|
||
} else if (eventType === 'ka_form') {
|
||
// Конъюнктурный анализ — панель офферов (срез 7)
|
||
if (data && data.rows) addKaPanel(data);
|
||
}
|
||
eventType = '';
|
||
}
|
||
}
|
||
}
|
||
if (!aiDiv && !aiText) addMsg('ai', '(пустой ответ)');
|
||
srAnnounce('Ответ получен');
|
||
|
||
} catch (err) {
|
||
removeTyping();
|
||
if (err && err.name === 'AbortError') {
|
||
// при переключении/новом чате abort «тихий» — не сорим системным сообщением
|
||
if (!myCtrl._silent) { addMsg('system', '⏹ Остановлено. Ответ мог сгенерироваться не полностью.'); srAnnounce('Ответ остановлен'); }
|
||
} else {
|
||
addErrorRetry('Нет связи с сервисом. ' + (err.message || ''), text);
|
||
}
|
||
} finally {
|
||
// финализация таблиц/ссылок и при обрыве (Стоп) — иначе оборванный ответ без скролла/скачивания
|
||
if (aiDiv) { enhanceTables(aiDiv); typografAI(aiDiv); externalizeLinks(aiDiv); }
|
||
streaming = false;
|
||
if (abortCtrl === myCtrl) abortCtrl = null;
|
||
setSendMode(false);
|
||
document.getElementById('msg-input').focus();
|
||
loadSessions(); // обновить превью/порядок чатов в панели
|
||
}
|
||
}
|
||
|
||
// --- Панель сметы (срез 6.1, read-only): показывает числа ИЗ данных, сама НЕ считает ---
|
||
function fmtMoney(v) {
|
||
if (typeof v !== 'number' || !isFinite(v)) return v == null ? '' : String(v);
|
||
return v.toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2});
|
||
}
|
||
function addEstimatePanel(data) {
|
||
const panel = document.createElement('div');
|
||
panel.className = 'est-panel';
|
||
panel.setAttribute('role', 'region');
|
||
panel.setAttribute('aria-label', 'Смета');
|
||
const head = document.createElement('div');
|
||
head.className = 'est-head';
|
||
head.textContent = data.title || 'Смета';
|
||
panel.appendChild(head);
|
||
|
||
const scroll = document.createElement('div');
|
||
scroll.className = 'est-scroll';
|
||
const table = document.createElement('table');
|
||
table.className = 'est-table';
|
||
const thead = document.createElement('tr');
|
||
['№', 'Код', 'Наименование', 'Ед.', 'Кол-во', 'Цена/ед', 'Стоимость'].forEach(h => {
|
||
const th = document.createElement('th'); th.textContent = h; thead.appendChild(th);
|
||
});
|
||
table.appendChild(thead);
|
||
(data.positions || []).forEach((p, i) => {
|
||
const tr = document.createElement('tr');
|
||
const cells = [i + 1, p.code || '', p.name || '', p.unit || '',
|
||
p.qty != null ? p.qty : '', fmtMoney(p.unit_cost), fmtMoney(p.total)];
|
||
cells.forEach((c, ci) => {
|
||
const td = document.createElement('td');
|
||
td.textContent = c;
|
||
if (ci >= 4) td.className = 'num'; // числовые колонки — правое выравнивание/tabular
|
||
tr.appendChild(td);
|
||
});
|
||
if (p.unresolved) tr.classList.add('est-unresolved'); // подсветить нерассчитанную позицию
|
||
table.appendChild(tr);
|
||
});
|
||
scroll.appendChild(table);
|
||
panel.appendChild(scroll);
|
||
|
||
// Итоги — строго из data.totals (JS не пересчитывает)
|
||
const t = data.totals || {};
|
||
const rows = [
|
||
['Прямые затраты', t.grand_pz], ['Накладные расходы', t.grand_nr],
|
||
['Сметная прибыль', t.grand_sp], ['ИТОГО', t.grand_total],
|
||
['НДС', t.vat], ['Всего с НДС', t.total_with_vat],
|
||
].filter(r => r[1] != null);
|
||
if (rows.length) {
|
||
const tot = document.createElement('div');
|
||
tot.className = 'est-totals';
|
||
rows.forEach(([label, val]) => {
|
||
const row = document.createElement('div');
|
||
row.className = 'est-tot-row' + (label === 'ИТОГО' || label === 'Всего с НДС' ? ' est-tot-strong' : '');
|
||
const l = document.createElement('span'); l.textContent = label;
|
||
const v = document.createElement('span'); v.className = 'num'; v.textContent = fmtMoney(val) + ' ₽';
|
||
row.appendChild(l); row.appendChild(v); tot.appendChild(row);
|
||
});
|
||
panel.appendChild(tot);
|
||
}
|
||
|
||
// Предупреждения/нерасчитанное — честно, не прячем
|
||
if (data.ok === false || (data.warnings && data.warnings.length) || (data.missing && data.missing.length)) {
|
||
const warn = document.createElement('div');
|
||
warn.className = 'est-warn';
|
||
const items = [];
|
||
if (data.ok === false) items.push('⚠ Смета не полная: часть позиций не рассчитана — не подавать как готовую.');
|
||
(data.warnings || []).forEach(w => items.push(typeof w === 'string' ? w : (w.rule || JSON.stringify(w))));
|
||
(data.missing || []).forEach(m => items.push('Не рассчитано: ' + (m.code || '') + ' — ' + (m.reason || '')));
|
||
items.forEach(txt => { const d = document.createElement('div'); d.textContent = txt; warn.appendChild(d); });
|
||
panel.appendChild(warn);
|
||
}
|
||
|
||
// Скачать в Excel — настоящий .xlsx из таблицы позиций (итог в имени файла)
|
||
const acts = document.createElement('div');
|
||
acts.className = 'est-actions';
|
||
const dl = document.createElement('button');
|
||
dl.className = 'est-dl'; dl.type = 'button'; dl.textContent = '⬇ Скачать в Excel';
|
||
dl.onclick = () => {
|
||
const gt = (data.totals || {}).grand_total;
|
||
const title = (data.title || 'Смета') + (typeof gt === 'number' ? ' (итого ' + fmtMoney(gt) + ' руб)' : '');
|
||
tableToExcel(panel.querySelector('.est-table'), 'смета.xlsx', title);
|
||
};
|
||
acts.appendChild(dl);
|
||
panel.appendChild(acts);
|
||
|
||
const ob = document.getElementById('onboarding'); if (ob) ob.remove();
|
||
msgs.appendChild(panel);
|
||
scrollIfPinned();
|
||
return panel;
|
||
}
|
||
|
||
// --- Панель конъюнктурного анализа (срез 7): офферы таблицей + принятая цена ---
|
||
function addKaPanel(form) {
|
||
const panel = document.createElement('div');
|
||
panel.className = 'est-panel';
|
||
panel.setAttribute('role', 'region');
|
||
panel.setAttribute('aria-label', 'Конъюнктурный анализ');
|
||
const res = form.resource || {};
|
||
const head = document.createElement('div');
|
||
head.className = 'est-head';
|
||
head.textContent = 'КА: ' + (res.name || form.query || 'материал');
|
||
panel.appendChild(head);
|
||
if (res.code_tc) {
|
||
const sub = document.createElement('div');
|
||
sub.className = 'ka-sub';
|
||
sub.textContent = 'Код ТЦ: ' + res.code_tc;
|
||
panel.appendChild(sub);
|
||
}
|
||
const scroll = document.createElement('div');
|
||
scroll.className = 'est-scroll';
|
||
const table = document.createElement('table');
|
||
table.className = 'est-table';
|
||
const thead = document.createElement('tr');
|
||
['№', 'Поставщик', 'Цена с НДС', 'Без НДС', 'Перевозка', 'Заготовит.', 'Сметная', 'Регион', 'Год/кв'].forEach(h => {
|
||
const th = document.createElement('th'); th.textContent = h; thead.appendChild(th);
|
||
});
|
||
table.appendChild(thead);
|
||
(form.rows || []).forEach(r => {
|
||
const tr = document.createElement('tr');
|
||
// r — 20 граф по номерам; берём ключевые
|
||
const cells = [r[1], r[14], fmtMoney(r[5]), fmtMoney(r[6]), fmtMoney(r[7]), fmtMoney(r[8]),
|
||
fmtMoney(r[9]), r[18], (r[12] || '') + (r[13] ? ' / ' + r[13] : '')];
|
||
cells.forEach((c, ci) => {
|
||
const td = document.createElement('td');
|
||
td.textContent = c == null ? '' : c;
|
||
if (ci >= 2 && ci <= 6) td.className = 'num';
|
||
tr.appendChild(td);
|
||
});
|
||
if (r.is_winner) tr.classList.add('ka-winner');
|
||
table.appendChild(tr);
|
||
});
|
||
scroll.appendChild(table);
|
||
panel.appendChild(scroll);
|
||
|
||
const a = form.accepted || {};
|
||
if (a.winner != null || a.median != null) {
|
||
const tot = document.createElement('div');
|
||
tot.className = 'est-totals';
|
||
[['Принятая (мин.)', a.winner], ['Медиана', a.median], ['Макс.', a.max]].filter(x => x[1] != null).forEach(([l, v]) => {
|
||
const row = document.createElement('div');
|
||
row.className = 'est-tot-row' + (l.startsWith('Принятая') ? ' est-tot-strong' : '');
|
||
const ls = document.createElement('span'); ls.textContent = l;
|
||
const vs = document.createElement('span'); vs.className = 'num'; vs.textContent = fmtMoney(v) + ' ₽';
|
||
row.appendChild(ls); row.appendChild(vs); tot.appendChild(row);
|
||
});
|
||
panel.appendChild(tot);
|
||
}
|
||
if (form.warnings && form.warnings.length) {
|
||
const warn = document.createElement('div');
|
||
warn.className = 'est-warn';
|
||
form.warnings.forEach(w => { const d = document.createElement('div'); d.textContent = w; warn.appendChild(d); });
|
||
panel.appendChild(warn);
|
||
}
|
||
const acts = document.createElement('div');
|
||
acts.className = 'est-actions';
|
||
const dl = document.createElement('button');
|
||
dl.className = 'est-dl'; dl.type = 'button'; dl.textContent = '⬇ Скачать в Excel';
|
||
dl.onclick = () => tableToExcel(panel.querySelector('.est-table'), 'конъюнктурный_анализ.xlsx',
|
||
'КА: ' + ((form.resource || {}).name || form.query || 'материал'));
|
||
acts.appendChild(dl);
|
||
panel.appendChild(acts);
|
||
const ob = document.getElementById('onboarding'); if (ob) ob.remove();
|
||
msgs.appendChild(panel);
|
||
scrollIfPinned();
|
||
return panel;
|
||
}
|
||
|
||
// --- Session ---
|
||
async function newChat() {
|
||
// New tab = new session, old one stays in DB and in the sidebar
|
||
closeSidebar();
|
||
if (abortCtrl) { abortCtrl._silent = true; abortCtrl.abort(); } // не тащить хвост стрима в новый чат
|
||
tabId = genUUID();
|
||
localStorage.setItem('tabId', tabId);
|
||
msgs.innerHTML = '';
|
||
showOnboarding();
|
||
renderSessions();
|
||
document.getElementById('msg-input').focus();
|
||
}
|
||
|
||
function toggleSidebar() {
|
||
const sb = document.getElementById('sidebar');
|
||
const open = sb.classList.toggle('open');
|
||
document.getElementById('sidebar-backdrop').classList.toggle('show', open);
|
||
const t = document.getElementById('sidebar-toggle');
|
||
if (t) t.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||
}
|
||
function closeSidebar() {
|
||
document.getElementById('sidebar').classList.remove('open');
|
||
document.getElementById('sidebar-backdrop').classList.remove('show');
|
||
const t = document.getElementById('sidebar-toggle');
|
||
if (t) t.setAttribute('aria-expanded', 'false');
|
||
}
|
||
|
||
function downloadWorkFile(name) {
|
||
fetch(API + '/api/files/' + encodeURIComponent(name), {headers: authHeaders()})
|
||
.then(r => { if (!r.ok) throw new Error(r.status); return r.blob(); })
|
||
.then(b => {
|
||
const u = URL.createObjectURL(b);
|
||
const l = document.createElement('a');
|
||
l.href = u; l.download = name; l.click();
|
||
// Немедленный revoke в Firefox может оборвать ещё не начавшееся скачивание
|
||
setTimeout(() => URL.revokeObjectURL(u), 30000);
|
||
})
|
||
.catch(err => addMsg('error', 'Не удалось скачать «' + name + '» (ошибка ' + err.message + '). Обновите страницу и попробуйте ещё раз.'));
|
||
}
|
||
|
||
function fmtSize(size) {
|
||
return size >= 1048576 ? (size / 1048576).toFixed(1) + ' МБ' : (size / 1024).toFixed(1) + ' КБ';
|
||
}
|
||
|
||
// Message with download buttons for files the agent prepared. files: [{name, size}]
|
||
function addFilesMsg(files, ts, title) {
|
||
const div = addMsg('file', title || 'Готовые файлы:', ts);
|
||
const copyBtn = div.querySelector('.copy-btn'); // кнопки файлов — над «Копировать»
|
||
files.forEach(f => {
|
||
const a = document.createElement('a');
|
||
a.className = 'dl-btn';
|
||
a.textContent = '⬇ ' + f.name + ' (' + fmtSize(f.size) + ')';
|
||
a.href = API + '/api/files/' + encodeURIComponent(f.name);
|
||
a.onclick = e => { e.preventDefault(); downloadWorkFile(f.name); };
|
||
div.insertBefore(a, copyBtn);
|
||
});
|
||
return div;
|
||
}
|
||
|
||
async function listFiles() {
|
||
const r = await fetch(API + '/api/files', {headers: authHeaders()});
|
||
if (!r.ok) return;
|
||
const files = await r.json();
|
||
if (files.length === 0) { addMsg('system', 'Файлов нет.'); return; }
|
||
addFilesMsg(files, null, 'Файлы в рабочей директории:');
|
||
}
|
||
|
||
// --- History ---
|
||
async function loadHistory() {
|
||
try {
|
||
const r = await fetch(API + '/api/history', {headers: authHeaders()});
|
||
if (!r.ok) { if (!msgs.children.length) showOnboarding(); return; }
|
||
const history = await r.json();
|
||
if (history.length === 0) { showOnboarding(); return; }
|
||
msgs.innerHTML = '';
|
||
for (const m of history) {
|
||
if (m.role === 'user') addMsg('user', m.content, m.timestamp);
|
||
else if (m.role === 'assistant') addMsg('ai', m.content, m.timestamp);
|
||
else if (m.role === 'system') addMsg('system', m.content, m.timestamp);
|
||
else if (m.role === 'files') {
|
||
try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {}
|
||
}
|
||
else if (m.role === 'estimate') {
|
||
try { addEstimatePanel(JSON.parse(m.content)); } catch {}
|
||
}
|
||
else if (m.role === 'ka_form') {
|
||
try { addKaPanel(JSON.parse(m.content)); } catch {}
|
||
}
|
||
}
|
||
} catch { if (!msgs.children.length) showOnboarding(); }
|
||
}
|
||
|
||
// --- Chat sidebar (Claude-desktop style left panel) ---
|
||
let allSessions = [];
|
||
async function loadSessions() {
|
||
try {
|
||
const r = await fetch(API + '/api/sessions', {headers: authHeaders()});
|
||
if (!r.ok) return;
|
||
allSessions = await r.json();
|
||
renderSessions();
|
||
} catch {}
|
||
}
|
||
function renderSessions() {
|
||
const list = document.getElementById('chat-list');
|
||
if (!list) return;
|
||
// Идёт инлайн-переименование — не перерисовывать (innerHTML='' снёс бы фокусированный
|
||
// input без blur → набранный текст пропал бы молча). Fable Ф3.
|
||
if (list.querySelector('.ci-rename')) return;
|
||
const q = (document.getElementById('chat-search')?.value || '').trim().toLowerCase();
|
||
const match = s => !q || (((s.title || '') + ' ' + (s.last_question || '')).toLowerCase().includes(q));
|
||
list.innerHTML = '';
|
||
// Текущий ещё не сохранённый диалог (без сообщений) — показываем сверху активным (не при поиске)
|
||
if (!q && !allSessions.some(s => s.tab_id === tabId)) {
|
||
list.appendChild(makeChatItem({tab_id: tabId, last_question: 'Новый чат', last_ts: null}, true));
|
||
}
|
||
for (const s of allSessions) if (match(s)) list.appendChild(makeChatItem(s, s.tab_id === tabId));
|
||
if (!list.children.length) list.innerHTML = '<div class="chat-list-empty">' + (q ? 'Ничего не найдено' : 'Пока нет чатов') + '</div>';
|
||
}
|
||
function makeChatItem(s, active) {
|
||
const div = document.createElement('div');
|
||
div.className = 'chat-item' + (active ? ' active' : '');
|
||
const label = (s.title || s.last_question || 'Без названия').slice(0, 90) || 'Новый чат';
|
||
div.onclick = () => switchChat(s.tab_id);
|
||
// Клавиатурная доступность (Fable Ф2): строка списка операбельна с клавиатуры.
|
||
// role не button (внутри вложенные кнопки ✎/✕) — фокусируемый элемент с именем.
|
||
div.tabIndex = 0;
|
||
div.setAttribute('aria-label', 'Открыть диалог: ' + label);
|
||
div.onkeydown = e => {
|
||
if ((e.key === 'Enter' || e.key === ' ') && e.target === div) { e.preventDefault(); switchChat(s.tab_id); }
|
||
};
|
||
const t = document.createElement('div');
|
||
t.className = 'ci-title';
|
||
t.textContent = label;
|
||
div.appendChild(t);
|
||
if (s.last_ts) {
|
||
const d = document.createElement('div');
|
||
d.className = 'ci-date';
|
||
d.textContent = new Date(s.last_ts * 1000).toLocaleString('ru-RU',
|
||
{day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'});
|
||
div.appendChild(d);
|
||
// Действия (переименовать/удалить) — только для сохранённых диалогов
|
||
const acts = document.createElement('div');
|
||
acts.className = 'ci-actions';
|
||
const ren = document.createElement('button');
|
||
ren.className = 'ci-act'; ren.title = 'Переименовать'; ren.setAttribute('aria-label', 'Переименовать диалог'); ren.textContent = '✎';
|
||
ren.onclick = e => { e.stopPropagation(); startRename(div, t, s); };
|
||
const del = document.createElement('button');
|
||
del.className = 'ci-act'; del.title = 'Удалить'; del.setAttribute('aria-label', 'Удалить диалог'); del.textContent = '✕';
|
||
del.onclick = e => { e.stopPropagation(); deleteChat(s); };
|
||
acts.appendChild(ren); acts.appendChild(del);
|
||
div.appendChild(acts);
|
||
}
|
||
return div;
|
||
}
|
||
// Инлайн-переименование: заголовок → поле ввода, Enter/blur сохраняют, Esc отменяет.
|
||
function startRename(div, titleEl, s) {
|
||
if (div.querySelector('.ci-rename')) return;
|
||
const input = document.createElement('input');
|
||
input.className = 'ci-rename'; input.type = 'text';
|
||
input.value = s.title || s.last_question || '';
|
||
input.onclick = e => e.stopPropagation();
|
||
let done = false;
|
||
const finish = async (save) => {
|
||
if (done) return; done = true;
|
||
const val = input.value.trim();
|
||
if (input.isConnected) input.replaceWith(titleEl);
|
||
if (save && val && val !== (s.title || '')) {
|
||
try {
|
||
const r = await authFetch('/api/sessions/' + encodeURIComponent(s.tab_id) + '/title', {
|
||
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({title: val})});
|
||
if (r.ok) { s.title = val; titleEl.textContent = val.slice(0, 90); }
|
||
} catch (e) {}
|
||
}
|
||
};
|
||
input.onkeydown = e => {
|
||
e.stopPropagation();
|
||
if (e.key === 'Enter') { e.preventDefault(); finish(true); }
|
||
else if (e.key === 'Escape') { e.preventDefault(); finish(false); }
|
||
};
|
||
input.onblur = () => finish(true);
|
||
titleEl.replaceWith(input);
|
||
input.focus(); input.select();
|
||
}
|
||
async function deleteChat(s) {
|
||
if (!confirm('Удалить диалог целиком? Это действие необратимо.')) return;
|
||
// Прерываем стрим ДО удаления: иначе финальный ответ агента допишется в БД и
|
||
// «удалённый навсегда» чат воскреснет (Fable Ф3).
|
||
if (s.tab_id === tabId && abortCtrl) { abortCtrl._silent = true; abortCtrl.abort(); }
|
||
try {
|
||
const r = await authFetch('/api/sessions/' + encodeURIComponent(s.tab_id), {method: 'DELETE'});
|
||
if (!r.ok) return;
|
||
if (s.tab_id === tabId) newChat(); // удалили текущий — открыть новый
|
||
await loadSessions();
|
||
} catch (e) {}
|
||
}
|
||
async function switchChat(id) {
|
||
closeSidebar();
|
||
if (id === tabId) return;
|
||
if (abortCtrl) { abortCtrl._silent = true; abortCtrl.abort(); } // не тащить хвост стрима в другой чат
|
||
tabId = id;
|
||
localStorage.setItem('tabId', tabId);
|
||
msgs.innerHTML = '';
|
||
await loadHistory();
|
||
renderSessions();
|
||
}
|
||
|
||
// Auto-resize textarea + скрыть быстрые действия, когда пользователь начал печатать
|
||
document.getElementById('msg-input').addEventListener('input', function() {
|
||
this.style.height = 'auto';
|
||
this.style.height = Math.min(this.scrollHeight, 150) + 'px';
|
||
const qa = document.getElementById('quick-actions');
|
||
if (qa) qa.classList.toggle('hide', this.value.trim().length > 0);
|
||
});
|
||
// Быстрые действия: клик подставляет заготовку в поле (не отправляет — можно дополнить)
|
||
document.querySelectorAll('#quick-actions .qa-chip').forEach(c => {
|
||
c.onclick = () => {
|
||
const inp = document.getElementById('msg-input');
|
||
inp.value = c.dataset.q;
|
||
inp.focus();
|
||
inp.dispatchEvent(new Event('input'));
|
||
// курсор в конец (для «КА по материалу: » — дописать название)
|
||
inp.setSelectionRange(inp.value.length, inp.value.length);
|
||
};
|
||
});
|
||
</script>
|
||
</body>
|
||
</html>
|