|
|
@@ -0,0 +1,4756 @@
|
|
|
+<!doctype html>
|
|
|
+<html lang="zh-CN">
|
|
|
+<head>
|
|
|
+ <meta charset="utf-8" />
|
|
|
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
|
+ <meta name="description" content="FitHealthAgent — 智能健身健康管理助手,支持 Garmin .fit 文件解析与训练纠错" />
|
|
|
+ <title>FitHealthAgent · 智能健康助手</title>
|
|
|
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
|
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
|
|
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
|
|
+ <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
|
|
|
+ <style>
|
|
|
+ /* ── 设计 tokens ─────────────────────────────────────────────────────── */
|
|
|
+ :root {
|
|
|
+ --bg: #0d1117;
|
|
|
+ --surface: #161b22;
|
|
|
+ --surface2: #21262d;
|
|
|
+ --surface3: #2d333b;
|
|
|
+ --border: #30363d;
|
|
|
+ --accent: #58a6ff;
|
|
|
+ --accent-dim: rgba(88,166,255,.12);
|
|
|
+ --green: #3fb950;
|
|
|
+ --green-dim: rgba(63,185,80,.12);
|
|
|
+ --red: #f85149;
|
|
|
+ --red-dim: rgba(248,81,73,.12);
|
|
|
+ --yellow: #e3b341;
|
|
|
+ --yellow-dim: rgba(227,179,65,.10);
|
|
|
+ --purple: #a371f7;
|
|
|
+ --purple-dim: rgba(163,113,247,.12);
|
|
|
+ --text: #e6edf3;
|
|
|
+ --text-muted: #7d8590;
|
|
|
+ --text-dim: #484f58;
|
|
|
+ --radius: 12px;
|
|
|
+ --radius-sm: 8px;
|
|
|
+ --shadow: 0 8px 32px rgba(0,0,0,.45);
|
|
|
+ }
|
|
|
+
|
|
|
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
|
+ html { scroll-behavior: smooth; }
|
|
|
+
|
|
|
+ body {
|
|
|
+ font-family: 'Inter', system-ui, sans-serif;
|
|
|
+ background: var(--bg);
|
|
|
+ color: var(--text);
|
|
|
+ min-height: 100vh;
|
|
|
+ display: grid;
|
|
|
+ grid-template-columns: 1fr minmax(0,1600px) 1fr;
|
|
|
+ grid-template-rows: auto 1fr;
|
|
|
+ padding: 24px 16px 40px;
|
|
|
+ gap: 0 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── Header ─────────────────────────────────────────────────────────── */
|
|
|
+ header {
|
|
|
+ grid-column: 2;
|
|
|
+ display: flex;
|
|
|
+ align-items: center;
|
|
|
+ justify-content: space-between;
|
|
|
+ margin-bottom: 20px;
|
|
|
+ }
|
|
|
+ .logo { display: flex; align-items: center; gap: 10px; }
|
|
|
+ .logo-icon {
|
|
|
+ width: 38px; height: 38px;
|
|
|
+ background: linear-gradient(135deg, #58a6ff, #3fb950);
|
|
|
+ border-radius: 10px;
|
|
|
+ display: flex; align-items: center; justify-content: center;
|
|
|
+ font-size: 20px;
|
|
|
+ }
|
|
|
+ .logo-text h1 {
|
|
|
+ font-size: 1.2rem; font-weight: 700;
|
|
|
+ background: linear-gradient(90deg, var(--accent), var(--green));
|
|
|
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
|
|
+ background-clip: text;
|
|
|
+ }
|
|
|
+ .logo-text span {
|
|
|
+ font-size: .72rem; color: var(--text-muted);
|
|
|
+ display: block; -webkit-text-fill-color: var(--text-muted);
|
|
|
+ }
|
|
|
+ .header-actions { display:flex; align-items:center; gap:8px; }
|
|
|
+ #btn-data {
|
|
|
+ width:38px; height:38px; border:1px solid var(--border); border-radius:var(--radius-sm);
|
|
|
+ background:var(--surface); color:var(--text-muted); cursor:pointer; font-size:1rem;
|
|
|
+ }
|
|
|
+ #btn-data:hover { color:var(--accent); border-color:var(--accent); }
|
|
|
+ #btn-overview {
|
|
|
+ height:38px; padding:0 11px; border:1px solid var(--border); border-radius:var(--radius-sm);
|
|
|
+ background:var(--surface); color:var(--text-muted); cursor:pointer; font:inherit; font-size:.78rem;
|
|
|
+ }
|
|
|
+ #btn-overview:hover { color:var(--green); border-color:var(--green); }
|
|
|
+ #btn-checkin { height:38px; padding:0 11px; border:1px solid var(--border); border-radius:var(--radius-sm); background:var(--surface); color:var(--text-muted); cursor:pointer; font:inherit; font-size:.78rem; }
|
|
|
+ #btn-checkin:hover { color:var(--accent); border-color:var(--accent); }
|
|
|
+
|
|
|
+ #btn-logout {
|
|
|
+ display: flex; align-items: center; gap: 6px;
|
|
|
+ padding: 8px 14px;
|
|
|
+ background: var(--red-dim);
|
|
|
+ border: 1px solid rgba(248,81,73,.3);
|
|
|
+ border-radius: var(--radius-sm);
|
|
|
+ color: var(--red); font-family: inherit; font-size: .85rem; font-weight: 600;
|
|
|
+ cursor: pointer;
|
|
|
+ transition: background .2s, border-color .2s, transform .15s;
|
|
|
+ }
|
|
|
+ #btn-logout:hover:not(:disabled) { background: rgba(248,81,73,.22); transform: translateY(-1px); }
|
|
|
+ #btn-logout:disabled { opacity: .5; cursor: not-allowed; }
|
|
|
+ #btn-logout .spin { display:none; width:13px; height:13px; border:2px solid rgba(248,81,73,.3); border-top-color:var(--red); border-radius:50%; animation:spin .7s linear infinite; }
|
|
|
+ #btn-logout.loading .spin { display:block; }
|
|
|
+ #btn-logout.loading .icon { display:none; }
|
|
|
+ #btn-logout.loading .lbl { display:none; }
|
|
|
+ #btn-logout.loading::after { content:"分析中…"; font-size:.85rem; }
|
|
|
+
|
|
|
+ .modal-backdrop { display:none; position:fixed; inset:0; z-index:1000; background:rgba(0,0,0,.72); padding:24px; align-items:center; justify-content:center; }
|
|
|
+ .modal-backdrop.show { display:flex; }
|
|
|
+ .data-modal { width:min(760px,100%); max-height:min(820px,calc(100vh - 48px)); display:flex; flex-direction:column; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; }
|
|
|
+ .modal-header { display:flex; align-items:center; padding:14px 16px; border-bottom:1px solid var(--border); }
|
|
|
+ .modal-header h2 { flex:1; font-size:1rem; }
|
|
|
+ .modal-close { width:32px; height:32px; border:0; background:transparent; color:var(--text-muted); cursor:pointer; font-size:1.25rem; }
|
|
|
+ .modal-close:hover { color:var(--text); }
|
|
|
+ .modal-body { overflow-y:auto; padding:0 16px 18px; }
|
|
|
+ .data-section { padding:16px 0; border-bottom:1px solid var(--border); }
|
|
|
+ .data-section:last-child { border-bottom:0; }
|
|
|
+ .section-heading { display:flex; align-items:center; gap:8px; margin-bottom:10px; }
|
|
|
+ .section-heading h3 { flex:1; font-size:.85rem; color:var(--text); }
|
|
|
+ .section-count { color:var(--text-muted); font-size:.72rem; }
|
|
|
+ .data-collapsible > summary { min-height:32px; margin-bottom:0; list-style:none; cursor:pointer; user-select:none; }
|
|
|
+ .data-collapsible > summary::-webkit-details-marker { display:none; }
|
|
|
+ .data-collapsible > summary::after { content:"›"; width:24px; flex:0 0 24px; color:var(--text-muted); font-size:1.15rem; line-height:1; text-align:center; transform:rotate(0deg); transition:transform .16s ease,color .16s ease; }
|
|
|
+ .data-collapsible[open] > summary { margin-bottom:10px; }
|
|
|
+ .data-collapsible[open] > summary::after { transform:rotate(90deg); }
|
|
|
+ .data-collapsible > summary:hover::after { color:var(--accent); }
|
|
|
+ .data-collapsible > summary:focus-visible { outline:2px solid var(--accent); outline-offset:3px; border-radius:4px; }
|
|
|
+ .data-list { display:flex; flex-direction:column; gap:6px; max-height:240px; overflow-y:auto; }
|
|
|
+ .data-row { display:flex; align-items:flex-start; gap:9px; padding:9px 10px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); }
|
|
|
+ .data-row input[type="checkbox"] { margin-top:3px; accent-color:var(--accent); }
|
|
|
+ .data-row-main { flex:1; min-width:0; }
|
|
|
+ .data-row-title { font-size:.8rem; color:var(--text); word-break:break-word; }
|
|
|
+ .data-row-meta { margin-top:3px; font-size:.68rem; color:var(--text-muted); }
|
|
|
+ .data-empty { padding:14px; text-align:center; color:var(--text-dim); font-size:.76rem; border:1px dashed var(--border); border-radius:6px; }
|
|
|
+ .small-delete { border:0; background:transparent; color:var(--text-muted); cursor:pointer; font-size:.75rem; }
|
|
|
+ .small-delete:hover { color:var(--red); }
|
|
|
+ .memory-fact-row { display:flex; gap:8px; align-items:center; padding:6px 0; border-top:1px solid var(--border); }
|
|
|
+ .memory-fact-row > div:first-child { flex:1; min-width:0; word-break:break-word; }
|
|
|
+ .memory-fact-row .plan-row-actions { flex:0 0 auto; display:flex; gap:6px; }
|
|
|
+ .memory-fact-input { min-width:180px; height:auto; min-height:30px; resize:vertical; }
|
|
|
+ .data-actions { display:flex; flex-wrap:wrap; gap:8px; }
|
|
|
+ .data-action { height:34px; padding:0 11px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text); font:inherit; font-size:.75rem; cursor:pointer; }
|
|
|
+ .data-action:hover:not(:disabled) { border-color:var(--accent); }
|
|
|
+ .data-action.danger { color:var(--red); border-color:rgba(248,81,73,.35); }
|
|
|
+ .data-action:disabled { opacity:.45; cursor:not-allowed; }
|
|
|
+ .profile-summary { margin-bottom:10px; color:var(--text-muted); font-size:.76rem; line-height:1.6; }
|
|
|
+ .reset-confirm { display:flex; gap:8px; margin-top:10px; }
|
|
|
+ .reset-confirm input { flex:1; min-width:0; height:34px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text); padding:0 9px; font:inherit; font-size:.76rem; }
|
|
|
+ .modal-status { min-height:20px; margin-top:10px; font-size:.74rem; color:var(--text-muted); }
|
|
|
+ .modal-status.error { color:var(--red); }
|
|
|
+ .modal-status.success { color:var(--green); }
|
|
|
+ .privacy-setting { padding:11px; border:1px solid var(--border); border-radius:7px; background:var(--surface2); }
|
|
|
+ .privacy-setting-head { display:flex; align-items:flex-start; gap:10px; }
|
|
|
+ .privacy-setting-copy { flex:1; min-width:0; }
|
|
|
+ .privacy-setting-copy strong { display:block; font-size:.8rem; color:var(--text); }
|
|
|
+ .privacy-setting-copy p { margin-top:4px; color:var(--text-muted); font-size:.7rem; line-height:1.5; }
|
|
|
+ .privacy-toggle { display:flex; align-items:center; gap:6px; color:var(--text-muted); font-size:.72rem; white-space:nowrap; cursor:pointer; }
|
|
|
+ .privacy-toggle input { accent-color:var(--accent); }
|
|
|
+ .privacy-status { margin-top:9px; color:var(--green); font-size:.72rem; line-height:1.5; }
|
|
|
+ .privacy-status.disabled { color:var(--yellow); }
|
|
|
+ .privacy-disclosure { display:flex; flex-direction:column; gap:6px; margin-top:10px; }
|
|
|
+ .privacy-disclosure-item { padding:8px; border-left:2px solid var(--border); color:var(--text-muted); font-size:.7rem; line-height:1.5; }
|
|
|
+ .privacy-disclosure-item strong { color:var(--text); }
|
|
|
+ .privacy-local { margin-top:10px; color:var(--text-muted); font-size:.7rem; line-height:1.5; }
|
|
|
+
|
|
|
+ .health-modal { width:min(820px,100%); max-height:min(820px,calc(100vh - 48px)); display:flex; flex-direction:column; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; }
|
|
|
+ .overview-controls { display:flex; align-items:center; gap:8px; padding:12px 16px; border-bottom:1px solid var(--border); }
|
|
|
+ .overview-date { flex:1; min-width:0; height:34px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text); padding:0 8px; font:inherit; font-size:.8rem; }
|
|
|
+ .overview-nav { width:34px; height:34px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text-muted); cursor:pointer; font-size:1rem; }
|
|
|
+ .overview-nav:hover { color:var(--accent); border-color:var(--accent); }
|
|
|
+ .overview-body { overflow-y:auto; padding:16px; }
|
|
|
+ .overview-status { min-height:20px; margin-bottom:12px; color:var(--text-muted); font-size:.75rem; }
|
|
|
+ .overview-status.empty { color:var(--yellow); }
|
|
|
+ .overview-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
|
|
|
+ .overview-card { min-height:128px; padding:13px; border:1px solid var(--border); border-radius:var(--radius-sm); background:var(--surface2); }
|
|
|
+ .overview-card h3 { margin-bottom:10px; color:var(--text-muted); font-size:.76rem; font-weight:600; }
|
|
|
+ .overview-value { margin-bottom:8px; color:var(--text); font-size:1.35rem; font-weight:700; }
|
|
|
+ .overview-value small { color:var(--text-muted); font-size:.7rem; font-weight:500; }
|
|
|
+ .overview-details { display:flex; flex-wrap:wrap; gap:5px 10px; color:var(--text-muted); font-size:.72rem; line-height:1.5; }
|
|
|
+ .overview-detail-good { color:var(--green); }
|
|
|
+ .overview-detail-warn { color:var(--yellow); }
|
|
|
+ .checkin-modal { width:min(680px,100%); max-height:min(820px,calc(100vh - 48px)); display:flex; flex-direction:column; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; }
|
|
|
+ .checkin-form { overflow-y:auto; padding:16px; }
|
|
|
+ .checkin-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
|
|
|
+ .checkin-field { display:flex; flex-direction:column; gap:5px; }
|
|
|
+ .checkin-field.full { grid-column:1 / -1; }
|
|
|
+ .checkin-field label { color:var(--text-muted); font-size:.72rem; }
|
|
|
+ .checkin-field input, .checkin-field textarea { width:100%; min-height:34px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text); padding:7px 8px; font:inherit; font-size:.78rem; outline:none; }
|
|
|
+ .checkin-field textarea { min-height:76px; resize:vertical; }
|
|
|
+ .checkin-field input:focus, .checkin-field textarea:focus { border-color:var(--accent); }
|
|
|
+ .checkin-section { grid-column:1 / -1; margin-top:4px; padding-top:10px; border-top:1px solid var(--border); color:var(--text); font-size:.8rem; font-weight:600; }
|
|
|
+ .checkin-hint { grid-column:1 / -1; display:none; color:var(--accent); font-size:.72rem; line-height:1.5; }
|
|
|
+ .checkin-hint.show { display:block; }
|
|
|
+ .checkin-date-row { grid-column:1 / -1; display:grid; grid-template-columns:minmax(180px,1fr) auto; gap:8px; align-items:end; }
|
|
|
+ .checkin-date-row .checkin-field { min-width:0; }
|
|
|
+ .checkin-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:14px; }
|
|
|
+ .meal-estimates { grid-column:1 / -1; display:grid; gap:10px; }
|
|
|
+ .meal-estimate { border:1px solid var(--border); background:var(--surface2); padding:10px; border-radius:6px; }
|
|
|
+ .meal-estimate-head { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:8px; font-size:.78rem; }
|
|
|
+ .meal-estimate-meta { color:var(--text-muted); font-size:.7rem; line-height:1.5; margin:6px 0; }
|
|
|
+ .meal-item-grid { display:grid; grid-template-columns:1.3fr 1fr repeat(4,minmax(66px,.7fr)); gap:6px; margin-top:6px; }
|
|
|
+ .meal-item-header { color:var(--text-muted); font-size:.66rem; line-height:1.25; }
|
|
|
+ .meal-item-header span { min-width:0; padding:0 6px; }
|
|
|
+ .meal-item-grid input { min-width:0; min-height:32px; border:1px solid var(--border); border-radius:5px; background:var(--surface); color:var(--text); padding:5px 6px; font:inherit; font-size:.72rem; }
|
|
|
+ .meal-confirm { display:flex; align-items:center; gap:6px; color:var(--yellow); font-size:.72rem; margin-top:8px; }
|
|
|
+ .meal-estimate-summary { color:var(--accent); font-size:.74rem; margin-top:8px; }
|
|
|
+ .plan-save-panel { margin-top:10px; padding:10px; border:1px solid rgba(63,185,80,.3); border-radius:6px; background:var(--green-dim); }
|
|
|
+ .plan-save-grid { display:grid; grid-template-columns:130px minmax(130px,1fr) minmax(160px,1.5fr); gap:7px; }
|
|
|
+ .plan-save-field { display:flex; flex-direction:column; gap:3px; }
|
|
|
+ .plan-save-field label { color:var(--text-muted); font-size:.65rem; }
|
|
|
+ .plan-save-field input, .plan-save-field textarea { width:100%; border:1px solid var(--border); border-radius:5px; background:var(--surface); color:var(--text); padding:7px; font:inherit; font-size:.72rem; }
|
|
|
+ .plan-save-field input { height:32px; padding:0 7px; }
|
|
|
+ .plan-save-field textarea { min-height:62px; resize:vertical; }
|
|
|
+ .plan-save-field.full { grid-column:1 / -1; }
|
|
|
+ .plan-save-actions { display:flex; align-items:center; gap:7px; margin-top:8px; }
|
|
|
+ .plan-save-result { flex:1; font-size:.7rem; color:var(--text-muted); }
|
|
|
+ .profile-update-panel { margin-top:10px; padding:10px; border:1px solid rgba(227,179,65,.4); border-radius:6px; background:var(--yellow-dim); }
|
|
|
+ .profile-update-panel strong { display:block; font-size:.78rem; color:var(--yellow); }
|
|
|
+ .profile-update-list { margin:7px 0; color:var(--text-muted); font-size:.74rem; line-height:1.65; }
|
|
|
+ .profile-update-actions { display:flex; align-items:center; gap:7px; }
|
|
|
+ .profile-update-actions button { height:32px; padding:0 10px; border:1px solid var(--border); border-radius:5px; background:var(--surface); color:var(--text); font:inherit; font-size:.72rem; cursor:pointer; }
|
|
|
+ .profile-update-actions button.confirm { border-color:rgba(63,185,80,.5); color:var(--green); }
|
|
|
+ .profile-update-actions button.cancel { color:var(--text-muted); }
|
|
|
+ .profile-update-result { color:var(--text-muted); font-size:.7rem; }
|
|
|
+ .plan-row-actions { display:flex; gap:8px; flex-wrap:wrap; justify-content:flex-end; }
|
|
|
+ .plan-preview { display:none; margin-top:10px; border:1px solid var(--border); border-radius:6px; overflow:hidden; }
|
|
|
+ .plan-preview.show { display:block; }
|
|
|
+ .plan-preview-header { display:flex; align-items:center; gap:8px; padding:8px 10px; background:var(--surface2); border-bottom:1px solid var(--border); }
|
|
|
+ .plan-preview-header strong { flex:1; font-size:.76rem; }
|
|
|
+ .plan-preview-body { max-height:420px; overflow:auto; padding:14px; background:var(--surface); font-size:.78rem; line-height:1.65; }
|
|
|
+ .plan-preview-body h1,.plan-preview-body h2,.plan-preview-body h3 { margin:12px 0 7px; }
|
|
|
+ .plan-preview-body ul,.plan-preview-body ol { margin-left:20px; }
|
|
|
+ .record-preview { display:none; margin-top:10px; border:1px solid var(--border); border-radius:6px; overflow:hidden; }
|
|
|
+ .record-preview.show { display:block; }
|
|
|
+ .record-preview-header { display:flex; align-items:center; gap:8px; padding:8px 10px; background:var(--surface2); border-bottom:1px solid var(--border); }
|
|
|
+ .record-preview-header strong { flex:1; font-size:.76rem; }
|
|
|
+ .record-preview-body { max-height:420px; overflow:auto; padding:14px; background:var(--surface); color:var(--text); font-size:.78rem; line-height:1.65; white-space:pre-wrap; }
|
|
|
+
|
|
|
+ /* ── Main layout: chat + sidebar ────────────────────────────────────── */
|
|
|
+ .main-grid {
|
|
|
+ grid-column: 2;
|
|
|
+ --chat-width: 820px;
|
|
|
+ --workout-width: 420px;
|
|
|
+ display: grid;
|
|
|
+ grid-template-columns: minmax(420px, var(--chat-width)) 10px minmax(340px, var(--workout-width));
|
|
|
+ grid-template-rows: minmax(0, 1fr);
|
|
|
+ gap: 0;
|
|
|
+ min-height: 0;
|
|
|
+ height: calc(100vh - 124px);
|
|
|
+ justify-content: center;
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── Chat panel ─────────────────────────────────────────────────────── */
|
|
|
+ .chat-panel {
|
|
|
+ grid-column: 1;
|
|
|
+ grid-row: 1;
|
|
|
+ background: var(--surface);
|
|
|
+ border: 1px solid var(--border);
|
|
|
+ border-radius: var(--radius);
|
|
|
+ box-shadow: var(--shadow);
|
|
|
+ display: flex; flex-direction: column;
|
|
|
+ overflow: hidden;
|
|
|
+ }
|
|
|
+ .chat-drop-overlay { display:none; position:absolute; inset:0; z-index:8; align-items:center; justify-content:center; padding:24px; background:rgba(13,17,23,.88); border:2px dashed var(--accent); border-radius:var(--radius); pointer-events:none; }
|
|
|
+ .chat-panel { position:relative; }
|
|
|
+ .chat-panel.dragging .chat-drop-overlay { display:flex; }
|
|
|
+ .chat-drop-message { width:min(420px,100%); padding:24px; border:1px solid rgba(88,166,255,.45); border-radius:var(--radius); background:var(--surface2); color:var(--text); text-align:center; box-shadow:var(--shadow); }
|
|
|
+ .chat-drop-message strong { display:block; margin-bottom:8px; color:var(--accent); font-size:1rem; }
|
|
|
+ .chat-drop-message span { color:var(--text-muted); font-size:.78rem; line-height:1.6; }
|
|
|
+
|
|
|
+ #chat {
|
|
|
+ flex: 1;
|
|
|
+ min-height: 0;
|
|
|
+ overflow-y: auto;
|
|
|
+ padding: 20px;
|
|
|
+ display: flex; flex-direction: column; gap: 10px;
|
|
|
+ scroll-behavior: smooth;
|
|
|
+ }
|
|
|
+ #chat::-webkit-scrollbar { width: 4px; }
|
|
|
+ #chat::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
|
|
|
+
|
|
|
+ .msg { max-width: 82%; padding: 10px 14px; border-radius: var(--radius-sm); font-size:.875rem; line-height:1.65; white-space:pre-wrap; word-break:break-word; animation:fadeUp .22s ease; }
|
|
|
+ @keyframes fadeUp { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }
|
|
|
+ .msg.user { align-self:flex-end; background:var(--accent-dim); border:1px solid rgba(88,166,255,.22); }
|
|
|
+ .msg.bot { align-self:flex-start; background:var(--surface2); border:1px solid var(--border); white-space:normal; }
|
|
|
+
|
|
|
+ /* Markdown Styles for bot messages */
|
|
|
+ .msg.bot p { margin-bottom: 8px; }
|
|
|
+ .msg.bot p:last-child { margin-bottom: 0; }
|
|
|
+ .msg.bot a { color: var(--accent); text-decoration: none; }
|
|
|
+ .msg.bot a:hover { text-decoration: underline; }
|
|
|
+ .msg.bot h1, .msg.bot h2, .msg.bot h3, .msg.bot h4 { margin-top: 12px; margin-bottom: 8px; font-weight: 600; color: var(--text); }
|
|
|
+ .msg.bot ul, .msg.bot ol { margin-left: 20px; margin-bottom: 8px; }
|
|
|
+ .msg.bot strong { color: #fff; }
|
|
|
+ .msg.bot pre, .msg.bot code { font-family: monospace; background: var(--surface3); padding: 2px 4px; border-radius: 4px; font-size: .8rem; }
|
|
|
+ .msg.bot pre { padding: 10px; overflow-x: auto; margin-bottom: 8px; }
|
|
|
+ .msg.bot pre code { padding: 0; background: transparent; }
|
|
|
+
|
|
|
+ .msg-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:6px; }
|
|
|
+ .msg .role { font-size:.7rem; font-weight:600; color:var(--text-muted); }
|
|
|
+ .msg.user .role { color:var(--accent); }
|
|
|
+ .msg.bot .role { color:var(--green); }
|
|
|
+
|
|
|
+ .btn-download {
|
|
|
+ background: transparent; border: 1px solid var(--border); color: var(--text-muted);
|
|
|
+ border-radius: 4px; padding: 2px 6px; font-size: 0.65rem; cursor: pointer;
|
|
|
+ transition: all 0.2s; display: flex; align-items: center; gap: 4px;
|
|
|
+ }
|
|
|
+ .btn-download:hover { background: var(--surface3); color: var(--accent); border-color: var(--accent); }
|
|
|
+
|
|
|
+ .msg.system { align-self:center; max-width:92%; background:transparent; border:1px solid var(--border); border-radius:var(--radius-sm); font-size:.8rem; color:var(--text-muted); text-align:center; padding:8px 16px; }
|
|
|
+ .msg.notify-saved { border-color:rgba(63,185,80,.4); color:var(--green); background:var(--green-dim); }
|
|
|
+ .msg.notify-skipped { border-color:rgba(88,166,255,.3); color:var(--accent); background:var(--accent-dim); }
|
|
|
+ .msg.notify-error { border-color:rgba(248,81,73,.4); color:var(--red); background:var(--red-dim); }
|
|
|
+
|
|
|
+ /* summary block inside notify */
|
|
|
+ .summary-block { margin-top:8px; padding:8px 10px; background:rgba(63,185,80,.08); border:1px solid rgba(63,185,80,.2); border-radius:6px; font-size:.78rem; color:var(--text); text-align:left; white-space:pre-wrap; }
|
|
|
+ .summary-block strong { display:block; margin-bottom:3px; color:var(--green); font-size:.72rem; text-transform:uppercase; letter-spacing:.04em; }
|
|
|
+
|
|
|
+ /* typing indicator */
|
|
|
+ .typing { display:flex; gap:4px; align-items:center; padding:10px 14px; }
|
|
|
+ .typing span { width:7px; height:7px; background:var(--text-muted); border-radius:50%; animation:bounce .9s infinite; }
|
|
|
+ .typing span:nth-child(2){animation-delay:.2s} .typing span:nth-child(3){animation-delay:.4s}
|
|
|
+ @keyframes bounce{0%,80%,100%{transform:translateY(0)}40%{transform:translateY(-6px)}}
|
|
|
+
|
|
|
+ .hint-banner { align-self:center; margin:auto; text-align:center; color:var(--text-dim); font-size:.875rem; }
|
|
|
+ .hint-banner .emoji { font-size:2rem; margin-bottom:8px; display:block; }
|
|
|
+
|
|
|
+ .session-recovery-panel { display:flex; align-items:center; gap:8px; flex-wrap:wrap; padding:10px 16px; border-bottom:1px solid var(--border); background:var(--surface2); color:var(--text-muted); font-size:.76rem; }
|
|
|
+ .session-recovery-panel label { font-weight:600; color:var(--text); }
|
|
|
+ .session-recovery-panel input { width:92px; height:30px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); padding:0 8px; font:inherit; }
|
|
|
+ .session-recovery-panel input:focus { outline:none; border-color:var(--accent); }
|
|
|
+ .session-recovery-panel button { height:30px; border:1px solid var(--accent); border-radius:6px; background:var(--accent-dim); color:var(--accent); padding:0 10px; cursor:pointer; font:inherit; }
|
|
|
+ .session-recovery-panel button:disabled { opacity:.5; cursor:not-allowed; }
|
|
|
+ .session-recovery-panel .session-recovery-status { color:var(--text-dim); }
|
|
|
+ .session-recovery-panel .session-recovery-status.error { color:var(--red); }
|
|
|
+
|
|
|
+ /* input bar */
|
|
|
+ .input-bar {
|
|
|
+ --message-height:72px;
|
|
|
+ padding: 14px 16px;
|
|
|
+ border-top: 1px solid var(--border);
|
|
|
+ display: flex; gap: 10px; align-items: stretch;
|
|
|
+ position:relative;
|
|
|
+ }
|
|
|
+ #message { flex:1; height:var(--message-height); min-height:72px; resize:none; padding:10px 12px; background:var(--surface2); border:1px solid var(--border); border-radius:var(--radius-sm); color:var(--text); font:inherit; font-size:.875rem; outline:none; transition:border-color .2s; }
|
|
|
+ #message::placeholder { color:var(--text-dim); }
|
|
|
+ #message:focus { border-color:var(--accent); }
|
|
|
+ #message:disabled, #send:disabled { opacity:.5; cursor:not-allowed; }
|
|
|
+ #food-image-button { width:44px; min-width:44px; height:var(--message-height); min-height:72px; border:1px solid var(--border); border-radius:var(--radius-sm); background:var(--surface2); color:var(--text); font-size:1.1rem; cursor:pointer; }
|
|
|
+ #food-image-button:hover:not(:disabled) { border-color:var(--accent); background:var(--accent-dim); }
|
|
|
+ #food-image-button:disabled { opacity:.5; cursor:not-allowed; }
|
|
|
+ .food-attachment { display:none; position:absolute; left:16px; right:16px; bottom:calc(100% + 6px); align-items:center; gap:8px; padding:7px 9px; border:1px solid var(--accent); border-radius:6px; background:var(--surface2); color:var(--text-muted); font-size:.72rem; box-shadow:var(--shadow); }
|
|
|
+ .food-attachment.show { display:flex; }
|
|
|
+ .food-attachment span { flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
|
+ .food-attachment button { border:0; background:transparent; color:var(--red); cursor:pointer; font:inherit; }
|
|
|
+ #file-upload-button { width:44px; min-width:44px; height:var(--message-height); min-height:72px; border:1px solid var(--border); border-radius:var(--radius-sm); background:var(--surface2); color:var(--text); font-size:1.1rem; cursor:pointer; }
|
|
|
+ #file-upload-button:hover:not(:disabled), #file-upload-button.uploading { border-color:var(--accent); background:var(--accent-dim); }
|
|
|
+ #file-upload-button.done { border-color:var(--green); }
|
|
|
+ #file-upload-button.err { border-color:var(--red); }
|
|
|
+ .activity-picker-list { display:flex; flex-direction:column; gap:8px; }
|
|
|
+ .activity-picker-item { display:flex; align-items:center; gap:10px; width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text); cursor:pointer; text-align:left; font:inherit; }
|
|
|
+ .activity-picker-item:hover { border-color:var(--accent); background:var(--accent-dim); }
|
|
|
+ .activity-picker-item span { flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
|
+ #send { padding:0 20px; height:var(--message-height); min-height:72px; background:linear-gradient(135deg,#388bfd,#3fb950); border:none; border-radius:var(--radius-sm); color:#fff; font:inherit; font-size:.875rem; font-weight:600; cursor:pointer; transition:opacity .2s, transform .15s; white-space:nowrap; }
|
|
|
+ #send:hover:not(:disabled) { opacity:.9; transform:translateY(-1px); }
|
|
|
+ .message-resizer { position:absolute; left:16px; right:16px; top:-5px; height:10px; cursor:ns-resize; z-index:2; }
|
|
|
+ .message-resizer::before { content:''; position:absolute; left:50%; top:4px; width:44px; height:3px; transform:translateX(-50%); border-radius:2px; background:var(--border); }
|
|
|
+ .message-resizer:hover::before, .message-resizer.dragging::before { background:var(--accent); }
|
|
|
+
|
|
|
+ .ended-overlay { display:none; padding:10px 16px; background:linear-gradient(90deg,rgba(248,81,73,.08),rgba(248,81,73,.03)); border-top:1px solid rgba(248,81,73,.2); font-size:.78rem; color:var(--text-muted); text-align:center; }
|
|
|
+ .ended-overlay.show { display:block; }
|
|
|
+
|
|
|
+ /* ── Sidebar: FIT upload + workout cards ─────────────────────────────── */
|
|
|
+ .sidebar {
|
|
|
+ grid-column: 3;
|
|
|
+ grid-row: 1;
|
|
|
+ display: flex; flex-direction: column; gap: 12px;
|
|
|
+ min-height: 0;
|
|
|
+ min-width: 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ .layout-resizer {
|
|
|
+ grid-column: 2;
|
|
|
+ grid-row: 1;
|
|
|
+ position: relative;
|
|
|
+ cursor: col-resize;
|
|
|
+ touch-action: none;
|
|
|
+ user-select: none;
|
|
|
+ }
|
|
|
+ .layout-resizer::before {
|
|
|
+ content: '';
|
|
|
+ position: absolute;
|
|
|
+ inset: 0 3px;
|
|
|
+ border-radius: 3px;
|
|
|
+ background: var(--border);
|
|
|
+ transition: background .15s, box-shadow .15s;
|
|
|
+ }
|
|
|
+ .layout-resizer:hover::before,
|
|
|
+ .layout-resizer.dragging::before {
|
|
|
+ background: var(--accent);
|
|
|
+ box-shadow: 0 0 0 3px var(--accent-dim);
|
|
|
+ }
|
|
|
+
|
|
|
+ /* Health trends */
|
|
|
+ .health-trend-panel { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; flex:0 0 auto; }
|
|
|
+ .trend-header { display:flex; align-items:center; gap:8px; padding:11px 12px 9px; border-bottom:1px solid var(--border); }
|
|
|
+ .trend-header h2 { flex:1; font-size:.85rem; font-weight:600; color:var(--text-muted); }
|
|
|
+ .trend-select { width:104px; height:28px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text); font:inherit; font-size:.72rem; padding:0 6px; }
|
|
|
+ .trend-controls { display:flex; align-items:center; gap:6px; padding:8px 12px; }
|
|
|
+ .trend-periods { display:flex; gap:3px; flex:1; }
|
|
|
+ .trend-period { min-width:36px; height:27px; border:1px solid var(--border); border-radius:5px; background:transparent; color:var(--text-muted); font:inherit; font-size:.72rem; cursor:pointer; }
|
|
|
+ .trend-period:hover, .trend-period.active { border-color:var(--accent); color:var(--accent); background:var(--accent-dim); }
|
|
|
+ .trend-date { width:112px; height:27px; border:1px solid var(--border); border-radius:5px; background:var(--surface2); color:var(--text); font:inherit; font-size:.7rem; padding:0 5px; }
|
|
|
+ .trend-summary { min-height:20px; padding:0 12px 6px; color:var(--text-muted); font-size:.7rem; }
|
|
|
+ .trend-chart-wrap { height:184px; padding:0 8px 8px; }
|
|
|
+ .trend-chart { display:block; width:100%; height:100%; overflow:visible; }
|
|
|
+ .trend-grid { stroke:var(--border); stroke-width:1; stroke-dasharray:3 3; }
|
|
|
+ .trend-axis { fill:var(--text-dim); font-size:9px; }
|
|
|
+ .trend-line { fill:none; stroke:var(--accent); stroke-width:2.5; stroke-linecap:round; stroke-linejoin:round; }
|
|
|
+ .trend-area { fill:rgba(88,166,255,.12); }
|
|
|
+ .trend-point { fill:var(--surface); stroke:var(--accent); stroke-width:2; }
|
|
|
+ .trend-empty { fill:var(--text-dim); font-size:12px; text-anchor:middle; }
|
|
|
+
|
|
|
+ /* Workout cards panel */
|
|
|
+ .workout-panel {
|
|
|
+ background: var(--surface);
|
|
|
+ border: 1px solid var(--border);
|
|
|
+ border-radius: var(--radius);
|
|
|
+ display: flex; flex-direction: column;
|
|
|
+ overflow: hidden;
|
|
|
+ flex: 1 1 auto;
|
|
|
+ min-height: 0;
|
|
|
+ height: 0;
|
|
|
+ }
|
|
|
+ .workout-header {
|
|
|
+ padding: 12px 14px;
|
|
|
+ border-bottom: 1px solid var(--border);
|
|
|
+ display: flex; align-items: center; justify-content: space-between;
|
|
|
+ }
|
|
|
+ .workout-header h2 { font-size:.85rem; font-weight:600; color:var(--text-muted); }
|
|
|
+ .workout-header-meta { display:flex; align-items:center; gap:6px; }
|
|
|
+ .workout-count { font-size:.75rem; color:var(--accent); background:var(--accent-dim); border:1px solid rgba(88,166,255,.2); border-radius:20px; padding:2px 8px; }
|
|
|
+ .workout-time { padding:7px 10px; border-bottom:1px solid var(--border); color:var(--text-muted); font-size:.72rem; }
|
|
|
+ .editor-toolbar { display:none; align-items:center; gap:6px; padding:8px 10px; border-bottom:1px solid var(--border); background:var(--surface2); }
|
|
|
+ .editor-toolbar.show { display:flex; }
|
|
|
+ .editor-selection { flex:1; color:var(--text-muted); font-size:.72rem; }
|
|
|
+ .editor-btn { height:30px; min-width:30px; padding:0 9px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text-muted); font:inherit; font-size:.75rem; cursor:pointer; }
|
|
|
+ .editor-btn:hover:not(:disabled) { border-color:var(--accent); color:var(--text); }
|
|
|
+ .editor-btn:disabled { opacity:.4; cursor:not-allowed; }
|
|
|
+ .editor-btn.danger:hover:not(:disabled) { border-color:var(--red); color:var(--red); }
|
|
|
+ .workout-list { flex:1; overflow-y:auto; padding:10px; display:flex; flex-direction:column; gap:8px; }
|
|
|
+ .workout-list::-webkit-scrollbar { width:3px; }
|
|
|
+ .workout-list::-webkit-scrollbar-thumb { background:var(--border); border-radius:2px; }
|
|
|
+
|
|
|
+ .workout-empty { color:var(--text-dim); font-size:.8rem; text-align:center; padding:24px 0; }
|
|
|
+ .data-viewer-switch { display:flex; gap:8px; padding:10px; border-bottom:1px solid var(--border); background:var(--surface2); }
|
|
|
+ .data-viewer-switch button { flex:0 0 auto; min-height:34px; padding:0 13px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text-muted); font:inherit; font-size:.76rem; cursor:pointer; }
|
|
|
+ .data-viewer-switch button.active { border-color:var(--accent); color:var(--accent); background:var(--accent-dim); }
|
|
|
+ .data-viewer-filter { display:grid; grid-template-columns:minmax(150px,1fr) minmax(150px,1fr); gap:8px; padding:10px; border-bottom:1px solid var(--border); }
|
|
|
+ .data-viewer-filter label { display:flex; flex-direction:column; gap:4px; color:var(--text-muted); font-size:.68rem; }
|
|
|
+ .data-viewer-filter input, .data-viewer-filter select { width:100%; height:34px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); padding:0 8px; font:inherit; font-size:.76rem; }
|
|
|
+ .data-viewer-detail { flex:1; min-height:0; overflow-y:auto; margin:10px; padding:10px; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text-muted); font-size:.76rem; line-height:1.6; }
|
|
|
+ .data-viewer-detail[hidden] { display:none; }
|
|
|
+ .data-viewer-detail.empty { color:var(--text-dim); text-align:center; }
|
|
|
+ .nutrition-editor { display:flex; flex-direction:column; gap:12px; }
|
|
|
+ .nutrition-editor-head { display:flex; align-items:flex-start; justify-content:space-between; gap:10px; }
|
|
|
+ .nutrition-editor-head h2 { color:var(--text); font-size:.86rem; }
|
|
|
+ .nutrition-source { color:var(--accent); font-size:.68rem; }
|
|
|
+ .nutrition-metrics { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:8px; }
|
|
|
+ .nutrition-field { display:flex; flex-direction:column; gap:4px; min-width:0; color:var(--text-muted); font-size:.68rem; }
|
|
|
+ .nutrition-field input, .nutrition-field textarea { width:100%; min-width:0; border:1px solid var(--border); border-radius:5px; background:var(--surface); color:var(--text); padding:6px 7px; font:inherit; }
|
|
|
+ .nutrition-field input { height:34px; }
|
|
|
+ .nutrition-field textarea { min-height:68px; resize:vertical; }
|
|
|
+ .nutrition-field input:focus, .nutrition-field textarea:focus { border-color:var(--accent); outline:none; }
|
|
|
+ .nutrition-item-list { display:flex; flex-direction:column; gap:8px; }
|
|
|
+ .nutrition-item { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)) auto; gap:6px; align-items:end; padding:9px; border:1px solid var(--border); border-radius:6px; background:var(--surface); }
|
|
|
+ .nutrition-item .nutrition-field:nth-child(-n+2) { grid-column:span 2; }
|
|
|
+ .nutrition-item-remove { width:32px; height:34px; border:1px solid var(--border); border-radius:5px; background:transparent; color:var(--text-muted); cursor:pointer; }
|
|
|
+ .nutrition-item-remove:hover { color:var(--red); border-color:var(--red); }
|
|
|
+ .nutrition-editor-actions { display:flex; align-items:center; gap:8px; padding-top:10px; border-top:1px solid var(--border); }
|
|
|
+ .nutrition-editor-status { flex:1; min-width:0; color:var(--text-muted); font-size:.7rem; }
|
|
|
+ .nutrition-editor-status.error { color:var(--red); }
|
|
|
+ .nutrition-editor-status.success { color:var(--green); }
|
|
|
+ #training-editor-area { flex:1; min-height:0; display:flex; flex-direction:column; }
|
|
|
+ #training-editor-area[hidden] { display:none; }
|
|
|
+
|
|
|
+ /* Set card */
|
|
|
+ .set-card {
|
|
|
+ background: var(--surface2);
|
|
|
+ border: 1px solid var(--border);
|
|
|
+ border-radius: var(--radius-sm);
|
|
|
+ padding: 10px 12px;
|
|
|
+ animation: fadeUp .2s ease;
|
|
|
+ transition: border-color .2s;
|
|
|
+ }
|
|
|
+ .set-card:hover { border-color: var(--accent); }
|
|
|
+ .set-card.selected { border-color:var(--accent); box-shadow:0 0 0 1px var(--accent-dim); }
|
|
|
+ .set-card.rest {
|
|
|
+ background: transparent;
|
|
|
+ border-style: dashed;
|
|
|
+ border-color: var(--surface3);
|
|
|
+ padding: 5px 12px;
|
|
|
+ display: flex; align-items: center; gap: 8px;
|
|
|
+ }
|
|
|
+ .set-card.rest:hover { border-color: var(--text-dim); }
|
|
|
+ .set-card.rest .rest-icon { font-size:.85rem; opacity:.5; }
|
|
|
+ .set-card.rest .rest-label { font-size:.74rem; color:var(--text-dim); flex:1; }
|
|
|
+ .set-card.rest .rest-dur { font-size:.7rem; color:var(--text-dim); background:var(--surface3); border-radius:20px; padding:1px 7px; }
|
|
|
+ .set-card-top { display:flex; align-items:center; gap:8px; margin-bottom:6px; }
|
|
|
+ .set-select { width:16px; height:16px; accent-color:var(--accent); flex:0 0 auto; }
|
|
|
+
|
|
|
+ .set-idx { font-size:.7rem; font-weight:700; color:var(--text-muted); background:var(--surface3); border-radius:4px; padding:1px 6px; }
|
|
|
+ .set-name { font-size:.85rem; font-weight:600; color:var(--text); flex:1; }
|
|
|
+ .set-stats { display:flex; gap:6px; flex-wrap:wrap; }
|
|
|
+ .set-stat { font-size:.72rem; padding:2px 7px; border-radius:20px; font-weight:500; }
|
|
|
+ .set-stat.weight { background:var(--purple-dim); color:var(--purple); border:1px solid rgba(163,113,247,.2); }
|
|
|
+ .set-stat.reps { background:var(--green-dim); color:var(--green); border:1px solid rgba(63,185,80,.2); }
|
|
|
+ .set-stat.dur { background:var(--accent-dim); color:var(--accent); border:1px solid rgba(88,166,255,.2); }
|
|
|
+ .set-hr { display:flex; gap:4px; margin-top:5px; }
|
|
|
+ .hr-badge { font-size:.7rem; padding:2px 7px; border-radius:20px; font-weight:500; display:flex; align-items:center; gap:3px; }
|
|
|
+ .hr-badge.avg { background:rgba(248,81,73,.1); color:#ff7b7b; border:1px solid rgba(248,81,73,.2); }
|
|
|
+ .hr-badge.max { background:rgba(248,81,73,.18); color:var(--red); border:1px solid rgba(248,81,73,.35); }
|
|
|
+ .hr-badge::before { content:'♥'; font-size:.65rem; }
|
|
|
+ .set-editor { display:grid; grid-template-columns:minmax(90px,1fr) 76px 68px; gap:6px; margin-top:8px; align-items:end; }
|
|
|
+ .editor-field { display:flex; flex-direction:column; gap:3px; min-width:0; }
|
|
|
+ .editor-field label { font-size:.65rem; color:var(--text-dim); }
|
|
|
+ .editor-input { width:100%; height:30px; min-width:0; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); padding:0 7px; font:inherit; font-size:.75rem; outline:none; }
|
|
|
+ .editor-input:focus { border-color:var(--accent); }
|
|
|
+ .editor-error { display:none; grid-column:1 / -1; margin-top:2px; color:var(--red); font-size:.7rem; }
|
|
|
+ .editor-error.show { display:block; }
|
|
|
+ .workout-note { display:none; padding:10px; border-top:1px solid var(--border); }
|
|
|
+ .workout-note.show { display:block; }
|
|
|
+ .workout-note label { display:block; margin-bottom:5px; color:var(--text-muted); font-size:.72rem; }
|
|
|
+ .workout-note textarea { width:100%; min-height:64px; max-height:130px; resize:vertical; border:1px solid var(--border); border-radius:6px; background:var(--surface2); color:var(--text); padding:8px; font:inherit; font-size:.76rem; line-height:1.5; outline:none; }
|
|
|
+ .workout-note textarea:focus { border-color:var(--accent); }
|
|
|
+
|
|
|
+ /* session 摘要条(有氧运动) */
|
|
|
+ .session-bar {
|
|
|
+ font-size:.72rem; color:var(--text-dim); padding:6px 10px;
|
|
|
+ background:var(--surface2); border-radius:var(--radius-sm);
|
|
|
+ border:1px solid var(--border); letter-spacing:.02em;
|
|
|
+ }
|
|
|
+ /* lap 卡片标记色 */
|
|
|
+ .set-stat.dist { background:rgba(56,139,253,.12); color:#58a6ff; border:1px solid rgba(56,139,253,.25); }
|
|
|
+ .set-stat.spd { background:rgba(163,113,247,.1); color:var(--purple); border:1px solid rgba(163,113,247,.2); }
|
|
|
+ .set-stat.cad { background:rgba(63,185,80,.1); color:var(--green); border:1px solid rgba(63,185,80,.2); }
|
|
|
+ .set-stat.cal { background:rgba(255,165,0,.1); color:#ffb347; border:1px solid rgba(255,165,0,.2); }
|
|
|
+ .set-name.lap-name { color:var(--text-muted); font-weight:500; }
|
|
|
+
|
|
|
+
|
|
|
+ /* confirm button inside sidebar */
|
|
|
+ /* 保存/丢弃并排:把"取消保存"放在决定点旁边。工具栏里的「清空」离得远、
|
|
|
+ 容易被忽略,用户在看着计划决定要不要存时需要就地有个出口。 */
|
|
|
+ .workout-actions { display: none; gap: 8px; margin: 0 10px 10px; }
|
|
|
+ .workout-actions.show { display: flex; }
|
|
|
+ #btn-confirm {
|
|
|
+ flex: 1 1 auto;
|
|
|
+ padding: 9px;
|
|
|
+ background: linear-gradient(135deg, var(--green), #2ea043);
|
|
|
+ border: none; border-radius: var(--radius-sm);
|
|
|
+ color: #fff; font-family: inherit; font-size: .85rem; font-weight: 600;
|
|
|
+ cursor: pointer; transition: opacity .2s, transform .15s;
|
|
|
+ }
|
|
|
+ #btn-confirm:hover { opacity:.9; transform:translateY(-1px); }
|
|
|
+ #btn-discard {
|
|
|
+ flex: 0 0 auto;
|
|
|
+ padding: 9px 12px;
|
|
|
+ background: transparent;
|
|
|
+ border: 1px solid var(--red); border-radius: var(--radius-sm);
|
|
|
+ color: var(--red); font-family: inherit; font-size: .85rem; font-weight: 600;
|
|
|
+ cursor: pointer; transition: background .2s, transform .15s, opacity .2s;
|
|
|
+ }
|
|
|
+ #btn-discard:hover { background: var(--red-dim); transform:translateY(-1px); }
|
|
|
+ #btn-discard:disabled { opacity:.5; cursor:not-allowed; transform:none; }
|
|
|
+
|
|
|
+ /* ── Responsive: stack on narrow ─────────────────────────────────────── */
|
|
|
+ @media (max-width: 900px) {
|
|
|
+ body { grid-template-columns: 1fr; padding: 12px 10px 32px; }
|
|
|
+ header { grid-column: 1; }
|
|
|
+ .main-grid { grid-column: 1; grid-template-columns: 1fr; grid-template-rows: auto auto auto; }
|
|
|
+ .chat-panel { grid-column: 1; grid-row: 2; }
|
|
|
+ .sidebar { grid-column: 1; grid-row: 1; }
|
|
|
+ .layout-resizer { display:none; }
|
|
|
+ .main-grid { height:auto; }
|
|
|
+ .workout-panel { height:440px; flex:none; }
|
|
|
+ .health-trend-panel { margin-bottom:0; }
|
|
|
+ #chat { max-height: 50vh; }
|
|
|
+ .set-editor { grid-template-columns:minmax(100px,1fr) 70px 64px; }
|
|
|
+ .plan-save-grid { grid-template-columns:1fr; }
|
|
|
+ .overview-grid { grid-template-columns:1fr; }
|
|
|
+ .checkin-grid { grid-template-columns:1fr; }
|
|
|
+ .checkin-date-row { grid-template-columns:1fr; }
|
|
|
+ .meal-item-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }
|
|
|
+ .data-viewer-filter { grid-template-columns:1fr; }
|
|
|
+ .nutrition-metrics { grid-template-columns:repeat(2,minmax(0,1fr)); }
|
|
|
+ .nutrition-item { grid-template-columns:repeat(2,minmax(0,1fr)); }
|
|
|
+ .nutrition-item .nutrition-field:nth-child(-n+2) { grid-column:span 1; }
|
|
|
+ .nutrition-item-remove { grid-column:2; justify-self:end; }
|
|
|
+ .nutrition-metrics { grid-template-columns:repeat(2,minmax(0,1fr)); }
|
|
|
+ }
|
|
|
+
|
|
|
+ /* Refined operational workspace */
|
|
|
+ :root {
|
|
|
+ --bg: #0b0f14;
|
|
|
+ --surface: #11171e;
|
|
|
+ --surface2: #17202a;
|
|
|
+ --surface3: #202b36;
|
|
|
+ --border: #28323d;
|
|
|
+ --accent: #45c486;
|
|
|
+ --accent-dim: rgba(69,196,134,.12);
|
|
|
+ --green: #45c486;
|
|
|
+ --green-dim: rgba(69,196,134,.12);
|
|
|
+ --red: #ee6b6e;
|
|
|
+ --red-dim: rgba(238,107,110,.12);
|
|
|
+ --yellow: #e5b567;
|
|
|
+ --yellow-dim: rgba(229,181,103,.10);
|
|
|
+ --purple: #a98bd4;
|
|
|
+ --purple-dim: rgba(169,139,212,.12);
|
|
|
+ --text: #f3f7fa;
|
|
|
+ --text-muted: #aeb9c4;
|
|
|
+ --text-dim: #778491;
|
|
|
+ --radius: 8px;
|
|
|
+ --radius-sm: 6px;
|
|
|
+ --shadow: 0 12px 28px rgba(0,0,0,.22);
|
|
|
+ }
|
|
|
+
|
|
|
+ body {
|
|
|
+ font-family: "Segoe UI", "Microsoft YaHei UI", "PingFang SC", system-ui, sans-serif;
|
|
|
+ grid-template-columns: 1fr minmax(0, 1440px) 1fr;
|
|
|
+ padding: 0 16px 16px;
|
|
|
+ }
|
|
|
+
|
|
|
+ header {
|
|
|
+ min-height: 68px;
|
|
|
+ margin-bottom: 16px;
|
|
|
+ padding: 0 4px;
|
|
|
+ border-bottom: 1px solid var(--border);
|
|
|
+ }
|
|
|
+ .logo { gap: 12px; }
|
|
|
+ .logo-icon {
|
|
|
+ width: 36px;
|
|
|
+ height: 36px;
|
|
|
+ border-radius: 6px;
|
|
|
+ background: #143c2d;
|
|
|
+ color: var(--green);
|
|
|
+ font-size: 0;
|
|
|
+ font-weight: 700;
|
|
|
+ }
|
|
|
+ .logo-icon::before { content: "F"; font-size: 18px; }
|
|
|
+ .logo-text h1 {
|
|
|
+ background: none;
|
|
|
+ color: var(--text);
|
|
|
+ -webkit-text-fill-color: currentColor;
|
|
|
+ font-size: 1.1rem;
|
|
|
+ letter-spacing: 0;
|
|
|
+ }
|
|
|
+ .logo-text span { font-size: .7rem; }
|
|
|
+ .header-actions { gap: 8px; }
|
|
|
+ #btn-checkin {
|
|
|
+ border-color: var(--green);
|
|
|
+ background: var(--green);
|
|
|
+ color: var(--bg);
|
|
|
+ font-weight: 700;
|
|
|
+ }
|
|
|
+ #btn-checkin:hover { color: var(--bg); border-color: #66d39c; background: #66d39c; }
|
|
|
+ #btn-overview, #btn-data, #btn-logout {
|
|
|
+ height: 36px;
|
|
|
+ background: var(--surface2);
|
|
|
+ border-color: var(--border);
|
|
|
+ color: var(--text-muted);
|
|
|
+ }
|
|
|
+ #btn-logout { padding: 0 13px; font-weight: 500; }
|
|
|
+ #btn-logout:hover:not(:disabled) { background: var(--surface3); border-color: var(--text-dim); color: var(--text); transform: none; }
|
|
|
+
|
|
|
+ .main-grid {
|
|
|
+ --chat-width: 872px;
|
|
|
+ --workout-width: 520px;
|
|
|
+ grid-template-columns: minmax(480px, var(--chat-width)) 16px minmax(380px, var(--workout-width));
|
|
|
+ height: calc(100vh - 84px);
|
|
|
+ }
|
|
|
+ .chat-panel, .health-trend-panel, .workout-panel {
|
|
|
+ box-shadow: none;
|
|
|
+ border-color: var(--border);
|
|
|
+ }
|
|
|
+ .layout-resizer::before { inset: 0 7px; width: 2px; }
|
|
|
+
|
|
|
+ .session-recovery-panel {
|
|
|
+ min-height: 56px;
|
|
|
+ flex-wrap: nowrap;
|
|
|
+ padding: 10px 14px;
|
|
|
+ gap: 10px;
|
|
|
+ background: var(--surface);
|
|
|
+ }
|
|
|
+ .session-recovery-panel label { white-space: nowrap; font-size: .74rem; }
|
|
|
+ .session-recovery-panel input { width: 84px; height: 34px; background: var(--bg); }
|
|
|
+ .session-recovery-panel button {
|
|
|
+ height: 34px;
|
|
|
+ border-color: var(--border);
|
|
|
+ background: var(--surface2);
|
|
|
+ color: var(--text);
|
|
|
+ font-weight: 600;
|
|
|
+ white-space: nowrap;
|
|
|
+ }
|
|
|
+ .session-recovery-panel button:hover:not(:disabled) { border-color: var(--green); color: var(--green); }
|
|
|
+ .session-recovery-panel .session-recovery-status {
|
|
|
+ margin-left: auto;
|
|
|
+ overflow: hidden;
|
|
|
+ color: var(--text-dim);
|
|
|
+ font-size: .7rem;
|
|
|
+ text-overflow: ellipsis;
|
|
|
+ white-space: nowrap;
|
|
|
+ }
|
|
|
+
|
|
|
+ #chat { padding: 18px; gap: 12px; }
|
|
|
+ .msg { max-width: 78%; padding: 11px 14px; border-radius: 7px; }
|
|
|
+ .msg.user { background: #143c2d; border-color: rgba(69,196,134,.25); }
|
|
|
+ .msg.user .role, .msg.bot .role { color: var(--green); }
|
|
|
+ .msg.bot { background: var(--surface2); }
|
|
|
+ .hint-banner { color: var(--text-dim); }
|
|
|
+ .hint-banner .emoji {
|
|
|
+ width: 36px;
|
|
|
+ height: 36px;
|
|
|
+ margin: 0 auto 12px;
|
|
|
+ border-radius: 6px;
|
|
|
+ background: #143c2d;
|
|
|
+ color: var(--green);
|
|
|
+ font-size: 0;
|
|
|
+ }
|
|
|
+ .hint-banner .emoji::before { content: "F"; font-size: 18px; font-weight: 700; line-height: 36px; }
|
|
|
+
|
|
|
+ .input-bar {
|
|
|
+ --message-height: 64px;
|
|
|
+ min-height: 88px;
|
|
|
+ padding: 12px 14px;
|
|
|
+ gap: 8px;
|
|
|
+ align-items: center;
|
|
|
+ background: var(--surface);
|
|
|
+ }
|
|
|
+ #message { min-height: 64px; padding: 11px 12px; background: var(--bg); }
|
|
|
+ #food-image-button, #file-upload-button {
|
|
|
+ width: 44px;
|
|
|
+ min-width: 44px;
|
|
|
+ height: 44px;
|
|
|
+ min-height: 44px;
|
|
|
+ background: var(--surface2);
|
|
|
+ color: var(--text-muted);
|
|
|
+ font-size: 1rem;
|
|
|
+ }
|
|
|
+ #send {
|
|
|
+ min-width: 74px;
|
|
|
+ height: 44px;
|
|
|
+ min-height: 44px;
|
|
|
+ padding: 0 18px;
|
|
|
+ background: var(--green);
|
|
|
+ color: var(--bg);
|
|
|
+ border-radius: 6px;
|
|
|
+ }
|
|
|
+ #send:hover:not(:disabled) { background: #66d39c; opacity: 1; transform: none; }
|
|
|
+ .message-resizer { left: 14px; right: 14px; }
|
|
|
+
|
|
|
+ .sidebar { gap: 16px; }
|
|
|
+ .trend-header { min-height: 52px; padding: 12px 14px; }
|
|
|
+ .trend-header h2, .workout-header h2 { color: var(--text); font-size: .9rem; }
|
|
|
+ .trend-select, .trend-date, .data-viewer-filter input, .data-viewer-filter select { background: var(--bg); }
|
|
|
+ .trend-controls { padding: 10px 14px; }
|
|
|
+ .trend-summary { padding: 0 14px 8px; }
|
|
|
+ .trend-chart-wrap { height: 186px; padding: 0 10px 10px; }
|
|
|
+ .trend-line { stroke: var(--green); }
|
|
|
+ .trend-area { fill: rgba(69,196,134,.10); }
|
|
|
+ .trend-point { stroke: var(--green); }
|
|
|
+ .trend-period:hover, .trend-period.active {
|
|
|
+ border-color: var(--green);
|
|
|
+ color: var(--green);
|
|
|
+ background: var(--green-dim);
|
|
|
+ }
|
|
|
+ .data-viewer-switch { padding: 8px; background: var(--surface); }
|
|
|
+ .data-viewer-switch button { min-height: 34px; background: transparent; }
|
|
|
+ .data-viewer-switch button.active {
|
|
|
+ border-color: var(--border);
|
|
|
+ background: var(--surface2);
|
|
|
+ color: var(--text);
|
|
|
+ }
|
|
|
+ .data-viewer-filter { padding: 10px 12px; }
|
|
|
+ .workout-header { padding: 12px 14px; }
|
|
|
+ .workout-count {
|
|
|
+ border: 0;
|
|
|
+ border-radius: 5px;
|
|
|
+ background: #143c2d;
|
|
|
+ color: var(--green);
|
|
|
+ }
|
|
|
+ .workout-list { padding: 12px; }
|
|
|
+ .set-card { background: var(--surface2); border-radius: 6px; }
|
|
|
+ .set-card:hover, .set-card.selected { border-color: var(--green); }
|
|
|
+ .workout-actions { margin: 0 12px 12px; }
|
|
|
+ #btn-confirm { background: var(--green); color: var(--bg); border-radius: 6px; }
|
|
|
+ #btn-confirm:hover { background: #66d39c; opacity: 1; transform: none; }
|
|
|
+ #btn-discard { border-color: var(--border); background: var(--surface2); font-weight: 500; }
|
|
|
+
|
|
|
+ @media (max-width: 1050px) {
|
|
|
+ body { grid-template-columns: 1fr; padding: 0 12px 24px; }
|
|
|
+ header { grid-column: 1; }
|
|
|
+ .main-grid {
|
|
|
+ grid-column: 1;
|
|
|
+ grid-template-columns: minmax(0, 1fr);
|
|
|
+ grid-template-rows: auto auto;
|
|
|
+ height: auto;
|
|
|
+ gap: 16px;
|
|
|
+ }
|
|
|
+ .chat-panel { grid-column: 1; grid-row: 1; min-height: calc(100vh - 100px); }
|
|
|
+ .sidebar { grid-column: 1; grid-row: 2; }
|
|
|
+ .layout-resizer { display: none; }
|
|
|
+ .health-trend-panel { margin: 0; }
|
|
|
+ .workout-panel { height: 520px; flex: none; }
|
|
|
+ #chat { max-height: none; }
|
|
|
+ }
|
|
|
+
|
|
|
+ @media (max-width: 640px) {
|
|
|
+ body { padding: 0 8px 20px; }
|
|
|
+ header { min-height: 0; margin-bottom: 10px; padding: 8px 0; gap: 8px; flex-wrap: wrap; }
|
|
|
+ .logo { width: 100%; }
|
|
|
+ .logo-text span { display: none; }
|
|
|
+ .logo-icon { width: 32px; height: 32px; }
|
|
|
+ .header-actions { width: 100%; min-width: 0; overflow-x: auto; padding-bottom: 2px; }
|
|
|
+ #btn-checkin, #btn-overview, #btn-data, #btn-logout { flex: 0 0 auto; }
|
|
|
+ #btn-logout { padding: 0 10px; }
|
|
|
+ .main-grid { gap: 10px; }
|
|
|
+ .chat-panel { min-height: calc(100vh - 78px); }
|
|
|
+ .session-recovery-panel { flex-wrap: wrap; padding: 9px 10px; }
|
|
|
+ .session-recovery-panel label { flex: 1 1 100%; white-space: normal; }
|
|
|
+ .session-recovery-panel input { margin-left: 0; }
|
|
|
+ .session-recovery-panel button { flex: 1 1 auto; }
|
|
|
+ .session-recovery-panel .session-recovery-status { display: none; }
|
|
|
+ #chat { padding: 12px; }
|
|
|
+ .msg { max-width: 92%; }
|
|
|
+ .input-bar { min-height: 80px; padding: 9px; gap: 6px; }
|
|
|
+ #message { min-width: 0; min-height: 58px; height: 58px; }
|
|
|
+ #food-image-button, #file-upload-button { width: 38px; min-width: 38px; height: 42px; min-height: 42px; font-size: .9rem; }
|
|
|
+ #send { min-width: 58px; height: 42px; min-height: 42px; padding: 0 12px; }
|
|
|
+ .trend-header, .trend-controls, .data-viewer-filter { flex-wrap: wrap; }
|
|
|
+ .trend-select { width: 132px; }
|
|
|
+ .data-viewer-switch { overflow-x: auto; }
|
|
|
+ .data-viewer-switch button { white-space: nowrap; }
|
|
|
+ .data-viewer-filter { grid-template-columns: 1fr; }
|
|
|
+ .workout-panel { height: 500px; }
|
|
|
+ }
|
|
|
+ </style>
|
|
|
+</head>
|
|
|
+<body>
|
|
|
+ <!-- ── Header ─────────────────────────────────────────────────────────── -->
|
|
|
+ <header>
|
|
|
+ <div class="logo">
|
|
|
+ <div class="logo-icon">💪</div>
|
|
|
+ <div class="logo-text">
|
|
|
+ <h1>FitHealthAgent</h1>
|
|
|
+ <span>智能健康训练助手</span>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ <div class="header-actions">
|
|
|
+ <button id="btn-checkin" type="button" title="新增每日记录">新增记录</button>
|
|
|
+ <button id="btn-overview" type="button" title="单日健康总览" aria-label="打开单日健康总览">单日健康总览</button>
|
|
|
+ <button id="btn-data" type="button" title="数据管理" aria-label="打开数据管理">⚙</button>
|
|
|
+ <button id="btn-logout" type="button" title="退出并智能保存对话摘要">
|
|
|
+ <span class="icon">🚪</span>
|
|
|
+ <span class="spin"></span>
|
|
|
+ <span class="lbl">退出</span>
|
|
|
+ </button>
|
|
|
+ </div>
|
|
|
+ </header>
|
|
|
+
|
|
|
+ <!-- ── Main grid ──────────────────────────────────────────────────────── -->
|
|
|
+ <div class="main-grid">
|
|
|
+
|
|
|
+ <!-- Chat panel -->
|
|
|
+ <div class="chat-panel">
|
|
|
+ <div class="chat-drop-overlay" id="chat-drop-overlay" aria-hidden="true"><div class="chat-drop-message"><strong>松开以导入或分析</strong><span>餐盘照片会估算热量;也支持训练 FIT、训练计划和健康/训练 ZIP/CSV</span></div></div>
|
|
|
+ <div class="session-recovery-panel" id="session-recovery-panel" aria-label="Garmin 恢复时间输入">
|
|
|
+ <label for="session-garmin-hours">Garmin 建议的恢复时间还有几小时?</label>
|
|
|
+ <input id="session-garmin-hours" type="number" min="0" max="96.0" step="0.1" value="0" inputmode="decimal" aria-describedby="session-recovery-status" />
|
|
|
+ <button id="session-recovery-apply" type="button">应用到本次会话</button>
|
|
|
+ <span class="session-recovery-status" id="session-recovery-status">输入 0–96.0,可统一增加本次会话的恢复小时。</span>
|
|
|
+ </div>
|
|
|
+ <div id="chat" aria-live="polite" aria-label="聊天记录">
|
|
|
+ <div class="hint-banner" id="hint">
|
|
|
+ <span class="emoji">🏋️</span>
|
|
|
+ 上传 Garmin .fit 文件或直接输入训练内容。
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ <div class="ended-overlay" id="ended-overlay">🔒 会话已结束,输入已禁用</div>
|
|
|
+ <form class="input-bar" id="form" autocomplete="off">
|
|
|
+ <div class="message-resizer" id="message-resizer" role="separator" aria-label="调整输入框高度" aria-orientation="horizontal" tabindex="0"></div>
|
|
|
+ <div class="food-attachment" id="food-attachment"><span id="food-attachment-name"></span><button id="food-attachment-remove" type="button">移除</button></div>
|
|
|
+ <textarea id="message" placeholder="例如:把第2和第3组合并;或:今天卧推 60kg×5组"></textarea>
|
|
|
+ <input id="food-image-input" type="file" accept="image/jpeg,image/png,image/webp" hidden />
|
|
|
+ <button id="food-image-button" type="button" title="上传餐盘照片分析热量" aria-label="上传餐盘照片分析热量">📷</button>
|
|
|
+ <input id="file-input" type="file" accept=".fit,.zip,.csv,.md,.txt" multiple hidden />
|
|
|
+ <button id="file-upload-button" type="button" title="上传训练、健康数据或计划" aria-label="上传训练、健康数据或计划">📁</button>
|
|
|
+ <button id="send" type="submit">发送</button>
|
|
|
+ </form>
|
|
|
+ </div>
|
|
|
+
|
|
|
+ <div
|
|
|
+ class="layout-resizer"
|
|
|
+ id="layout-resizer"
|
|
|
+ role="separator"
|
|
|
+ aria-label="调整对话与训练区域宽度"
|
|
|
+ aria-orientation="vertical"
|
|
|
+ tabindex="0"
|
|
|
+ ></div>
|
|
|
+
|
|
|
+ <!-- Sidebar -->
|
|
|
+ <div class="sidebar">
|
|
|
+ <section class="health-trend-panel" aria-label="健康指标趋势">
|
|
|
+ <div class="trend-header">
|
|
|
+ <h2>健康趋势</h2>
|
|
|
+ <select class="trend-select" id="trend-metric" aria-label="选择健康指标">
|
|
|
+ <option value="heart_rate">心率 (bpm)</option>
|
|
|
+ <option value="stress">压力</option>
|
|
|
+ <option value="respiration">呼吸频率</option>
|
|
|
+ <option value="spo2">血氧饱和度</option>
|
|
|
+ <option value="hrv">HRV</option>
|
|
|
+ <option value="total_calories">总消耗热量 (kcal)</option>
|
|
|
+ </select>
|
|
|
+ </div>
|
|
|
+ <div class="trend-controls">
|
|
|
+ <div class="trend-periods" role="group" aria-label="选择时间范围">
|
|
|
+ <button class="trend-period active" type="button" data-period="day">日</button>
|
|
|
+ <button class="trend-period" type="button" data-period="week">周</button>
|
|
|
+ <button class="trend-period" type="button" data-period="month">月</button>
|
|
|
+ </div>
|
|
|
+ <input class="trend-date" id="trend-date" type="date" aria-label="趋势截止日期" />
|
|
|
+ </div>
|
|
|
+ <div class="trend-summary" id="trend-summary" aria-live="polite">正在加载健康数据…</div>
|
|
|
+ <div class="trend-chart-wrap"><svg class="trend-chart" id="trend-chart" role="img" aria-label="健康指标折线图"></svg></div>
|
|
|
+ </section>
|
|
|
+
|
|
|
+ <!-- Workout cards -->
|
|
|
+ <div class="workout-panel">
|
|
|
+ <div class="data-viewer-switch" role="group" aria-label="选择右侧数据类型">
|
|
|
+ <button id="viewer-training" type="button" class="active">训练组数据</button>
|
|
|
+ <button id="viewer-nutrition" type="button">营养组数据</button>
|
|
|
+ </div>
|
|
|
+ <div class="data-viewer-filter">
|
|
|
+ <label>数据组<select id="viewer-record-select" disabled><option>请选择日期</option></select></label>
|
|
|
+ <label>日期<input id="viewer-date" type="date" /></label>
|
|
|
+ </div>
|
|
|
+ <div id="viewer-detail" class="data-viewer-detail empty" hidden></div>
|
|
|
+ <div id="training-editor-area">
|
|
|
+ <div class="workout-header">
|
|
|
+ <h2 id="viewer-content-title">训练组列表</h2>
|
|
|
+ <div class="workout-header-meta">
|
|
|
+ <span class="workout-count" id="set-count">0 组</span>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ <div class="workout-time" id="workout-time">训练时间:--</div>
|
|
|
+ <div class="editor-toolbar" id="editor-toolbar">
|
|
|
+ <span class="editor-selection" id="editor-selection">已选择 0 组</span>
|
|
|
+ <button class="editor-btn" id="btn-rename" type="button" disabled title="统一重命名选中的动作组">重命名</button>
|
|
|
+ <button class="editor-btn" id="btn-merge" type="button" disabled title="合并选中的动作组">合并</button>
|
|
|
+ <button class="editor-btn" id="btn-undo" type="button" disabled title="撤销最近一次已提交的训练编辑">撤销</button>
|
|
|
+ <button class="editor-btn" id="btn-restore-source" type="button" disabled title="放弃所有待确认编辑,恢复 FIT 原始解析结果">恢复原件</button>
|
|
|
+ <button class="editor-btn danger" id="btn-clear" type="button" title="清空待确认训练">清空</button>
|
|
|
+ </div>
|
|
|
+ <div class="workout-list" id="workout-list">
|
|
|
+ <div class="workout-empty">上传 .fit 文件后将在此显示训练组</div>
|
|
|
+ </div>
|
|
|
+ <div class="workout-note" id="workout-note-wrap">
|
|
|
+ <label for="workout-note">本次训练感受</label>
|
|
|
+ <textarea id="workout-note" maxlength="500" placeholder="例如:状态良好、下背略疲劳、最后两组比较吃力"></textarea>
|
|
|
+ </div>
|
|
|
+ <div class="workout-actions" id="workout-actions">
|
|
|
+ <button id="btn-confirm" type="button">✅ 确认并保存训练</button>
|
|
|
+ <button id="btn-discard" type="button" title="不保存,丢弃这次导入的训练">🗑 取消并丢弃</button>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+
|
|
|
+ </div><!-- /.main-grid -->
|
|
|
+
|
|
|
+ <div class="modal-backdrop" id="checkin-modal" aria-hidden="true">
|
|
|
+ <div class="checkin-modal" role="dialog" aria-modal="true" aria-labelledby="checkin-modal-title">
|
|
|
+ <div class="modal-header"><h2 id="checkin-modal-title">每日手动记录</h2><button class="modal-close" id="checkin-modal-close" type="button" aria-label="关闭">×</button></div>
|
|
|
+ <form class="checkin-form" id="checkin-form">
|
|
|
+ <div class="checkin-grid">
|
|
|
+ <div class="checkin-date-row">
|
|
|
+ <div class="checkin-field"><label for="checkin-date">日期</label><input id="checkin-date" name="date" type="date" required /></div>
|
|
|
+ <button class="data-action" id="add-nutrition-record" type="button">添加营养记录</button>
|
|
|
+ </div>
|
|
|
+ <div class="checkin-hint" id="checkin-hint"></div>
|
|
|
+ <div class="checkin-section">身体与恢复</div>
|
|
|
+ <div class="checkin-field"><label>体重 (kg)</label><input name="weight_kg" type="number" min="20" max="350" step="0.1" /></div>
|
|
|
+ <div class="checkin-field"><label>睡眠质量 (1-10)</label><input name="sleep_quality" type="number" min="1" max="10" step="1" /></div>
|
|
|
+ <div class="checkin-field"><label>精力 (1-10)</label><input name="energy_level" type="number" min="1" max="10" step="1" /></div>
|
|
|
+ <div class="checkin-field"><label>疲劳 (1-10)</label><input name="fatigue_level" type="number" min="1" max="10" step="1" /></div>
|
|
|
+ <div class="checkin-field"><label>疼痛 (0-10)</label><input name="pain_level" type="number" min="0" max="10" step="1" /></div>
|
|
|
+ <div class="checkin-section">营养与训练</div>
|
|
|
+ <div class="checkin-field"><label>热量 (kcal)</label><input name="calories_kcal" type="number" min="0" step="1" /></div>
|
|
|
+ <div class="checkin-field"><label>蛋白质 (g)</label><input name="protein_g" type="number" min="0" step="0.1" /></div>
|
|
|
+ <div class="checkin-field"><label>碳水 (g)</label><input name="carbs_g" type="number" min="0" step="0.1" /></div>
|
|
|
+ <div class="checkin-field"><label>脂肪 (g)</label><input name="fat_g" type="number" min="0" step="0.1" /></div>
|
|
|
+ <div class="checkin-field"><label>训练 RPE (1-10)</label><input name="training_rpe" type="number" min="1" max="10" step="1" /></div>
|
|
|
+ <div class="checkin-field"><label>训练完成度 (%)</label><input name="training_completion_pct" type="number" min="0" max="100" step="1" /></div>
|
|
|
+ <label class="checkin-field full"><span>放纵餐</span><input name="cheat_meal" type="checkbox" /></label>
|
|
|
+ <div class="checkin-section meal-estimate-section" id="meal-estimate-section" hidden>营养组</div>
|
|
|
+ <div class="meal-estimates" id="meal-estimates" hidden></div>
|
|
|
+ <div class="checkin-field full"><label>备注</label><textarea name="note" maxlength="500"></textarea></div>
|
|
|
+ </div>
|
|
|
+ <div class="checkin-actions"><button class="data-action" id="checkin-cancel" type="button">取消</button><button class="data-action" type="submit">保存记录</button></div>
|
|
|
+ </form>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+
|
|
|
+ <div class="modal-backdrop" id="activity-picker-modal" aria-hidden="true">
|
|
|
+ <div class="checkin-modal" role="dialog" aria-modal="true" aria-labelledby="activity-picker-title">
|
|
|
+ <div class="modal-header"><h2 id="activity-picker-title">选择要编辑的训练</h2><button class="modal-close" id="activity-picker-close" type="button" aria-label="关闭">×</button></div>
|
|
|
+ <div class="checkin-form"><p class="profile-summary">压缩包中的健康数据已导入。选择一份活动 FIT 后,可在训练编辑区修改动作和合并组,再确认保存。</p><div class="activity-picker-list" id="activity-picker-list"></div></div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+
|
|
|
+ <div class="modal-backdrop" id="health-modal" aria-hidden="true">
|
|
|
+ <div class="health-modal" role="dialog" aria-modal="true" aria-labelledby="health-modal-title">
|
|
|
+ <div class="modal-header">
|
|
|
+ <h2 id="health-modal-title">每日健康总览</h2>
|
|
|
+ <button class="modal-close" id="health-modal-close" type="button" aria-label="关闭">×</button>
|
|
|
+ </div>
|
|
|
+ <div class="overview-controls">
|
|
|
+ <button class="overview-nav" id="overview-prev" type="button" title="前一天" aria-label="查看前一天">‹</button>
|
|
|
+ <input class="overview-date" id="overview-date" type="date" aria-label="选择日期" />
|
|
|
+ <button class="overview-nav" id="overview-next" type="button" title="后一天" aria-label="查看后一天">›</button>
|
|
|
+ </div>
|
|
|
+ <div class="overview-body">
|
|
|
+ <div class="overview-status" id="overview-status" aria-live="polite">正在加载健康数据…</div>
|
|
|
+ <div class="overview-grid" id="overview-grid"></div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+
|
|
|
+ <div class="modal-backdrop" id="data-modal" aria-hidden="true">
|
|
|
+ <div class="data-modal" role="dialog" aria-modal="true" aria-labelledby="data-modal-title">
|
|
|
+ <div class="modal-header">
|
|
|
+ <h2 id="data-modal-title">数据管理</h2>
|
|
|
+ <button class="modal-close" id="data-modal-close" type="button" aria-label="关闭">×</button>
|
|
|
+ </div>
|
|
|
+ <div class="modal-body">
|
|
|
+ <details class="data-section data-collapsible" open>
|
|
|
+ <summary class="section-heading"><h3>训练计划</h3><span class="section-count" id="plans-count">0 条</span></summary>
|
|
|
+ <div class="data-list" id="plans-list"></div>
|
|
|
+ <div class="data-actions" style="margin-top:10px"><button class="data-action danger" id="delete-plans" type="button" disabled>删除所选计划</button></div>
|
|
|
+ <div class="plan-preview" id="plan-preview">
|
|
|
+ <div class="plan-preview-header"><strong id="plan-preview-title"></strong><button class="small-delete" id="plan-preview-download" type="button">下载</button><button class="small-delete" id="plan-preview-close" type="button">关闭</button></div>
|
|
|
+ <div class="plan-preview-body" id="plan-preview-body"></div>
|
|
|
+ </div>
|
|
|
+ </details>
|
|
|
+ <details class="data-section data-collapsible" open>
|
|
|
+ <summary class="section-heading"><h3>训练记录</h3><span class="section-count" id="records-count">0 条</span></summary>
|
|
|
+ <div class="data-list" id="records-list"></div>
|
|
|
+ <div class="data-actions" style="margin-top:10px"><button class="data-action" id="open-checkin" type="button">新增记录</button><button class="data-action" id="view-record" type="button" disabled title="请先选择一条训练记录">查看所选记录</button><button class="data-action danger" id="delete-records" type="button" disabled>删除所选记录</button></div>
|
|
|
+ <div class="record-preview" id="record-preview">
|
|
|
+ <div class="record-preview-header"><strong id="record-preview-title"></strong><button class="small-delete" id="record-preview-close" type="button">关闭</button></div>
|
|
|
+ <div class="record-preview-body" id="record-preview-body"></div>
|
|
|
+ </div>
|
|
|
+ </details>
|
|
|
+ <section class="data-section">
|
|
|
+ <div class="section-heading"><h3>每日与营养记录</h3><span class="section-count" id="daily-records-count">0 条</span></div>
|
|
|
+ <div class="data-list" id="daily-records-list"></div>
|
|
|
+ </section>
|
|
|
+ <details class="data-section data-collapsible" open>
|
|
|
+ <summary class="section-heading"><h3>全天健康与睡眠</h3><span class="section-count" id="health-imports-count">0 条</span></summary>
|
|
|
+ <div class="data-list" id="health-imports-list"></div>
|
|
|
+ </details>
|
|
|
+ <details class="data-section data-collapsible">
|
|
|
+ <summary class="section-heading"><h3>数据文件对账</h3><span class="section-count" id="data-audit-count">0 项</span></summary>
|
|
|
+ <div class="data-list" id="data-audit-list"></div>
|
|
|
+ </details>
|
|
|
+ <section class="data-section">
|
|
|
+ <div class="section-heading"><h3>被隔离的未确认训练</h3><span class="section-count" id="quarantined-count">0 条</span></div>
|
|
|
+ <div class="data-list" id="quarantined-list"></div>
|
|
|
+ </section>
|
|
|
+ <details class="data-section data-collapsible" open>
|
|
|
+ <summary class="section-heading"><h3>临时记忆</h3><span class="section-count" id="memories-count">0 条</span></summary>
|
|
|
+ <div class="data-list" id="memories-list"></div>
|
|
|
+ <div class="data-actions" style="margin-top:10px"><button class="data-action danger" id="clear-memories" type="button">清空临时记忆</button></div>
|
|
|
+ </details>
|
|
|
+ <details class="data-section data-collapsible" open>
|
|
|
+ <summary class="section-heading"><h3>酸痛与伤病记录</h3><span class="section-count" id="soreness-count">0 条</span></summary>
|
|
|
+ <div class="data-actions" style="margin-bottom:10px"><button class="data-action" id="add-soreness" type="button">新增酸痛记录</button></div>
|
|
|
+ <div class="data-list" id="soreness-list"></div>
|
|
|
+ </details>
|
|
|
+ <section class="data-section">
|
|
|
+ <div class="section-heading"><h3>重置前恢复点</h3><span class="section-count" id="recovery-points-count">0 条</span></div>
|
|
|
+ <div class="data-list" id="recovery-points-list"></div>
|
|
|
+ </section>
|
|
|
+ <section class="data-section">
|
|
|
+ <div class="section-heading"><h3>本地数据</h3></div>
|
|
|
+ <div class="profile-summary" id="profile-data-summary"></div>
|
|
|
+ <div class="data-actions">
|
|
|
+ <button class="data-action" id="export-backup" type="button">导出备份</button>
|
|
|
+ <button class="data-action" id="import-backup" type="button">导入备份</button>
|
|
|
+ <input id="backup-file" type="file" accept=".zip,application/zip" hidden />
|
|
|
+ <button class="data-action danger" id="delete-pending" type="button">删除待确认训练</button>
|
|
|
+ <button class="data-action danger" id="reset-profile" type="button">重置用户档案</button>
|
|
|
+ </div>
|
|
|
+ <div class="reset-confirm">
|
|
|
+ <input id="reset-confirmation" placeholder="输入“删除全部数据”" autocomplete="off" />
|
|
|
+ <button class="data-action danger" id="reset-all" type="button">删除全部数据</button>
|
|
|
+ </div>
|
|
|
+ <div class="modal-status" id="data-status" aria-live="polite"></div>
|
|
|
+ </section>
|
|
|
+ <section class="data-section">
|
|
|
+ <div class="section-heading"><h3>外部模型与数据外发</h3></div>
|
|
|
+ <div class="privacy-setting">
|
|
|
+ <div class="privacy-setting-head">
|
|
|
+ <div class="privacy-setting-copy">
|
|
|
+ <strong>允许联网模型处理数据</strong>
|
|
|
+ <p>关闭后,对话、餐盘识别、模糊训练计划鉴定和退出摘要不会发送到外部模型。</p>
|
|
|
+ </div>
|
|
|
+ <label class="privacy-toggle"><input id="external-models-toggle" type="checkbox" />启用</label>
|
|
|
+ </div>
|
|
|
+ <div class="privacy-status" id="external-models-status" aria-live="polite">正在读取设置…</div>
|
|
|
+ <div class="privacy-disclosure" id="external-model-disclosure"></div>
|
|
|
+ <div class="privacy-local" id="external-model-local-features"></div>
|
|
|
+ </div>
|
|
|
+ </section>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+
|
|
|
+ <script>
|
|
|
+ /* ════════════════════════════════════════════════════
|
|
|
+ FitHealthAgent Frontend
|
|
|
+ 功能:
|
|
|
+ 1. 聊天(/chat)
|
|
|
+ 2. 拖拽/点击上传 .fit(/upload_fit)→ 注入 Agent 消息
|
|
|
+ 3. 轮询 /workout_state 实时更新训练卡片
|
|
|
+ 4. "确认并保存"按钮 → 发送 "confirm" 消息
|
|
|
+ 5. 退出(/logout)→ 智能摘要判断
|
|
|
+ ════════════════════════════════════════════════════ */
|
|
|
+
|
|
|
+ const $chat = document.getElementById('chat');
|
|
|
+ const $chatPanel = document.querySelector('.chat-panel');
|
|
|
+ const $form = document.getElementById('form');
|
|
|
+ const $msg = document.getElementById('message');
|
|
|
+ const $foodImageInput = document.getElementById('food-image-input');
|
|
|
+ const $foodImageButton = document.getElementById('food-image-button');
|
|
|
+ const $foodAttachment = document.getElementById('food-attachment');
|
|
|
+ const $foodAttachmentName = document.getElementById('food-attachment-name');
|
|
|
+ const $fileUploadButton = document.getElementById('file-upload-button');
|
|
|
+ const $send = document.getElementById('send');
|
|
|
+ const $logout = document.getElementById('btn-logout');
|
|
|
+ const $checkinButton = document.getElementById('btn-checkin');
|
|
|
+ const $checkinModal = document.getElementById('checkin-modal');
|
|
|
+ const $checkinModalClose = document.getElementById('checkin-modal-close');
|
|
|
+ const $checkinForm = document.getElementById('checkin-form');
|
|
|
+ const $checkinHint = document.getElementById('checkin-hint');
|
|
|
+ const $mealEstimateSection = document.getElementById('meal-estimate-section');
|
|
|
+ const $mealEstimates = document.getElementById('meal-estimates');
|
|
|
+ const $addNutritionRecord = document.getElementById('add-nutrition-record');
|
|
|
+ let pendingMealEstimates = [];
|
|
|
+ let loadedCheckinFields = new Set();
|
|
|
+ let checkinSubmitting = false;
|
|
|
+ const $overviewButton = document.getElementById('btn-overview');
|
|
|
+ const $healthModal = document.getElementById('health-modal');
|
|
|
+ const $healthModalClose = document.getElementById('health-modal-close');
|
|
|
+ const $overviewDate = document.getElementById('overview-date');
|
|
|
+ const $overviewStatus = document.getElementById('overview-status');
|
|
|
+ const $overviewGrid = document.getElementById('overview-grid');
|
|
|
+ const $dataButton = document.getElementById('btn-data');
|
|
|
+ const $dataModal = document.getElementById('data-modal');
|
|
|
+ const $dataModalClose = document.getElementById('data-modal-close');
|
|
|
+ const $hint = document.getElementById('hint');
|
|
|
+ const $overlay = document.getElementById('ended-overlay');
|
|
|
+ const $fileIn = document.getElementById('file-input');
|
|
|
+ const $activityPickerModal = document.getElementById('activity-picker-modal');
|
|
|
+ const $activityPickerList = document.getElementById('activity-picker-list');
|
|
|
+ const $wList = document.getElementById('workout-list');
|
|
|
+ const $setCount = document.getElementById('set-count');
|
|
|
+ const $confirm = document.getElementById('btn-confirm');
|
|
|
+ const $discard = document.getElementById('btn-discard');
|
|
|
+ const $workoutActions = document.getElementById('workout-actions');
|
|
|
+ const $workoutTime = document.getElementById('workout-time');
|
|
|
+ const $workoutNoteWrap = document.getElementById('workout-note-wrap');
|
|
|
+ const $viewerTraining = document.getElementById('viewer-training');
|
|
|
+ const $viewerNutrition = document.getElementById('viewer-nutrition');
|
|
|
+ const $viewerSelect = document.getElementById('viewer-record-select');
|
|
|
+ const $viewerDate = document.getElementById('viewer-date');
|
|
|
+ const $viewerDetail = document.getElementById('viewer-detail');
|
|
|
+ const $trainingEditorArea = document.getElementById('training-editor-area');
|
|
|
+ const $viewerContentTitle = document.getElementById('viewer-content-title');
|
|
|
+ const $workoutNote = document.getElementById('workout-note');
|
|
|
+ const $editorToolbar = document.getElementById('editor-toolbar');
|
|
|
+ const $editorSelection = document.getElementById('editor-selection');
|
|
|
+ const $merge = document.getElementById('btn-merge');
|
|
|
+ const $rename = document.getElementById('btn-rename');
|
|
|
+ const $undo = document.getElementById('btn-undo');
|
|
|
+ const $restoreSource = document.getElementById('btn-restore-source');
|
|
|
+ const $clear = document.getElementById('btn-clear');
|
|
|
+ const $mainGrid = document.querySelector('.main-grid');
|
|
|
+ const $layoutResizer = document.getElementById('layout-resizer');
|
|
|
+ const $messageResizer = document.getElementById('message-resizer');
|
|
|
+ const $trendMetric = document.getElementById('trend-metric');
|
|
|
+ const $trendDate = document.getElementById('trend-date');
|
|
|
+ const $trendSummary = document.getElementById('trend-summary');
|
|
|
+ const $trendChart = document.getElementById('trend-chart');
|
|
|
+
|
|
|
+ let sessionEnded = false;
|
|
|
+ let hasWorkout = false;
|
|
|
+ let pollTimer = null;
|
|
|
+ let selectedSets = new Set();
|
|
|
+ let editorBusy = false;
|
|
|
+ let discardBusy = false;
|
|
|
+ let renderedWorkoutKey = '';
|
|
|
+ let workoutNoteDraft = '';
|
|
|
+ let workoutConfirmation = null;
|
|
|
+ let workoutEditHistory = { can_undo:false, can_restore_parsed_source:false };
|
|
|
+ let activeSavedTrainingRecordId = null;
|
|
|
+ let activeSavedTrainingRecordRevision = null;
|
|
|
+ let pendingMessageSource = 'chat';
|
|
|
+ let pendingPlanContext = null;
|
|
|
+ let pendingMemoryEntryIds = [];
|
|
|
+ const sessionConversationHistory = [];
|
|
|
+ const SESSION_HISTORY_MAX_ITEMS = 20;
|
|
|
+ let previewedPlan = null;
|
|
|
+ let chatDragDepth = 0;
|
|
|
+ let trendPeriod = 'day';
|
|
|
+ let activityPickerFiles = [];
|
|
|
+ let activePickerActivity = '';
|
|
|
+ let pendingFoodImage = null;
|
|
|
+ let externalModelsEnabled = true;
|
|
|
+ let messageResizeStart = null;
|
|
|
+ let sessionGarminRecoveryHours = 0;
|
|
|
+ let sorenessPromptRegions = [];
|
|
|
+ let viewerMode = 'training';
|
|
|
+ let viewerItems = [];
|
|
|
+ let viewerSelectedArtifact = null;
|
|
|
+ let viewerLoadToken = 0;
|
|
|
+ let workoutRefreshInFlight = false;
|
|
|
+
|
|
|
+ const LAYOUT_STORAGE_KEY = 'fithealth-layout-v2';
|
|
|
+ const MIN_CHAT_WIDTH = 480;
|
|
|
+ const MIN_WORKOUT_WIDTH = 380;
|
|
|
+ const DEFAULT_WORKOUT_WIDTH = 520;
|
|
|
+ const LAYOUT_BREAKPOINT = '(max-width: 1050px)';
|
|
|
+
|
|
|
+ /* BUG-46:/profile/status 的 missing_fields 原先无人消费,用户只看到一句笼统的
|
|
|
+ 补全提示,不知道到底缺哪几项。 */
|
|
|
+ const PROFILE_FIELD_LABELS = {
|
|
|
+ weekly_weight_kg: '体重', height_cm: '身高', birth_date: '出生日期',
|
|
|
+ sex: '性别', goal: '训练目标',
|
|
|
+ };
|
|
|
+
|
|
|
+ const trendMetricLabels = {
|
|
|
+ heart_rate: '心率', stress: '压力', respiration: '呼吸频率', spo2: '血氧饱和度', hrv: 'HRV',
|
|
|
+ total_calories: '总消耗热量',
|
|
|
+ };
|
|
|
+
|
|
|
+ function formatOverviewValue(value, digits = 0) {
|
|
|
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '--';
|
|
|
+ return value.toFixed(digits);
|
|
|
+ }
|
|
|
+
|
|
|
+ function formatOverviewDuration(minutes) {
|
|
|
+ if (typeof minutes !== 'number' || !Number.isFinite(minutes)) return '--';
|
|
|
+ const total = Math.max(0, Math.round(minutes));
|
|
|
+ return Math.floor(total / 60) + ' 小时 ' + total % 60 + ' 分钟';
|
|
|
+ }
|
|
|
+
|
|
|
+ function formatOverviewTime(value) {
|
|
|
+ return typeof value === 'string' && value.length >= 16 ? value.slice(11, 16) : '--';
|
|
|
+ }
|
|
|
+
|
|
|
+ function createOverviewCard(title, value, unit, details = []) {
|
|
|
+ const card = document.createElement('section'); card.className = 'overview-card';
|
|
|
+ const heading = document.createElement('h3'); heading.textContent = title;
|
|
|
+ const primary = document.createElement('div'); primary.className = 'overview-value';
|
|
|
+ primary.append(document.createTextNode(value));
|
|
|
+ if (unit) { const suffix = document.createElement('small'); suffix.textContent = ' ' + unit; primary.appendChild(suffix); }
|
|
|
+ const meta = document.createElement('div'); meta.className = 'overview-details';
|
|
|
+ details.forEach(detail => {
|
|
|
+ const item = document.createElement('span'); item.textContent = detail.text;
|
|
|
+ if (detail.tone) item.className = 'overview-detail-' + detail.tone;
|
|
|
+ meta.appendChild(item);
|
|
|
+ });
|
|
|
+ card.append(heading, primary, meta);
|
|
|
+ return card;
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderDailyOverview(data) {
|
|
|
+ $overviewGrid.replaceChildren();
|
|
|
+ const sleep = data.sleep || null;
|
|
|
+ const heartRate = data.heart_rate || null;
|
|
|
+ const stress = data.stress || null;
|
|
|
+ const hrv = data.hrv || null;
|
|
|
+ const activity = data.activity || null;
|
|
|
+ const intensity = data.intensity || null;
|
|
|
+ const device = data.device || null;
|
|
|
+ const respiration = data.respiration || null;
|
|
|
+ const spo2 = data.spo2 || null;
|
|
|
+ const sections = data.available_sections || [];
|
|
|
+ $overviewStatus.classList.toggle('empty', !data.has_data);
|
|
|
+ $overviewStatus.textContent = data.has_data
|
|
|
+ ? data.date + ' · 已导入 ' + sections.map(name => ({sleep:'睡眠', heart_rate:'心率', stress:'压力', hrv:'HRV', activity:'活动', intensity:'强度分钟', device:'静息指标'}[name] || name)).join('、') + ' 数据'
|
|
|
+ : data.date + ' 暂无已导入的健康数据';
|
|
|
+
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '睡眠(按起床日)', sleep ? formatOverviewDuration(sleep.duration_min) : '--', '',
|
|
|
+ sleep ? [
|
|
|
+ {text: sleep.score != null ? '评分 ' + sleep.score : '未提供睡眠评分'},
|
|
|
+ /* 主数值 = 躺床 − 清醒,两者都来自文件里明写的 sleep start/stop 事件与
|
|
|
+ METRICS 的清醒分钟,与 Garmin Connect 的「睡眠时长」逐日精确一致。
|
|
|
+ 不要再用深/浅/REM 累加当主数值:那条分期时间线是设备端粗分期,实测
|
|
|
+ 每晚少报 13~144 分钟。 */
|
|
|
+ {text: sleep.time_in_bed_min != null ? '卧床 ' + formatOverviewDuration(sleep.time_in_bed_min) + '(清醒 ' + Math.round(sleep.awake_min || 0) + ' 分钟)' : ''},
|
|
|
+ {text: sleep.restlessness != null ? '不安稳 ' + sleep.restlessness : ''},
|
|
|
+ {text: sleep.night_avg_hr != null ? '夜间心率 ' + formatOverviewValue(sleep.night_avg_hr, 1) + ' bpm(最低 ' + formatOverviewValue(sleep.night_min_hr) + ')' : ''},
|
|
|
+ {text: sleep.bed_start_local ? formatOverviewTime(sleep.bed_start_local) + ' - ' + formatOverviewTime(sleep.bed_end_local) : (sleep.coverage_start ? formatOverviewTime(sleep.coverage_start) + ' - ' + formatOverviewTime(sleep.coverage_end) : '')},
|
|
|
+ /* 粗分期照旧展示,但必须写明是手表自己分的,否则用户会拿它跟 Connect
|
|
|
+ 对不上而以为哪边坏了。 */
|
|
|
+ {text: sleep.device_stage_deep_min != null ? '手表粗分期:深睡 ' + Math.round(sleep.device_stage_deep_min) + ' / REM ' + Math.round(sleep.device_stage_rem_min || 0) + ' 分钟(与 Connect 口径不同)' : ''},
|
|
|
+ {text: sleep.duration_note ? sleep.duration_note : ''},
|
|
|
+ ].filter(item => item.text) : [{text:'该日期未导入睡眠数据', tone:'warn'}]
|
|
|
+ ));
|
|
|
+ /* DATA-18:主数值用重映射后的「昨夜平均」(`last_night_average_ms`),不再
|
|
|
+ 用 fitfile 那个同名却其实是 5 分钟峰值的字段——旧口径会让这张卡片显示 64 ms
|
|
|
+ 而基线写 35-37,看着永远"爆表",与手表自报的 balanced 矛盾。基线区间显示的
|
|
|
+ 是**平衡区** [balanced_lower, balanced_upper],昨夜平均落在其中才叫正常。 */
|
|
|
+ const hrvValue = hrv && (hrv.last_night_average_ms ?? hrv.avg);
|
|
|
+ const hrvBalancedLow = hrv && hrv.baseline_balanced_lower_ms;
|
|
|
+ const hrvBalancedHigh = hrv && hrv.baseline_balanced_upper_ms;
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '恢复与压力', hrvValue != null ? formatOverviewValue(hrvValue, 1) : '--', hrvValue != null ? 'ms 昨夜平均 HRV' : '',
|
|
|
+ [
|
|
|
+ {text: stress ? '平均压力 ' + formatOverviewValue(stress.avg, 1) : '未导入压力数据'},
|
|
|
+ {text: hrvBalancedLow != null && hrvBalancedHigh != null ? '平衡区 ' + formatOverviewValue(hrvBalancedLow, 0) + '-' + formatOverviewValue(hrvBalancedHigh, 0) + ' ms' : ''},
|
|
|
+ {text: hrv && hrv.weekly_average_ms != null ? '七日平均 ' + formatOverviewValue(hrv.weekly_average_ms, 1) + ' ms' : ''},
|
|
|
+ {text: hrv && hrv.last_night_5min_high_ms != null ? '昨夜 5 分钟峰值 ' + formatOverviewValue(hrv.last_night_5min_high_ms, 1) + ' ms' : ''},
|
|
|
+ {text: hrv && hrv.status ? '状态 ' + hrv.status : ''},
|
|
|
+ ].filter(item => item.text)
|
|
|
+ ));
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '全天心率', heartRate ? formatOverviewValue(heartRate.avg, 1) : '--', heartRate ? 'bpm 平均' : '',
|
|
|
+ heartRate ? [
|
|
|
+ {text:'最低 ' + formatOverviewValue(heartRate.min) + ' bpm'},
|
|
|
+ {text:'最高 ' + formatOverviewValue(heartRate.max) + ' bpm'},
|
|
|
+ {text: heartRate.coverage_start ? '覆盖 ' + formatOverviewTime(heartRate.coverage_start) + ' - ' + formatOverviewTime(heartRate.coverage_end) : ''},
|
|
|
+ ].filter(item => item.text) : [{text:'该日期未导入心率数据', tone:'warn'}]
|
|
|
+ ));
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '活动', activity && activity.steps != null ? formatOverviewValue(activity.steps) : '--', activity && activity.steps != null ? '步' : '',
|
|
|
+ activity ? [
|
|
|
+ {text: activity.distance_m != null ? '距离 ' + formatOverviewValue(activity.distance_m / 1000, 2) + ' km' : ''},
|
|
|
+ {text: activity.active_calories != null ? '活动消耗 ' + formatOverviewValue(activity.active_calories) + ' kcal' : ''},
|
|
|
+ /* 静态消耗现在优先用手表算的静息代谢率(monitoring_info.resting_metabolic_rate);
|
|
|
+ 以前那个字段读错了位置,这一行 16 天全是"请补充年龄和性别后估算"。 */
|
|
|
+ {text: activity.resting_calories != null
|
|
|
+ ? '静态消耗 ' + formatOverviewValue(activity.resting_calories) + ' kcal'
|
|
|
+ + (device && device.resting_metabolic_rate != null ? '(手表静息代谢率)' : '')
|
|
|
+ : '静态消耗:该日期未导入手表静息代谢率'},
|
|
|
+ {text: activity.total_calories != null ? '总消耗 ' + formatOverviewValue(activity.total_calories) + ' kcal' : ''},
|
|
|
+ {text: activity.active_time_min != null ? '活动 ' + formatOverviewValue(activity.active_time_min) + ' 分钟' : ''},
|
|
|
+ ].filter(item => item.text) : [{text:'该日期未导入活动数据', tone:'warn'}]
|
|
|
+ ));
|
|
|
+ /* 强度分钟:Garmin / WHO 的每周 150 分钟目标口径,高强度按双倍计入。 */
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '强度分钟', intensity ? formatOverviewValue(intensity.intensity_minutes, 0) : '--', intensity ? '分钟(高强度双倍)' : '',
|
|
|
+ intensity ? [
|
|
|
+ {text: intensity.moderate_min != null ? '中等强度 ' + formatOverviewValue(intensity.moderate_min, 0) + ' 分钟' : ''},
|
|
|
+ {text: intensity.vigorous_min != null ? '高强度 ' + formatOverviewValue(intensity.vigorous_min, 0) + ' 分钟' : ''},
|
|
|
+ {text: 'WHO 建议每周 150 分钟'},
|
|
|
+ ].filter(item => item.text) : [{text:'该日期未导入强度分钟数据', tone:'warn'}]
|
|
|
+ ));
|
|
|
+ /* 静息心率是从 Garmin 私有消息逆向出来的,标注清楚它的来源与不确定性。 */
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '静息指标', device && device.resting_heart_rate != null ? formatOverviewValue(device.resting_heart_rate) : '--',
|
|
|
+ device && device.resting_heart_rate != null ? 'bpm 静息心率' : '',
|
|
|
+ device ? [
|
|
|
+ {text: device.resting_heart_rate_baseline != null ? '基线 ' + formatOverviewValue(device.resting_heart_rate_baseline) + ' bpm' : ''},
|
|
|
+ {text: device.resting_metabolic_rate != null ? '静息代谢率 ' + formatOverviewValue(device.resting_metabolic_rate) + ' kcal/天' : ''},
|
|
|
+ {text: device.utc_offset_minutes != null ? '设备时区 UTC' + (device.utc_offset_minutes >= 0 ? '+' : '') + (device.utc_offset_minutes / 60) : ''},
|
|
|
+ {text: device.resting_heart_rate != null ? '静息心率来自手表私有字段,非官方接口' : ''},
|
|
|
+ ].filter(item => item.text) : [{text:'该日期未导入静息指标', tone:'warn'}]
|
|
|
+ ));
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '血氧饱和度', spo2 ? formatOverviewValue(spo2.avg, 1) : '--', spo2 ? '%' : '',
|
|
|
+ spo2 ? [
|
|
|
+ {text:'最低 ' + formatOverviewValue(spo2.min, 1) + '%'},
|
|
|
+ {text:'最高 ' + formatOverviewValue(spo2.max, 1) + '%'},
|
|
|
+ {text:'采样 ' + spo2.samples + ' 次'},
|
|
|
+ ] : [{text:'该日期未导入血氧数据', tone:'warn'}]
|
|
|
+ ));
|
|
|
+ $overviewGrid.appendChild(createOverviewCard(
|
|
|
+ '呼吸频率', respiration ? formatOverviewValue(respiration.avg, 1) : '--', respiration ? 'brpm 平均' : '',
|
|
|
+ respiration ? [
|
|
|
+ {text:'最低 ' + formatOverviewValue(respiration.min, 1)},
|
|
|
+ {text:'最高 ' + formatOverviewValue(respiration.max, 1)},
|
|
|
+ {text:'采样 ' + respiration.samples + ' 次'},
|
|
|
+ ] : [{text:'该日期未导入呼吸数据', tone:'warn'}]
|
|
|
+ ));
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadDailyOverview(day = '') {
|
|
|
+ $overviewStatus.classList.remove('empty');
|
|
|
+ $overviewStatus.textContent = '正在加载健康数据…';
|
|
|
+ try {
|
|
|
+ const response = await fetch('/health/overview' + (day ? '?day=' + encodeURIComponent(day) : ''));
|
|
|
+ const data = await response.json();
|
|
|
+ if (!response.ok || data.error) throw new Error(data.error || '健康总览加载失败');
|
|
|
+ $overviewDate.value = data.date;
|
|
|
+ renderDailyOverview(data);
|
|
|
+ } catch (error) {
|
|
|
+ $overviewGrid.replaceChildren();
|
|
|
+ $overviewStatus.classList.add('empty');
|
|
|
+ $overviewStatus.textContent = error.message || '健康总览加载失败';
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function openHealthOverview() {
|
|
|
+ $healthModal.classList.add('show');
|
|
|
+ $healthModal.setAttribute('aria-hidden', 'false');
|
|
|
+ document.body.style.overflow = 'hidden';
|
|
|
+ loadDailyOverview();
|
|
|
+ }
|
|
|
+
|
|
|
+ function closeHealthOverview() {
|
|
|
+ $healthModal.classList.remove('show');
|
|
|
+ $healthModal.setAttribute('aria-hidden', 'true');
|
|
|
+ document.body.style.overflow = '';
|
|
|
+ $overviewButton.focus();
|
|
|
+ }
|
|
|
+
|
|
|
+ function changeOverviewDay(offset) {
|
|
|
+ if (!$overviewDate.value) return;
|
|
|
+ const target = new Date($overviewDate.value + 'T00:00:00');
|
|
|
+ target.setDate(target.getDate() + offset);
|
|
|
+ const localDay = target.getFullYear() + '-'
|
|
|
+ + String(target.getMonth() + 1).padStart(2, '0') + '-'
|
|
|
+ + String(target.getDate()).padStart(2, '0');
|
|
|
+ loadDailyOverview(localDay);
|
|
|
+ }
|
|
|
+
|
|
|
+ /* BUG-09:同一天再次打开表单时载入已有记录,让用户看到的是「编辑」而不是
|
|
|
+ 一张空表。后端已按日期 upsert 且按字段合并,所以不预填也不会丢数据;但
|
|
|
+ 用户看着空表填写,会以为自己在覆盖,无从知道今天已经记过什么。 */
|
|
|
+ function mealNumber(value, maximum, integer = false) {
|
|
|
+ const numeric = Number(value);
|
|
|
+ if (!Number.isFinite(numeric)) return 0;
|
|
|
+ const safe = Math.max(0, Math.min(maximum, numeric));
|
|
|
+ return integer ? Math.round(safe) : Math.round(safe * 10) / 10;
|
|
|
+ }
|
|
|
+
|
|
|
+ function updateMealEstimateTotals(meal) {
|
|
|
+ meal.total_kcal = meal.items.reduce((sum, item) => sum + mealNumber(item.calories_kcal, 20000, true), 0);
|
|
|
+ meal.protein_g = Math.round(meal.items.reduce((sum, item) => sum + mealNumber(item.protein_g, 1000), 0) * 10) / 10;
|
|
|
+ meal.carbs_g = Math.round(meal.items.reduce((sum, item) => sum + mealNumber(item.carbs_g, 2000), 0) * 10) / 10;
|
|
|
+ meal.fat_g = Math.round(meal.items.reduce((sum, item) => sum + mealNumber(item.fat_g, 1000), 0) * 10) / 10;
|
|
|
+ if (!meal.range_low_kcal || !meal.range_high_kcal) {
|
|
|
+ meal.range_low_kcal = Math.round(meal.total_kcal * .8);
|
|
|
+ meal.range_high_kcal = Math.round(meal.total_kcal * 1.2);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function normalizeMealEstimate(raw) {
|
|
|
+ if (!raw || !Array.isArray(raw.items) || !raw.items.length) return null;
|
|
|
+ const items = raw.items.slice(0, 12).map(item => ({
|
|
|
+ name: String(item.name || '').trim().slice(0, 80) || '未命名食物',
|
|
|
+ portion: String(item.portion || '').trim().slice(0, 80) || '份量不确定',
|
|
|
+ calories_kcal: mealNumber(item.calories_kcal, 20000, true),
|
|
|
+ protein_g: mealNumber(item.protein_g, 1000),
|
|
|
+ carbs_g: mealNumber(item.carbs_g, 2000),
|
|
|
+ fat_g: mealNumber(item.fat_g, 1000),
|
|
|
+ }));
|
|
|
+ const source = ['food_photo_estimate', 'manual_nutrition', 'text_nutrition', 'manual_meal'].includes(raw.source) ? raw.source : 'food_photo_estimate';
|
|
|
+ const meal = {
|
|
|
+ source, items, meal_slot: String(raw.meal_slot || ''), photographed_at: String(raw.photographed_at || ''),
|
|
|
+ total_kcal: mealNumber(raw.total_kcal, 20000, true),
|
|
|
+ protein_g: mealNumber(raw.protein_g, 1000), carbs_g: mealNumber(raw.carbs_g, 2000), fat_g: mealNumber(raw.fat_g, 1000),
|
|
|
+ range_low_kcal: mealNumber(raw.range_low_kcal, 20000, true), range_high_kcal: mealNumber(raw.range_high_kcal, 20000, true),
|
|
|
+ confidence: ['low', 'medium', 'high'].includes(raw.confidence) ? raw.confidence : 'low',
|
|
|
+ assumptions: Array.isArray(raw.assumptions) ? raw.assumptions.map(item => String(item).slice(0, 160)).slice(0, 6) : [],
|
|
|
+ user_confirmed: Boolean(raw.user_confirmed),
|
|
|
+ analysis_token: String(raw.analysis_token || '').slice(0, 200),
|
|
|
+ applied_to_form: Boolean(raw.applied_to_form),
|
|
|
+ };
|
|
|
+ updateMealEstimateTotals(meal);
|
|
|
+ return meal;
|
|
|
+ }
|
|
|
+
|
|
|
+ function mealSummary(meal) {
|
|
|
+ return '合计:' + meal.total_kcal + ' kcal;蛋白质 ' + meal.protein_g + ' g;碳水 ' + meal.carbs_g + ' g;脂肪 ' + meal.fat_g + ' g';
|
|
|
+ }
|
|
|
+
|
|
|
+ function mealNutritionTotals(meal) {
|
|
|
+ return {calories_kcal: meal.total_kcal, protein_g: meal.protein_g, carbs_g: meal.carbs_g, fat_g: meal.fat_g};
|
|
|
+ }
|
|
|
+
|
|
|
+ function applyMealNutritionDelta(before, after) {
|
|
|
+ [['calories_kcal', 20000, true], ['protein_g', 1000, false], ['carbs_g', 2000, false], ['fat_g', 1000, false]].forEach(([field, maximum, integer]) => {
|
|
|
+ const current = $checkinForm.elements[field].value;
|
|
|
+ const base = current === '' ? 0 : mealNumber(current, maximum, integer);
|
|
|
+ $checkinForm.elements[field].value = mealNumber(base + (after[field] || 0) - (before[field] || 0), maximum, integer);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderMealEstimates() {
|
|
|
+ const hasMeals = pendingMealEstimates.length > 0;
|
|
|
+ $mealEstimateSection.hidden = !hasMeals;
|
|
|
+ $mealEstimates.hidden = !hasMeals;
|
|
|
+ $mealEstimates.replaceChildren();
|
|
|
+ pendingMealEstimates.forEach((meal, mealIndex) => {
|
|
|
+ const panel = document.createElement('section'); panel.className = 'meal-estimate';
|
|
|
+ const head = document.createElement('div'); head.className = 'meal-estimate-head';
|
|
|
+ const sourceLabel = {food_photo_estimate:'照片估算', manual_nutrition:'手动营养', text_nutrition:'文字营养', manual_meal:'手动餐次'}[meal.source] || '营养记录';
|
|
|
+ const title = document.createElement('strong'); title.textContent = sourceLabel + ' ' + (mealIndex + 1);
|
|
|
+ const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '移除';
|
|
|
+ remove.addEventListener('click', () => {
|
|
|
+ if (meal.applied_to_form) applyMealNutritionDelta(mealNutritionTotals(meal), {});
|
|
|
+ pendingMealEstimates.splice(mealIndex, 1); renderMealEstimates();
|
|
|
+ });
|
|
|
+ head.append(title, remove); panel.appendChild(head);
|
|
|
+ const meta = document.createElement('div'); meta.className = 'meal-estimate-meta';
|
|
|
+ meta.textContent = meal.source === 'food_photo_estimate'
|
|
|
+ ? '可信度:' + ({low:'低', medium:'中', high:'高'}[meal.confidence]) + ';热量范围:'
|
|
|
+ + meal.range_low_kcal + '-' + meal.range_high_kcal + ' kcal'
|
|
|
+ + (meal.assumptions.length ? ';假设:' + meal.assumptions.join(';') : '')
|
|
|
+ : '可直接编辑本组的食物、份量和营养数据';
|
|
|
+ panel.appendChild(meta);
|
|
|
+ const columns = [
|
|
|
+ ['name', '食物'], ['portion', '份量'], ['calories_kcal', '热量 (kcal)'],
|
|
|
+ ['protein_g', '蛋白质 (g)'], ['carbs_g', '碳水 (g)'], ['fat_g', '脂肪 (g)'],
|
|
|
+ ];
|
|
|
+ const columnHeader = document.createElement('div');
|
|
|
+ columnHeader.className = 'meal-item-grid meal-item-header';
|
|
|
+ columns.forEach(([, label]) => {
|
|
|
+ const heading = document.createElement('span'); heading.textContent = label; columnHeader.appendChild(heading);
|
|
|
+ });
|
|
|
+ panel.appendChild(columnHeader);
|
|
|
+ meal.items.forEach(item => {
|
|
|
+ const grid = document.createElement('div'); grid.className = 'meal-item-grid';
|
|
|
+ [['name', '食物', 'text', 0], ['portion', '份量', 'text', 0], ['calories_kcal', '热量 (kcal)', 'number', 1], ['protein_g', '蛋白质 (g)', 'number', .1], ['carbs_g', '碳水 (g)', 'number', .1], ['fat_g', '脂肪 (g)', 'number', .1]].forEach(([field, label, type, step]) => {
|
|
|
+ const input = document.createElement('input'); input.type = type; input.value = item[field]; input.placeholder = label; input.setAttribute('aria-label', label);
|
|
|
+ if (type === 'number') { input.min = '0'; input.step = String(step); }
|
|
|
+ input.addEventListener('input', () => {
|
|
|
+ const before = mealNutritionTotals(meal);
|
|
|
+ item[field] = type === 'number' ? mealNumber(input.value, field === 'calories_kcal' ? 20000 : field === 'carbs_g' ? 2000 : 1000, field === 'calories_kcal') : input.value.slice(0, 80);
|
|
|
+ updateMealEstimateTotals(meal);
|
|
|
+ if (meal.applied_to_form) applyMealNutritionDelta(before, mealNutritionTotals(meal));
|
|
|
+ summary.textContent = mealSummary(meal);
|
|
|
+ });
|
|
|
+ grid.appendChild(input);
|
|
|
+ });
|
|
|
+ panel.appendChild(grid);
|
|
|
+ });
|
|
|
+ const summary = document.createElement('div'); summary.className = 'meal-estimate-summary'; summary.textContent = mealSummary(meal); panel.appendChild(summary);
|
|
|
+ if (meal.confidence === 'low') {
|
|
|
+ const confirmation = document.createElement('label'); confirmation.className = 'meal-confirm';
|
|
|
+ const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = meal.user_confirmed;
|
|
|
+ checkbox.addEventListener('change', () => { meal.user_confirmed = checkbox.checked; });
|
|
|
+ confirmation.append(checkbox, document.createTextNode('我已查看不确定因素,仍要保存这条低可信度估算'));
|
|
|
+ panel.appendChild(confirmation);
|
|
|
+ }
|
|
|
+ $mealEstimates.appendChild(panel);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function addMealEstimateNutritionToForm(meal) {
|
|
|
+ [['calories_kcal', meal.total_kcal, 20000, true], ['protein_g', meal.protein_g, 1000, false], ['carbs_g', meal.carbs_g, 2000, false], ['fat_g', meal.fat_g, 1000, false]].forEach(([field, amount, maximum, integer]) => {
|
|
|
+ const current = $checkinForm.elements[field].value;
|
|
|
+ const existing = current === '' ? 0 : mealNumber(current, maximum, integer);
|
|
|
+ $checkinForm.elements[field].value = mealNumber(existing + amount, maximum, integer);
|
|
|
+ });
|
|
|
+ meal.applied_to_form = true;
|
|
|
+ }
|
|
|
+
|
|
|
+ function addManualNutritionRecord() {
|
|
|
+ const mealSlot = window.prompt('餐次(早餐/午餐/晚餐/加餐)', '晚餐');
|
|
|
+ if (mealSlot === null) return;
|
|
|
+ const meal = normalizeMealEstimate({
|
|
|
+ source:'manual_meal', meal_slot:mealSlot.trim(), confidence:'high', user_confirmed:true,
|
|
|
+ items:[{name:'手动记录', portion:'未记录', calories_kcal:0, protein_g:0, carbs_g:0, fat_g:0}],
|
|
|
+ total_kcal:0, protein_g:0, carbs_g:0, fat_g:0,
|
|
|
+ range_low_kcal:0, range_high_kcal:0, assumptions:[], applied_to_form:true,
|
|
|
+ });
|
|
|
+ if (!meal) return;
|
|
|
+ pendingMealEstimates.push(meal);
|
|
|
+ renderMealEstimates();
|
|
|
+ $mealEstimates.lastElementChild?.scrollIntoView({behavior:'smooth', block:'nearest'});
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadCheckinInto(day) {
|
|
|
+ const data = await dataRequest('/data/checkins/' + encodeURIComponent(day));
|
|
|
+ if (data.error) {
|
|
|
+ $checkinHint.textContent = '读取 ' + day + ' 的每日记录失败:' + data.error;
|
|
|
+ $checkinHint.classList.add('show');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const checkin = data.checkin;
|
|
|
+ if (!checkin) {
|
|
|
+ $checkinHint.textContent = '';
|
|
|
+ $checkinHint.classList.remove('show');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ Object.entries(checkin).forEach(([key, value]) => {
|
|
|
+ loadedCheckinFields.add(key);
|
|
|
+ if (key === 'meal_estimates') {
|
|
|
+ pendingMealEstimates = Array.isArray(value) ? value.map(item => normalizeMealEstimate({...item, applied_to_form:true})).filter(Boolean) : [];
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const field = $checkinForm.elements[key];
|
|
|
+ if (!field) return;
|
|
|
+ if (field.type === 'checkbox') field.checked = Boolean(value);
|
|
|
+ else field.value = value;
|
|
|
+ });
|
|
|
+ $checkinHint.textContent = '已载入 ' + day + ' 的记录,保存将更新这一条(留空的字段保持不变)。';
|
|
|
+ renderMealEstimates();
|
|
|
+ $checkinHint.classList.add('show');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function openCheckin(date = '') {
|
|
|
+ $checkinForm.reset();
|
|
|
+ loadedCheckinFields = new Set();
|
|
|
+ pendingMealEstimates = [];
|
|
|
+ renderMealEstimates();
|
|
|
+ const day = date || localDateISO();
|
|
|
+ document.getElementById('checkin-date').value = day;
|
|
|
+ $checkinHint.textContent = '';
|
|
|
+ $checkinHint.classList.remove('show');
|
|
|
+ $checkinModal.classList.add('show');
|
|
|
+ $checkinModal.setAttribute('aria-hidden', 'false');
|
|
|
+ document.body.style.overflow = 'hidden';
|
|
|
+ await loadCheckinInto(day);
|
|
|
+ }
|
|
|
+
|
|
|
+ function closeCheckin() {
|
|
|
+ $checkinModal.classList.remove('show');
|
|
|
+ $checkinModal.setAttribute('aria-hidden', 'true');
|
|
|
+ document.body.style.overflow = '';
|
|
|
+ pendingMealEstimates = [];
|
|
|
+ renderMealEstimates();
|
|
|
+ $checkinButton.focus();
|
|
|
+ }
|
|
|
+
|
|
|
+ async function submitCheckin(event) {
|
|
|
+ event.preventDefault();
|
|
|
+ if (checkinSubmitting) return;
|
|
|
+ if (pendingMealEstimates.some(meal => meal.confidence === 'low' && !meal.user_confirmed)) {
|
|
|
+ window.alert('Please confirm or remove every low-confidence meal estimate.');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const formData = new FormData($checkinForm);
|
|
|
+ const payload = {};
|
|
|
+ formData.forEach((value, key) => { if (value !== '') payload[key] = value; });
|
|
|
+ ['weight_kg','energy_level','fatigue_level','pain_level','sleep_quality','calories_kcal','protein_g','carbs_g','fat_g','training_rpe','training_completion_pct','note'].forEach(key => {
|
|
|
+ if (loadedCheckinFields.has(key) && String($checkinForm.elements[key]?.value || '').trim() === '') payload[key] = null;
|
|
|
+ });
|
|
|
+ payload.cheat_meal = $checkinForm.elements.cheat_meal.checked;
|
|
|
+ payload.meal_estimates = pendingMealEstimates;
|
|
|
+ const actualInputs = Object.entries(payload).filter(([key, value]) =>
|
|
|
+ key !== 'date' && value !== null && value !== ''
|
|
|
+ && !(key === 'cheat_meal' && value === false)
|
|
|
+ && !(key === 'meal_estimates' && Array.isArray(value) && value.length === 0)
|
|
|
+ );
|
|
|
+ if (!actualInputs.length) {
|
|
|
+ window.alert('请至少填写一项每日记录。');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (pendingMealEstimates.length) {
|
|
|
+ const grouped = pendingMealEstimates.reduce((sum, meal) => ({
|
|
|
+ calories_kcal:sum.calories_kcal + meal.total_kcal,
|
|
|
+ protein_g:sum.protein_g + meal.protein_g,
|
|
|
+ carbs_g:sum.carbs_g + meal.carbs_g,
|
|
|
+ fat_g:sum.fat_g + meal.fat_g,
|
|
|
+ }), {calories_kcal:0, protein_g:0, carbs_g:0, fat_g:0});
|
|
|
+ const inconsistent = [
|
|
|
+ ['calories_kcal', '热量', .5], ['protein_g', '蛋白质', .05],
|
|
|
+ ['carbs_g', '碳水', .05], ['fat_g', '脂肪', .05],
|
|
|
+ ].find(([field, , tolerance]) => {
|
|
|
+ const total = Number($checkinForm.elements[field].value);
|
|
|
+ return !Number.isFinite(total) || Math.abs(total - grouped[field]) > tolerance;
|
|
|
+ });
|
|
|
+ if (inconsistent) {
|
|
|
+ window.alert(inconsistent[1] + '合计与营养组明细不一致,请修改营养组或合计后再保存。');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ checkinSubmitting = true;
|
|
|
+ const submitButton = $checkinForm.querySelector('[type="submit"]');
|
|
|
+ submitButton.disabled = true;
|
|
|
+ let response;
|
|
|
+ let data;
|
|
|
+ try {
|
|
|
+ response = await fetch('/data/checkins', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload),
|
|
|
+ });
|
|
|
+ data = await response.json().catch(() => ({}));
|
|
|
+ } catch (error) {
|
|
|
+ window.alert('\u6bcf\u65e5\u8bb0\u5f55\u4fdd\u5b58\u5931\u8d25\uff1a' + (error.message || '\u7f51\u7edc\u5f02\u5e38'));
|
|
|
+ checkinSubmitting = false;
|
|
|
+ submitButton.disabled = false;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (!response.ok || data.error) {
|
|
|
+ window.alert(data.error || '\u6bcf\u65e5\u8bb0\u5f55\u4fdd\u5b58\u5931\u8d25');
|
|
|
+ checkinSubmitting = false;
|
|
|
+ submitButton.disabled = false;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ closeCheckin();
|
|
|
+ // BUG-09:同一天再次保存是更新而不是新增,说清楚是哪一种,否则用户无从判断
|
|
|
+ // 自己刚才是不是又加了一条。folded_duplicates 只在折叠掉旧缺陷留下的重复
|
|
|
+ // 记录时才有。
|
|
|
+ addNotify(
|
|
|
+ (data.created ? '已保存 ' : '已更新 ') + (data.date || '') + ' 的每日记录。'
|
|
|
+ + (data.notice || ''),
|
|
|
+ 'notify-saved',
|
|
|
+ );
|
|
|
+ if ($dataModal.classList.contains('show')) await loadDataOverview();
|
|
|
+ if ($healthModal.classList.contains('show')) await loadDailyOverview($overviewDate.value);
|
|
|
+ checkinSubmitting = false;
|
|
|
+ submitButton.disabled = false;
|
|
|
+ }
|
|
|
+
|
|
|
+ function svgNode(name, attrs = {}) {
|
|
|
+ const node = document.createElementNS('http://www.w3.org/2000/svg', name);
|
|
|
+ Object.entries(attrs).forEach(([key, value]) => node.setAttribute(key, String(value)));
|
|
|
+ return node;
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderTrendChart(items, metric) {
|
|
|
+ $trendChart.replaceChildren();
|
|
|
+ $trendChart.setAttribute('viewBox', '0 0 360 180');
|
|
|
+ items = (items || []).filter(item => Number.isFinite(Number(item.value)));
|
|
|
+ const width = 360, height = 180, left = 34, right = 10, top = 12, bottom = 28;
|
|
|
+ const chartWidth = width - left - right, chartHeight = height - top - bottom;
|
|
|
+ if (!items.length) {
|
|
|
+ const empty = svgNode('text', {x: width / 2, y: height / 2, class: 'trend-empty'});
|
|
|
+ empty.textContent = '此时间范围暂无' + trendMetricLabels[metric] + '数据';
|
|
|
+ $trendChart.appendChild(empty);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const values = items.map(item => Number(item.value)).filter(Number.isFinite);
|
|
|
+ const rawMin = Math.min(...values), rawMax = Math.max(...values);
|
|
|
+ const padding = rawMin === rawMax ? Math.max(1, rawMin * 0.08) : (rawMax - rawMin) * 0.12;
|
|
|
+ const min = Math.max(0, rawMin - padding), max = rawMax + padding;
|
|
|
+ const yFor = value => top + (max - value) / (max - min || 1) * chartHeight;
|
|
|
+ const xFor = index => left + (items.length === 1 ? chartWidth / 2 : index / (items.length - 1) * chartWidth);
|
|
|
+
|
|
|
+ for (let index = 0; index < 3; index++) {
|
|
|
+ const y = top + index * chartHeight / 2;
|
|
|
+ const value = max - index * (max - min) / 2;
|
|
|
+ $trendChart.appendChild(svgNode('line', {x1:left, y1:y, x2:width-right, y2:y, class:'trend-grid'}));
|
|
|
+ const label = svgNode('text', {x:left - 5, y:y + 3, class:'trend-axis', 'text-anchor':'end'});
|
|
|
+ label.textContent = value.toFixed(metric === 'spo2' ? 1 : 0);
|
|
|
+ $trendChart.appendChild(label);
|
|
|
+ }
|
|
|
+ const points = items.map((item, index) => [xFor(index), yFor(Number(item.value))]);
|
|
|
+ const linePath = points.map((point, index) => (index ? 'L' : 'M') + point[0].toFixed(1) + ' ' + point[1].toFixed(1)).join(' ');
|
|
|
+ const areaPath = linePath + ' L' + points[points.length - 1][0].toFixed(1) + ' ' + (height-bottom) + ' L' + points[0][0].toFixed(1) + ' ' + (height-bottom) + ' Z';
|
|
|
+ $trendChart.append(svgNode('path', {d:areaPath, class:'trend-area'}), svgNode('path', {d:linePath, class:'trend-line'}));
|
|
|
+ const labelIndexes = Array.from(new Set([0, Math.floor((items.length - 1) / 2), items.length - 1]));
|
|
|
+ points.forEach((point, index) => {
|
|
|
+ const circle = svgNode('circle', {cx:point[0], cy:point[1], r:3, class:'trend-point'});
|
|
|
+ const title = svgNode('title'); title.textContent = items[index].label + ': ' + items[index].value;
|
|
|
+ circle.appendChild(title); $trendChart.appendChild(circle);
|
|
|
+ if (labelIndexes.includes(index)) {
|
|
|
+ const label = svgNode('text', {x:point[0], y:height - 8, class:'trend-axis', 'text-anchor':'middle'});
|
|
|
+ label.textContent = trendPeriod === 'day' ? items[index].label : items[index].label.slice(5);
|
|
|
+ $trendChart.appendChild(label);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ async function refreshHealthTrend(useSelectedDate = true) {
|
|
|
+ const params = new URLSearchParams({metric:$trendMetric.value, period:trendPeriod});
|
|
|
+ if (useSelectedDate && $trendDate.value) params.set('end_date', $trendDate.value);
|
|
|
+ $trendSummary.textContent = '正在加载健康数据…';
|
|
|
+ try {
|
|
|
+ const response = await fetch('/health/trend?' + params.toString());
|
|
|
+ const data = await response.json();
|
|
|
+ if (!response.ok || data.error) throw new Error(data.error || '健康趋势加载失败');
|
|
|
+ $trendDate.value = data.end_date;
|
|
|
+ const items = (data.items || []).filter(item => Number.isFinite(Number(item.value)));
|
|
|
+ renderTrendChart(items, data.metric);
|
|
|
+ const unit = data.unit ? ' ' + data.unit : '';
|
|
|
+ if (!items.length) {
|
|
|
+ $trendSummary.textContent = data.start_date + ' 至 ' + data.end_date;
|
|
|
+ } else if (data.cumulative) {
|
|
|
+ /* 日视图下总消耗热量是**累计曲线**:取平均没有意义(那会得到"半天的量"),
|
|
|
+ 所以报当日累计到最后一个数据点的值,并说明静息部分是按日速率摊的。 */
|
|
|
+ const last = items[items.length - 1];
|
|
|
+ $trendSummary.textContent = data.end_date + ' · 截至 ' + last.label + ' 累计 '
|
|
|
+ + Number(last.value).toFixed(0) + unit
|
|
|
+ + '(静息 ' + Number(last.resting_calories).toFixed(0)
|
|
|
+ + ' + 活动 ' + Number(last.active_calories).toFixed(0) + ',静息按日速率均摊)';
|
|
|
+ } else {
|
|
|
+ const values = items.map(item => Number(item.value));
|
|
|
+ const average = values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
|
+ $trendSummary.textContent = data.start_date + ' 至 ' + data.end_date + ' · 平均 '
|
|
|
+ + average.toFixed(1) + unit + ' · ' + items.length + ' 个数据点';
|
|
|
+ }
|
|
|
+ } catch (error) {
|
|
|
+ $trendSummary.textContent = error.message || '健康趋势加载失败';
|
|
|
+ renderTrendChart([], $trendMetric.value);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ document.querySelectorAll('.trend-period').forEach(button => button.addEventListener('click', () => {
|
|
|
+ trendPeriod = button.dataset.period;
|
|
|
+ document.querySelectorAll('.trend-period').forEach(item => item.classList.toggle('active', item === button));
|
|
|
+ refreshHealthTrend();
|
|
|
+ }));
|
|
|
+ $trendMetric.addEventListener('change', () => refreshHealthTrend());
|
|
|
+ $trendDate.addEventListener('change', () => refreshHealthTrend());
|
|
|
+
|
|
|
+ function setMessageHeight(height) {
|
|
|
+ const boundedHeight = Math.max(72, Math.min(360, Math.round(height)));
|
|
|
+ $form.style.setProperty('--message-height', boundedHeight + 'px');
|
|
|
+ }
|
|
|
+
|
|
|
+ $messageResizer.addEventListener('pointerdown', event => {
|
|
|
+ if (sessionEnded) return;
|
|
|
+ messageResizeStart = { y:event.clientY, height:$msg.getBoundingClientRect().height };
|
|
|
+ $messageResizer.classList.add('dragging');
|
|
|
+ $messageResizer.setPointerCapture(event.pointerId);
|
|
|
+ event.preventDefault();
|
|
|
+ });
|
|
|
+ $messageResizer.addEventListener('pointermove', event => {
|
|
|
+ if (!messageResizeStart) return;
|
|
|
+ setMessageHeight(messageResizeStart.height + messageResizeStart.y - event.clientY);
|
|
|
+ });
|
|
|
+ function endMessageResize() {
|
|
|
+ messageResizeStart = null;
|
|
|
+ $messageResizer.classList.remove('dragging');
|
|
|
+ }
|
|
|
+ $messageResizer.addEventListener('pointerup', endMessageResize);
|
|
|
+ $messageResizer.addEventListener('pointercancel', endMessageResize);
|
|
|
+
|
|
|
+ function applyLayout(workoutWidth) {
|
|
|
+ if (window.matchMedia(LAYOUT_BREAKPOINT).matches) return;
|
|
|
+ const available = $mainGrid.clientWidth - 16;
|
|
|
+ if (available <= MIN_CHAT_WIDTH + MIN_WORKOUT_WIDTH) return;
|
|
|
+ const clampedWorkout = Math.max(
|
|
|
+ MIN_WORKOUT_WIDTH,
|
|
|
+ Math.min(Number(workoutWidth) || DEFAULT_WORKOUT_WIDTH, available - MIN_CHAT_WIDTH)
|
|
|
+ );
|
|
|
+ const chatWidth = available - clampedWorkout;
|
|
|
+ $mainGrid.style.setProperty('--chat-width', chatWidth + 'px');
|
|
|
+ $mainGrid.style.setProperty('--workout-width', clampedWorkout + 'px');
|
|
|
+ $layoutResizer.setAttribute('aria-valuenow', String(Math.round(clampedWorkout)));
|
|
|
+ }
|
|
|
+
|
|
|
+ function savedWorkoutWidth() {
|
|
|
+ try {
|
|
|
+ const saved = JSON.parse(localStorage.getItem(LAYOUT_STORAGE_KEY) || '{}');
|
|
|
+ return Number(saved.workoutWidth) || DEFAULT_WORKOUT_WIDTH;
|
|
|
+ } catch (_) {
|
|
|
+ return DEFAULT_WORKOUT_WIDTH;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function persistLayout() {
|
|
|
+ const workoutWidth = document.querySelector('.sidebar').getBoundingClientRect().width;
|
|
|
+ localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify({ workoutWidth: Math.round(workoutWidth) }));
|
|
|
+ }
|
|
|
+
|
|
|
+ $layoutResizer.addEventListener('pointerdown', (event) => {
|
|
|
+ if (window.matchMedia(LAYOUT_BREAKPOINT).matches) return;
|
|
|
+ event.preventDefault();
|
|
|
+ $layoutResizer.setPointerCapture(event.pointerId);
|
|
|
+ $layoutResizer.classList.add('dragging');
|
|
|
+ });
|
|
|
+
|
|
|
+ $layoutResizer.addEventListener('pointermove', (event) => {
|
|
|
+ if (!$layoutResizer.hasPointerCapture(event.pointerId)) return;
|
|
|
+ const bounds = $mainGrid.getBoundingClientRect();
|
|
|
+ applyLayout(bounds.right - event.clientX - 8);
|
|
|
+ });
|
|
|
+
|
|
|
+ function finishLayoutDrag(event) {
|
|
|
+ if (!$layoutResizer.hasPointerCapture(event.pointerId)) return;
|
|
|
+ $layoutResizer.releasePointerCapture(event.pointerId);
|
|
|
+ $layoutResizer.classList.remove('dragging');
|
|
|
+ persistLayout();
|
|
|
+ }
|
|
|
+ $layoutResizer.addEventListener('pointerup', finishLayoutDrag);
|
|
|
+ $layoutResizer.addEventListener('pointercancel', finishLayoutDrag);
|
|
|
+
|
|
|
+ $layoutResizer.addEventListener('keydown', (event) => {
|
|
|
+ if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
|
|
|
+ event.preventDefault();
|
|
|
+ const current = document.querySelector('.sidebar').getBoundingClientRect().width;
|
|
|
+ applyLayout(current + (event.key === 'ArrowLeft' ? 24 : -24));
|
|
|
+ persistLayout();
|
|
|
+ });
|
|
|
+
|
|
|
+ window.addEventListener('resize', () => applyLayout(savedWorkoutWidth()));
|
|
|
+ requestAnimationFrame(() => applyLayout(savedWorkoutWidth()));
|
|
|
+
|
|
|
+ /* ── utils ─────────────────────────────────────────────────────────── */
|
|
|
+ function removeHint() { if ($hint && $hint.parentNode) $hint.remove(); }
|
|
|
+ function scrollBottom() { $chat.scrollTop = $chat.scrollHeight; }
|
|
|
+
|
|
|
+ function rememberConversation(role, text) {
|
|
|
+ const content = String(text || '').trim();
|
|
|
+ if (!content || (role !== 'user' && role !== 'assistant')) return;
|
|
|
+ sessionConversationHistory.push({ role, text:content });
|
|
|
+ if (sessionConversationHistory.length > SESSION_HISTORY_MAX_ITEMS) {
|
|
|
+ sessionConversationHistory.splice(0, sessionConversationHistory.length - SESSION_HISTORY_MAX_ITEMS);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function esc(s) {
|
|
|
+ return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
|
|
+ }
|
|
|
+
|
|
|
+ function beijingStartFromWorkout(workout) {
|
|
|
+ const segments = workout.sets || [];
|
|
|
+ const active = segments.filter(item => !item.is_rest);
|
|
|
+ const starts = (active.length ? active : segments).map(item => item.start_time).filter(Boolean);
|
|
|
+ if (!starts.length && workout.session && workout.session.start_time) starts.push(workout.session.start_time);
|
|
|
+ if (!starts.length) return null;
|
|
|
+ return starts.map(value => new Date(value)).reduce((earliest, item) => item < earliest ? item : earliest);
|
|
|
+ }
|
|
|
+
|
|
|
+ function formatBeijingTime(date) {
|
|
|
+ if (!date || Number.isNaN(date.getTime())) return '--';
|
|
|
+ return new Intl.DateTimeFormat('zh-CN', {
|
|
|
+ timeZone:'Asia/Shanghai', year:'numeric', month:'2-digit', day:'2-digit',
|
|
|
+ hour:'2-digit', minute:'2-digit', second:'2-digit', hour12:false,
|
|
|
+ }).format(date);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function dataRequest(url, options={}) {
|
|
|
+ try {
|
|
|
+ const response = await fetch(url, options);
|
|
|
+ const data = await response.json().catch(() => ({}));
|
|
|
+ return response.ok ? data : { error:data.error || '操作失败', status:response.status, code:data.code };
|
|
|
+ } catch (error) {
|
|
|
+ return { error:'网络异常:' + error.message };
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function setDataStatus(message='', type='') {
|
|
|
+ const status = document.getElementById('data-status');
|
|
|
+ status.textContent = message;
|
|
|
+ status.className = 'modal-status' + (type ? ' ' + type : '');
|
|
|
+ }
|
|
|
+
|
|
|
+ function applyExternalModelState(enabled) {
|
|
|
+ externalModelsEnabled = Boolean(enabled);
|
|
|
+ $send.disabled = sessionEnded || !externalModelsEnabled;
|
|
|
+ $foodImageButton.disabled = sessionEnded || !externalModelsEnabled;
|
|
|
+ $msg.placeholder = externalModelsEnabled
|
|
|
+ ? '例如:把第2和第3组合并;或:今天卧推 60kg×5组'
|
|
|
+ : '联网模型已关闭;本地健康查询、导入、训练编辑和数据管理仍可使用';
|
|
|
+ if (!externalModelsEnabled && pendingFoodImage) clearPendingFoodImage();
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderExternalModelSettings(settings) {
|
|
|
+ const toggle = document.getElementById('external-models-toggle');
|
|
|
+ const status = document.getElementById('external-models-status');
|
|
|
+ const disclosure = document.getElementById('external-model-disclosure');
|
|
|
+ const localFeatures = document.getElementById('external-model-local-features');
|
|
|
+ const enabled = Boolean(settings.external_models_enabled);
|
|
|
+ toggle.checked = enabled;
|
|
|
+ toggle.disabled = false;
|
|
|
+ status.textContent = enabled
|
|
|
+ ? '已启用:下方列出的数据可能按功能发送到对应的外部服务。'
|
|
|
+ : '已关闭:不会向外部模型发送对话、档案、记忆、训练计划或餐盘照片。';
|
|
|
+ status.className = 'privacy-status' + (enabled ? '' : ' disabled');
|
|
|
+ disclosure.innerHTML = '';
|
|
|
+ (settings.disclosure || []).forEach(item => {
|
|
|
+ const row = document.createElement('div');
|
|
|
+ row.className = 'privacy-disclosure-item';
|
|
|
+ const title = document.createElement('strong');
|
|
|
+ title.textContent = item.name || '外部服务';
|
|
|
+ const text = document.createElement('span');
|
|
|
+ text.textContent = ':' + (item.data || '');
|
|
|
+ row.append(title, text);
|
|
|
+ disclosure.appendChild(row);
|
|
|
+ });
|
|
|
+ const features = settings.local_features || [];
|
|
|
+ localFeatures.textContent = features.length
|
|
|
+ ? '关闭后仍可使用:' + features.join('、') + '。'
|
|
|
+ : '';
|
|
|
+ applyExternalModelState(enabled);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadExternalModelSettings() {
|
|
|
+ const settings = await dataRequest('/settings/external-models');
|
|
|
+ if (settings.error) {
|
|
|
+ setDataStatus('无法读取外部模型设置:' + settings.error, 'error');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ renderExternalModelSettings(settings);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function updateExternalModelSettings(enabled) {
|
|
|
+ const toggle = document.getElementById('external-models-toggle');
|
|
|
+ toggle.disabled = true;
|
|
|
+ const result = await dataRequest('/settings/external-models', {
|
|
|
+ method:'PUT',
|
|
|
+ headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({external_models_enabled:Boolean(enabled)}),
|
|
|
+ });
|
|
|
+ if (result.error) {
|
|
|
+ toggle.checked = externalModelsEnabled;
|
|
|
+ toggle.disabled = false;
|
|
|
+ setDataStatus(result.error, 'error');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ renderExternalModelSettings(result);
|
|
|
+ setDataStatus(
|
|
|
+ result.external_models_enabled ? '已允许外部模型处理数据' : '已关闭外部模型数据外发',
|
|
|
+ 'success',
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ function formatDataTime(value) {
|
|
|
+ if (!value) return '';
|
|
|
+ const date = new Date(value);
|
|
|
+ return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN');
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderRecords(records) {
|
|
|
+ const list = document.getElementById('records-list');
|
|
|
+ document.getElementById('record-preview').classList.remove('show');
|
|
|
+ document.getElementById('records-count').textContent = records.length + ' 条';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!records.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">暂无已保存训练记录</div>';
|
|
|
+ updateRecordButtons();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ records.forEach(record => {
|
|
|
+ const row = document.createElement('label');
|
|
|
+ row.className = 'data-row';
|
|
|
+ const checkbox = document.createElement('input');
|
|
|
+ checkbox.type = 'checkbox'; checkbox.value = record.id;
|
|
|
+ checkbox.addEventListener('change', updateRecordButtons);
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = (record.date || '未知日期') + ' · ' + (record.sport || '未知运动');
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ const checkin = record.checkin || null;
|
|
|
+ const details = checkin
|
|
|
+ ? [
|
|
|
+ checkin.weight_kg != null ? '体重 ' + checkin.weight_kg + ' kg' : '',
|
|
|
+ checkin.fatigue_level != null ? '疲劳 ' + checkin.fatigue_level + '/10' : '',
|
|
|
+ checkin.training_rpe != null ? 'RPE ' + checkin.training_rpe + '/10' : '',
|
|
|
+ ].filter(Boolean)
|
|
|
+ : [Number(record.total_sets || 0) + ' 组'];
|
|
|
+ if (record.source_file) details.push(record.source_file);
|
|
|
+ meta.textContent = details.join(' · ');
|
|
|
+ main.append(title, meta); row.append(checkbox, main); list.appendChild(row);
|
|
|
+ });
|
|
|
+ updateRecordButtons();
|
|
|
+ }
|
|
|
+
|
|
|
+ function downloadMarkdown(content, filename) {
|
|
|
+ const blob = new Blob([content], { type:'text/markdown;charset=utf-8' });
|
|
|
+ const url = URL.createObjectURL(blob);
|
|
|
+ const anchor = document.createElement('a');
|
|
|
+ anchor.href = url; anchor.download = filename;
|
|
|
+ document.body.appendChild(anchor); anchor.click(); anchor.remove();
|
|
|
+ URL.revokeObjectURL(url);
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderPlans(plans) {
|
|
|
+ const list = document.getElementById('plans-list');
|
|
|
+ document.getElementById('plans-count').textContent = plans.length + ' 条';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!plans.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">暂无已保存训练计划</div>';
|
|
|
+ document.getElementById('delete-plans').disabled = true;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ plans.forEach(plan => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const checkbox = document.createElement('input');
|
|
|
+ checkbox.type = 'checkbox'; checkbox.value = plan.id;
|
|
|
+ checkbox.addEventListener('change', updatePlanDeleteButton);
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title'; title.textContent = plan.title;
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta'; meta.textContent = plan.date + ' · ' + plan.subject + ' · ' + plan.filename + (plan.memo ? ' · 有备忘' : '');
|
|
|
+ const actions = document.createElement('div'); actions.className = 'plan-row-actions';
|
|
|
+ const view = document.createElement('button'); view.type='button'; view.className='small-delete'; view.textContent='查看';
|
|
|
+ const edit = document.createElement('button'); edit.type='button'; edit.className='small-delete'; edit.textContent='编辑';
|
|
|
+ const remove = document.createElement('button'); remove.type='button'; remove.className='small-delete'; remove.textContent='删除';
|
|
|
+ view.addEventListener('click', () => showPlanPreview(plan.id));
|
|
|
+ edit.addEventListener('click', () => editPlanMetadata(plan));
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除训练计划“' + plan.title + '”吗?')) return;
|
|
|
+ const result = await dataRequest('/plans/' + encodeURIComponent(plan.id), {method:'DELETE'});
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('训练计划已删除', 'success'); await loadDataOverview();
|
|
|
+ });
|
|
|
+ actions.append(view, edit, remove); main.append(title, meta, actions); row.append(checkbox, main); list.appendChild(row);
|
|
|
+ });
|
|
|
+ updatePlanDeleteButton();
|
|
|
+ }
|
|
|
+
|
|
|
+ function updatePlanDeleteButton() {
|
|
|
+ const count = document.querySelectorAll('#plans-list input:checked').length;
|
|
|
+ const button = document.getElementById('delete-plans');
|
|
|
+ button.disabled = count === 0;
|
|
|
+ button.textContent = count ? '删除所选计划(' + count + ')' : '删除所选计划';
|
|
|
+ }
|
|
|
+
|
|
|
+ async function showPlanPreview(planId) {
|
|
|
+ const plan = await dataRequest('/plans/' + encodeURIComponent(planId));
|
|
|
+ if (plan.error) return setDataStatus(plan.error, 'error');
|
|
|
+ previewedPlan = plan;
|
|
|
+ document.getElementById('plan-preview-title').textContent = plan.filename;
|
|
|
+ const body = document.getElementById('plan-preview-body');
|
|
|
+ if (window.marked && window.DOMPurify) {
|
|
|
+ body.innerHTML = DOMPurify.sanitize(marked.parse(plan.content), {USE_PROFILES:{html:true}, FORBID_TAGS:['style','form','input','button','textarea']});
|
|
|
+ } else body.textContent = plan.content;
|
|
|
+ if (plan.memo) {
|
|
|
+ const memo = document.createElement('p');
|
|
|
+ memo.className = 'profile-summary';
|
|
|
+ memo.textContent = '计划备忘:' + plan.memo;
|
|
|
+ body.prepend(memo);
|
|
|
+ }
|
|
|
+ document.getElementById('plan-preview').classList.add('show');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function editPlanMetadata(plan) {
|
|
|
+ const date = window.prompt('计划日期(YYYY-MM-DD)', plan.date);
|
|
|
+ if (date === null) return;
|
|
|
+ const subject = window.prompt('训练科目', plan.subject);
|
|
|
+ if (subject === null) return;
|
|
|
+ const title = window.prompt('计划标题', plan.title);
|
|
|
+ if (title === null) return;
|
|
|
+ const memo = window.prompt('计划备忘录(训练反馈、偏好、频道或视频链接)', plan.memo || '');
|
|
|
+ if (memo === null) return;
|
|
|
+ const content = window.prompt('计划正文(可直接修改动作、组数、次数和要点)', plan.content || '');
|
|
|
+ if (content === null) return;
|
|
|
+ const result = await dataRequest('/plans/' + encodeURIComponent(plan.id), {
|
|
|
+ method:'PATCH', headers:{'Content-Type':'application/json'}, body:JSON.stringify({date,subject,title,memo,content}),
|
|
|
+ });
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('计划信息已更新:' + result.filename, 'success'); await loadDataOverview();
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderMemories(memories) {
|
|
|
+ const list = document.getElementById('memories-list');
|
|
|
+ document.getElementById('memories-count').textContent = memories.length + ' 条';
|
|
|
+ document.getElementById('clear-memories').disabled = memories.length === 0;
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!memories.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">暂无临时记忆</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const typeLabels = {preference:'偏好', constraint:'限制', plan_decision:'计划决策', training_feedback:'训练反馈'};
|
|
|
+ memories.slice().reverse().forEach(memory => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = memory.summary || '空摘要';
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ const typeLabel = typeLabels[memory.type] || '训练反馈';
|
|
|
+ const memoryFacts = Array.isArray(memory.facts) ? memory.facts : [];
|
|
|
+ const confirmedFactCount = memoryFacts.filter(fact => fact && fact.user_confirmed).length;
|
|
|
+ const confirmation = memoryFacts.length ? (confirmedFactCount + '/' + memoryFacts.length + ' 条事实已确认') : (memory.user_confirmed ? '已确认,可用于对话' : '待确认,不会用于对话');
|
|
|
+ meta.textContent = typeLabel + ' · 重要度 ' + (memory.importance || 1) + '/5 · ' + confirmation
|
|
|
+ + ' · 创建:' + formatDataTime(memory.created_at) + (memory.expires_at ? ' · 到期:' + formatDataTime(memory.expires_at) : ' · 长期保留');
|
|
|
+ let factText = null;
|
|
|
+ const facts = Array.isArray(memory.facts)
|
|
|
+ ? memory.facts.filter(fact => fact && fact.status !== 'rejected')
|
|
|
+ : [];
|
|
|
+ if (facts.length) {
|
|
|
+ factText = document.createElement('div'); factText.className = 'memory-facts';
|
|
|
+ const labels = {
|
|
|
+ 'youtube.avoid_channel':'不优先推荐频道', 'training.avoid_exercise':'避免动作',
|
|
|
+ 'training.prefer_exercise':'优先动作', 'training.max_rpe':'最高 RPE',
|
|
|
+ 'training.required_plan_elements':'计划必需元素', 'health.injury_or_constraint':'健康限制', 'health.recovery_status':'恢复状态', 'plan.preference':'计划偏好',
|
|
|
+ 'plan.decision':'已确认计划决定', 'plan.weekly_schedule':'每周训练安排'
|
|
|
+ };
|
|
|
+ facts.forEach((fact, factIndex) => {
|
|
|
+ // BUG-12:优先用后端给的稳定 fact_id 寻址。下标会在用户眼皮底下位移
|
|
|
+ // ——每次 /chat 都会清理过期事实、拒绝事实也会让后面的整体前移,
|
|
|
+ // 老页面按下标点"确认"就会作用到另一条事实上。
|
|
|
+ const factRef = encodeURIComponent(fact.fact_id || String(factIndex));
|
|
|
+ const factRow = document.createElement('div'); factRow.className = 'memory-fact-row';
|
|
|
+ const factBody = document.createElement('div');
|
|
|
+ const label = labels[(fact.namespace || '') + '.' + (fact.key || '')] || '事实';
|
|
|
+ const state = fact.user_confirmed ? '已确认' : '待确认';
|
|
|
+ const validity = fact.duration_type === 'temporary'
|
|
|
+ ? ' · 临时' + (fact.valid_from ? ' · ' + fact.valid_from : '') + (fact.valid_until ? ' 至 ' + fact.valid_until : '')
|
|
|
+ : fact.duration_type === 'long_term' ? ' · 长期' : '';
|
|
|
+ let scheduleNotice = '';
|
|
|
+ if (fact.key === 'weekly_schedule') {
|
|
|
+ try {
|
|
|
+ const schedule = JSON.parse(String(fact.value || '{}'));
|
|
|
+ const recognized = Object.keys(schedule.days || {}).length;
|
|
|
+ const skipped = Array.isArray(schedule.invalid_days) ? schedule.invalid_days : [];
|
|
|
+ if (skipped.length) scheduleNotice = ' · 已识别 ' + recognized + ' 天,跳过:' + skipped.join('、');
|
|
|
+ } catch (_) {}
|
|
|
+ }
|
|
|
+ factBody.textContent = label + ':' + (fact.value || '') + scheduleNotice + ' · ' + state + validity + (fact.evidence ? ' · 证据:“' + fact.evidence + '”' : '');
|
|
|
+ const factActions = document.createElement('div'); factActions.className = 'plan-row-actions';
|
|
|
+ if (!fact.user_confirmed) {
|
|
|
+ const confirm = document.createElement('button'); confirm.type = 'button'; confirm.className = 'small-delete'; confirm.textContent = '确认';
|
|
|
+ confirm.addEventListener('click', async () => {
|
|
|
+ const result = await dataRequest('/data/memories/' + encodeURIComponent(memory.id) + '/facts/' + factRef + '/confirm', {method:'POST'});
|
|
|
+ if (result.error) {
|
|
|
+ setDataStatus(memoryConflictMessage(result), 'error');
|
|
|
+ if (result.code === 'MEMORY_CONFLICT') await loadDataOverview();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ setDataStatus('事实已确认,将用于后续对话', 'success'); await loadDataOverview();
|
|
|
+ }); factActions.appendChild(confirm);
|
|
|
+ }
|
|
|
+ const reject = document.createElement('button'); reject.type = 'button'; reject.className = 'small-delete'; reject.textContent = '拒绝';
|
|
|
+ reject.addEventListener('click', async () => {
|
|
|
+ const result = await dataRequest('/data/memories/' + encodeURIComponent(memory.id) + '/facts/' + factRef + '/reject', {method:'POST'});
|
|
|
+ if (result.error) {
|
|
|
+ setDataStatus(memoryConflictMessage(result), 'error');
|
|
|
+ if (result.code === 'MEMORY_CONFLICT') await loadDataOverview();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ setDataStatus('事实已拒绝', 'success'); await loadDataOverview();
|
|
|
+ }); factActions.appendChild(reject);
|
|
|
+ const edit = document.createElement('button'); edit.type = 'button'; edit.className = 'small-delete'; edit.textContent = '编辑';
|
|
|
+ edit.addEventListener('click', () => {
|
|
|
+ factBody.innerHTML = '';
|
|
|
+ const input = document.createElement(fact.key === 'weekly_schedule' ? 'textarea' : 'input');
|
|
|
+ input.className = 'editor-input memory-fact-input';
|
|
|
+ input.value = String(fact.value || '');
|
|
|
+ if (fact.key === 'weekly_schedule') { input.rows = 5; input.placeholder = '{"enabled":true,"days":{"mon":{"type":"training","subject":"胸部训练"},"wed":{"type":"rest"},"fri":{"type":"aerobic","subject":"跑步"}}}'; }
|
|
|
+ else { input.type = (fact.key === 'max_rpe') ? 'number' : 'text'; }
|
|
|
+ if (input.type === 'number') { input.min = '1'; input.max = '10'; input.step = '0.1'; }
|
|
|
+ const save = document.createElement('button'); save.type = 'button'; save.className = 'small-delete'; save.textContent = '保存';
|
|
|
+ const cancel = document.createElement('button'); cancel.type = 'button'; cancel.className = 'small-delete'; cancel.textContent = '取消';
|
|
|
+ const originalActions = factActions.innerHTML;
|
|
|
+ factActions.innerHTML = '';
|
|
|
+ factBody.appendChild(input);
|
|
|
+ factActions.append(save, cancel);
|
|
|
+ input.focus(); input.select();
|
|
|
+ save.addEventListener('click', async () => {
|
|
|
+ const value = input.value.trim();
|
|
|
+ if (!value) return setDataStatus('事实内容不能为空', 'error');
|
|
|
+ const result = await dataRequest('/data/memories/' + encodeURIComponent(memory.id) + '/facts/' + factRef, {
|
|
|
+ method:'PATCH', headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({value, evidence:fact.evidence || ''}),
|
|
|
+ });
|
|
|
+ if (result.error) {
|
|
|
+ setDataStatus(memoryConflictMessage(result), 'error');
|
|
|
+ if (result.code === 'MEMORY_CONFLICT') await loadDataOverview();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ setDataStatus('事实已保存,需重新确认后才会用于对话', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ cancel.addEventListener('click', async () => {
|
|
|
+ factBody.textContent = label + ':' + (fact.value || '') + scheduleNotice + ' · ' + state + validity + (fact.evidence ? ' · 证据:“' + fact.evidence + '”' : '');
|
|
|
+ factActions.innerHTML = originalActions;
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ }); factActions.appendChild(edit);
|
|
|
+ const history = Array.isArray(fact.history) ? fact.history : [];
|
|
|
+ if (history.length) {
|
|
|
+ const rollback = document.createElement('button'); rollback.type = 'button'; rollback.className = 'small-delete'; rollback.textContent = '回滚';
|
|
|
+ rollback.title = '恢复上一版本,恢复后需要重新确认';
|
|
|
+ rollback.addEventListener('click', async () => {
|
|
|
+ const result = await dataRequest('/data/memories/' + encodeURIComponent(memory.id) + '/facts/' + factRef + '/rollback', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({history_index:-1}),
|
|
|
+ });
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('已回滚到上一版本,需重新确认后才会用于对话', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ factActions.appendChild(rollback);
|
|
|
+ const historyMeta = document.createElement('div'); historyMeta.className = 'data-row-meta';
|
|
|
+ historyMeta.textContent = '历史版本 ' + history.length + ' 个';
|
|
|
+ factBody.appendChild(historyMeta);
|
|
|
+ }
|
|
|
+ const usage = Array.isArray(fact.usage_log) ? fact.usage_log : [];
|
|
|
+ if (usage.length) {
|
|
|
+ const latest = usage[usage.length - 1];
|
|
|
+ const usageMeta = document.createElement('div'); usageMeta.className = 'data-row-meta';
|
|
|
+ usageMeta.textContent = '最近使用:' + formatDataTime(latest.at) + (latest.action ? ' · ' + latest.action : '') + (latest.detail ? ' · ' + latest.detail : '');
|
|
|
+ factBody.appendChild(usageMeta);
|
|
|
+ }
|
|
|
+ factRow.append(factBody, factActions); factText.appendChild(factRow);
|
|
|
+ });
|
|
|
+ }
|
|
|
+ const actions = document.createElement('div'); actions.className = 'plan-row-actions';
|
|
|
+ if (!memory.user_confirmed && facts.length === 0) {
|
|
|
+ const confirm = document.createElement('button');
|
|
|
+ confirm.type = 'button'; confirm.className = 'small-delete'; confirm.textContent = '确认使用';
|
|
|
+ confirm.addEventListener('click', async () => {
|
|
|
+ const result = await dataRequest('/data/memories/' + encodeURIComponent(memory.id) + '/confirm', {method:'POST'});
|
|
|
+ if (result.error) {
|
|
|
+ setDataStatus(memoryConflictMessage(result), 'error');
|
|
|
+ if (result.code === 'MEMORY_CONFLICT') await loadDataOverview();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ setDataStatus('记忆已确认,将用于后续对话', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ actions.appendChild(confirm);
|
|
|
+ }
|
|
|
+ const remove = document.createElement('button');
|
|
|
+ remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '删除';
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除这条临时记忆吗?')) return;
|
|
|
+ const result = await dataRequest('/data/memories/' + encodeURIComponent(memory.id), { method:'DELETE' });
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('临时记忆已删除', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ actions.appendChild(remove); main.append(title, meta); if (factText) main.append(factText); main.append(actions); row.append(main); list.appendChild(row);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderDailyRecords(records) {
|
|
|
+ const list = document.getElementById('daily-records-list');
|
|
|
+ document.getElementById('daily-records-count').textContent = records.length + ' 条';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!records.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">暂无每日或营养记录</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ records.slice().reverse().forEach(item => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = (item.date || '未注明日期') + ' · ' + (item.category === 'daily_checkin' ? '每日记录' : '营养记录');
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ const record = item.record || {};
|
|
|
+ meta.textContent = ['体重 ' + (record.weight_kg ?? '--') + ' kg', '热量 ' + (record.calories_kcal ?? '--') + ' kcal'].join(' · ');
|
|
|
+ const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '删除';
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除这条每日记录及其中的营养数据吗?')) return;
|
|
|
+ const result = await dataRequest('/data/records/' + encodeURIComponent(item.id), {method:'DELETE'});
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('每日记录已删除', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ main.append(title, meta); row.append(main, remove); list.appendChild(row);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function memoryConflictMessage(result) {
|
|
|
+ return result.code === 'MEMORY_CONFLICT'
|
|
|
+ ? '该事实已过期:已有更新版本,请重新查看并确认最新事实'
|
|
|
+ : result.error;
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderSorenessReports(reports) {
|
|
|
+ const list = document.getElementById('soreness-list');
|
|
|
+ const count = document.getElementById('soreness-count');
|
|
|
+ const levelLabels = { recovered:'已恢复', sore:'酸痛', painful:'疼痛' };
|
|
|
+ count.textContent = reports.length + ' 条';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!reports.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">没有肌群酸痛记录</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ reports.slice().reverse().forEach(report => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = report.region + ' · ' + (levelLabels[report.level] || report.level) + (report.expired ? ' · 已过期' : '');
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ meta.textContent = '报告:' + formatDataTime(report.reported_at) + ' · 到期:' + formatDataTime(report.expires_at)
|
|
|
+ + (report.evidence ? ' · 原话:' + report.evidence : '');
|
|
|
+ main.append(title, meta);
|
|
|
+ const actions = document.createElement('div'); actions.className = 'plan-row-actions';
|
|
|
+ const edit = document.createElement('button'); edit.type = 'button'; edit.className = 'small-delete'; edit.textContent = '修改';
|
|
|
+ edit.addEventListener('click', async () => {
|
|
|
+ const region = window.prompt('受伤或酸痛区域(例如颈部、膝部、手腕、腿部)', report.region);
|
|
|
+ if (region === null) return;
|
|
|
+ const level = window.prompt('程度(recovered/sore/painful)', report.level);
|
|
|
+ if (level === null) return;
|
|
|
+ const result = await dataRequest('/data/soreness/' + encodeURIComponent(report.id), {
|
|
|
+ method:'PATCH', headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({region:region.trim(), level:level.trim(), evidence:report.evidence || ''}),
|
|
|
+ });
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus(
|
|
|
+ level.trim() === report.level
|
|
|
+ ? '肌群酸痛记录已更新,原有效期保持不变'
|
|
|
+ : '肌群酸痛程度已更新,新的 72 小时有效期从现在开始',
|
|
|
+ 'success'
|
|
|
+ );
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '删除';
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('删除这条肌群酸痛记录吗?')) return;
|
|
|
+ const result = await dataRequest('/data/soreness/' + encodeURIComponent(report.id), {method:'DELETE'});
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('肌群酸痛记录已删除', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ actions.append(edit, remove); row.append(main, actions); list.appendChild(row);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderHealthImports(imports) {
|
|
|
+ const list = document.getElementById('health-imports-list');
|
|
|
+ document.getElementById('health-imports-count').textContent = imports.length + ' 条';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!imports.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">暂无全天健康或睡眠导入</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ imports.forEach(item => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = item.filename || '未命名健康数据';
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ const kindLabels = {sleep_csv:'睡眠 CSV', health_fit:'健康 FIT', wellness_zip:'健康数据 ZIP'};
|
|
|
+ const details = [kindLabels[item.kind] || 'Garmin 健康数据'];
|
|
|
+ if (item.date_hint) details.push(item.date_hint);
|
|
|
+ if (item.heart_rate_count) details.push(item.heart_rate_count + ' 条心率');
|
|
|
+ if (item.sleep_date) details.push('睡眠 ' + item.sleep_date);
|
|
|
+ if (item.metric_count) details.push(item.metric_count + ' 条健康指标');
|
|
|
+ if (item.sleep_stage_count) details.push(item.sleep_stage_count + ' 段睡眠阶段');
|
|
|
+ if (item.status === 'partial') details.push('有解析提示');
|
|
|
+ details.push(formatDataTime(item.created_at));
|
|
|
+ meta.textContent = details.join(' · ');
|
|
|
+ const remove = document.createElement('button');
|
|
|
+ remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '删除';
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除该健康数据导入及其派生数据吗?')) return;
|
|
|
+ const result = await dataRequest('/health/imports/' + encodeURIComponent(item.id), {method:'DELETE'});
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('健康数据导入已删除', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ await refreshHealthTrend();
|
|
|
+ if ($healthModal.classList.contains('show')) await loadDailyOverview($overviewDate.value);
|
|
|
+ });
|
|
|
+ main.append(title, meta); row.append(main, remove); list.appendChild(row);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ async function renderDataFileAudit() {
|
|
|
+ const list = document.getElementById('data-audit-list');
|
|
|
+ const count = document.getElementById('data-audit-count');
|
|
|
+ const [raw, streams] = await Promise.all([
|
|
|
+ dataRequest('/health/imports/raw-audit'),
|
|
|
+ dataRequest('/data/hr-streams/audit'),
|
|
|
+ ]);
|
|
|
+ if (raw.error || streams.error) {
|
|
|
+ count.textContent = '读取失败';
|
|
|
+ list.innerHTML = '<div class="data-empty">' + escapeHtml(raw.error || streams.error) + '</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const items = [
|
|
|
+ ...(raw.missing || []).map(name => ({kind:'健康原始文件缺失', name, missing:true})),
|
|
|
+ ...(raw.orphans || []).map(name => ({kind:'孤立健康原始文件', name, endpoint:'/health/imports/raw-orphans/'})),
|
|
|
+ ...(streams.missing || []).map(item => ({
|
|
|
+ kind:'训练心率流缺失', name:item.file,
|
|
|
+ detail:'关联训练记录:' + ((item.record_ids || []).join('、') || '未知'), missing:true,
|
|
|
+ })),
|
|
|
+ ...(streams.orphans || []).map(name => ({kind:'孤立训练心率流', name, endpoint:'/data/hr-streams/orphans/'})),
|
|
|
+ ];
|
|
|
+ count.textContent = items.length + ' 项';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!items.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">文件与数据库引用一致</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ items.forEach(item => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = item.kind + ' · ' + item.name;
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ meta.textContent = item.detail || (item.missing
|
|
|
+ ? '数据库仍有引用;可从个人备份或原设备重新导入恢复'
|
|
|
+ : '没有任何记录引用,可安全清理');
|
|
|
+ main.append(title, meta); row.appendChild(main);
|
|
|
+ if (item.endpoint) {
|
|
|
+ const remove = document.createElement('button');
|
|
|
+ remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '删除';
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除孤立文件 ' + item.name + ' 吗?')) return;
|
|
|
+ const result = await dataRequest(item.endpoint + encodeURIComponent(item.name), {method:'DELETE'});
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('孤立文件已删除', 'success');
|
|
|
+ await renderDataFileAudit();
|
|
|
+ });
|
|
|
+ row.appendChild(remove);
|
|
|
+ }
|
|
|
+ list.appendChild(row);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function updateRecordButtons() {
|
|
|
+ const checked = document.querySelectorAll('#records-list input:checked').length;
|
|
|
+ const deleteButton = document.getElementById('delete-records');
|
|
|
+ const viewButton = document.getElementById('view-record');
|
|
|
+ deleteButton.disabled = checked === 0;
|
|
|
+ deleteButton.textContent = checked ? '删除所选记录(' + checked + ')' : '删除所选记录';
|
|
|
+ viewButton.disabled = checked !== 1;
|
|
|
+ viewButton.textContent = checked === 1 ? '查看所选记录' : '查看所选记录' + (checked > 1 ? '(请选择 1 条)' : '');
|
|
|
+ viewButton.title = checked === 1 ? '查看所选训练记录详情' : '请先选择一条训练记录';
|
|
|
+ }
|
|
|
+
|
|
|
+ const $sessionGarminHours = document.getElementById('session-garmin-hours');
|
|
|
+ const $sessionRecoveryApply = document.getElementById('session-recovery-apply');
|
|
|
+ const $sessionRecoveryStatus = document.getElementById('session-recovery-status');
|
|
|
+
|
|
|
+ function setSessionRecoveryStatus(message, type='') {
|
|
|
+ $sessionRecoveryStatus.textContent = message;
|
|
|
+ $sessionRecoveryStatus.className = 'session-recovery-status' + (type ? ' ' + type : '');
|
|
|
+ }
|
|
|
+
|
|
|
+ function validateSessionGarminHours(raw) {
|
|
|
+ const text = String(raw == null ? '' : raw).trim();
|
|
|
+ if (!text) return 0;
|
|
|
+ const value = Number(text);
|
|
|
+ if (!Number.isFinite(value) || ( value < 0 || value > 96.0)) {
|
|
|
+ throw new Error('请输入0–96.0 之间的数字。');
|
|
|
+ }
|
|
|
+ return Math.round(value * 10) / 10;
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderSessionIntro(data) {
|
|
|
+ if (!data || data.error || !data.message) return false;
|
|
|
+ sessionGarminRecoveryHours = Number(data.garmin_recovery_hours || 0);
|
|
|
+ sorenessPromptRegions = Array.isArray(data.soreness_prompt_regions)
|
|
|
+ ? data.soreness_prompt_regions.slice() : [];
|
|
|
+ $sessionGarminHours.value = String(sessionGarminRecoveryHours);
|
|
|
+ setSessionRecoveryStatus(
|
|
|
+ '已应用到本次会话:' + sessionGarminRecoveryHours + ' 小时;刷新页面后需要重新输入。'
|
|
|
+ );
|
|
|
+ document.querySelectorAll('.session-intro').forEach(item => item.remove());
|
|
|
+ addMsg('bot', data.message, 'session-intro');
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ async function refreshSessionIntroWithGarmin(rawValue) {
|
|
|
+ let value;
|
|
|
+ try {
|
|
|
+ value = validateSessionGarminHours(rawValue);
|
|
|
+ } catch (error) {
|
|
|
+ setSessionRecoveryStatus(error.message, 'error');
|
|
|
+ $sessionGarminHours.focus();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ $sessionRecoveryApply.disabled = true;
|
|
|
+ setSessionRecoveryStatus('正在刷新肌群恢复清单…');
|
|
|
+ const data = await dataRequest('/session/intro?garmin_recovery_hours=' + encodeURIComponent(value));
|
|
|
+ if (data.error) {
|
|
|
+ setSessionRecoveryStatus(data.error, 'error');
|
|
|
+ } else {
|
|
|
+ renderSessionIntro(data);
|
|
|
+ }
|
|
|
+ $sessionRecoveryApply.disabled = false;
|
|
|
+ }
|
|
|
+
|
|
|
+ async function showSelectedTrainingRecord(recordId) {
|
|
|
+ const preview = document.getElementById('record-preview');
|
|
|
+ const title = document.getElementById('record-preview-title');
|
|
|
+ const body = document.getElementById('record-preview-body');
|
|
|
+ preview.classList.add('show');
|
|
|
+ title.textContent = '正在读取训练记录…';
|
|
|
+ body.textContent = '';
|
|
|
+ const response = await dataRequest('/data/training-records/' + encodeURIComponent(recordId));
|
|
|
+ if (response.error) {
|
|
|
+ title.textContent = '训练记录';
|
|
|
+ body.textContent = response.error;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const item = response.record || {};
|
|
|
+ const session = item.session || {};
|
|
|
+ const segments = Array.isArray(item.segments) ? item.segments.filter(segment => !segment.is_rest) : [];
|
|
|
+ const lines = [
|
|
|
+ '日期:' + (response.date || '--'),
|
|
|
+ '名称:' + (item.name || '--'),
|
|
|
+ '训练时间(北京时间):' + (item.workout_start_time_beijing || '--'),
|
|
|
+ '训练科目:' + (item.sport || session.sport || '--'),
|
|
|
+ '训练组数:' + (item.total_sets ?? segments.length),
|
|
|
+ '总次数:' + (item.total_reps ?? '--'),
|
|
|
+ item.avg_hr != null ? '平均心率:' + item.avg_hr + ' bpm' : '',
|
|
|
+ item.max_hr != null ? '最高心率:' + item.max_hr + ' bpm' : '',
|
|
|
+ item.note ? '训练感受:' + item.note : '',
|
|
|
+ '',
|
|
|
+ '动作组:',
|
|
|
+ ].filter(Boolean);
|
|
|
+ if (!segments.length) {
|
|
|
+ lines.push('暂无动作组明细');
|
|
|
+ } else {
|
|
|
+ segments.forEach((segment, index) => {
|
|
|
+ const weight = segment.weight_kg != null ? segment.weight_kg + ' kg' : '--';
|
|
|
+ const reps = segment.repetitions != null ? segment.repetitions + ' 次' : '--';
|
|
|
+ const duration = segment.duration_s != null ? segment.duration_s + ' 秒' : '';
|
|
|
+ const heartRate = segment.avg_hr != null ? ' · 平均心率 ' + segment.avg_hr + ' bpm' : '';
|
|
|
+ lines.push((segment.index || index + 1) + '. ' + (segment.category || '未命名动作') + ' · ' + weight + ' × ' + reps + (duration ? ' · ' + duration : '') + heartRate);
|
|
|
+ });
|
|
|
+ }
|
|
|
+ title.textContent = item.name || ((response.date || '') + ' · ' + (item.sport || session.sport || '训练'));
|
|
|
+ body.textContent = lines.join('\n');
|
|
|
+ }
|
|
|
+
|
|
|
+ function quarantinedSummary(item) {
|
|
|
+ if (!item.recoverable) return '无法解析:' + (item.reason || '未知原因');
|
|
|
+ const parts = [item.sport || '未知运动'];
|
|
|
+ if (item.start_time) parts.push(new Date(item.start_time).toLocaleString('zh-CN'));
|
|
|
+ parts.push((item.segments || 0) + ' 个分段');
|
|
|
+ parts.push((item.hr_records || 0) + ' 条心率');
|
|
|
+ if (item.total_calories) parts.push(item.total_calories + ' kcal');
|
|
|
+ if (item.dismissed) parts.push('已设为不再提醒');
|
|
|
+ return parts.join(' · ');
|
|
|
+ }
|
|
|
+
|
|
|
+ async function renderQuarantined() {
|
|
|
+ const list = document.getElementById('quarantined-list');
|
|
|
+ const count = document.getElementById('quarantined-count');
|
|
|
+ const data = await dataRequest('/workout_state/quarantined?include_dismissed=true');
|
|
|
+ const files = (data && Array.isArray(data.files)) ? data.files : [];
|
|
|
+ count.textContent = files.length + ' 条';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!files.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">没有被隔离的未确认训练</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ files.forEach(item => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = item.name;
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ meta.textContent = quarantinedSummary(item);
|
|
|
+ main.append(title, meta);
|
|
|
+ const actions = document.createElement('div'); actions.className = 'plan-row-actions';
|
|
|
+ if (item.recoverable) {
|
|
|
+ const preview = document.createElement('button');
|
|
|
+ preview.type = 'button'; preview.className = 'small-delete'; preview.textContent = '只读预览';
|
|
|
+ preview.addEventListener('click', async () => {
|
|
|
+ const result = await dataRequest('/workout_state/quarantined/' + encodeURIComponent(item.name) + '/preview');
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ const p = result.preview || {};
|
|
|
+ window.alert(['文件:' + p.name, '运动类型:' + (p.sport || '--'), '分段:' + (p.segments ?? '--'), '心率点:' + (p.hr_records ?? '--'), '平均心率:' + (p.avg_hr ?? '--'), '警告:' + ((p.warnings || []).join(';') || '无')].join('\n'));
|
|
|
+ });
|
|
|
+ actions.appendChild(preview);
|
|
|
+ const load = document.createElement('button');
|
|
|
+ load.type = 'button'; load.className = 'small-delete'; load.textContent = '载入编辑';
|
|
|
+ load.addEventListener('click', async () => {
|
|
|
+ if (hasWorkout && !savedRecordEditingTarget()
|
|
|
+ && !window.confirm('载入隔离训练会覆盖当前待确认训练,继续吗?')) return;
|
|
|
+ const result = await dataRequest('/workout_state/quarantined/restore', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({name:item.name, overwrite_pending:hasWorkout && !savedRecordEditingTarget()}),
|
|
|
+ });
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('已载入到训练编辑区,请核对后确认保存', 'success');
|
|
|
+ closeDataModal();
|
|
|
+ await refreshWorkoutState(true);
|
|
|
+ startPolling();
|
|
|
+ });
|
|
|
+ actions.appendChild(load);
|
|
|
+ }
|
|
|
+ if (!item.dismissed) {
|
|
|
+ const mute = document.createElement('button');
|
|
|
+ mute.type = 'button'; mute.className = 'small-delete'; mute.textContent = '不再提醒';
|
|
|
+ mute.addEventListener('click', async () => {
|
|
|
+ const result = await dataRequest('/workout_state/quarantined/dismiss', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({name:item.name}),
|
|
|
+ });
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('已设为不再提醒,文件仍保留在 data 目录', 'success');
|
|
|
+ await renderQuarantined();
|
|
|
+ });
|
|
|
+ actions.appendChild(mute);
|
|
|
+ }
|
|
|
+ const remove = document.createElement('button');
|
|
|
+ remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '永久删除';
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除隔离文件 ' + item.name + ' 吗?此操作不可撤销。')) return;
|
|
|
+ const result = await dataRequest('/workout_state/quarantined/delete', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({name:item.name}),
|
|
|
+ });
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('隔离文件已删除', 'success');
|
|
|
+ await renderQuarantined();
|
|
|
+ });
|
|
|
+ actions.appendChild(remove);
|
|
|
+ row.append(main, actions);
|
|
|
+ list.appendChild(row);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── 重置前恢复点(DATA-14)─────────────────────────────────────────
|
|
|
+ `/data/reset` 是唯一不可逆的批量删除,后端在删之前必须落一份完整快照。
|
|
|
+ 这个区块的意义在于让那份快照**可见、可下载、可删除**——只在后端存一份
|
|
|
+ 用户找不到的备份,既救不了人,又等于在"删除全部数据"之后偷偷留着一份
|
|
|
+ 全量数据,两头都不对。恢复走已有的「导入备份」,不新开还原路径。 */
|
|
|
+ function recoveryPointSummary(item) {
|
|
|
+ const size = item.bytes >= 1024 * 1024
|
|
|
+ ? (item.bytes / (1024 * 1024)).toFixed(2) + ' MiB'
|
|
|
+ : Math.max(1, Math.round(item.bytes / 1024)) + ' KiB';
|
|
|
+ const when = item.created_at ? new Date(item.created_at).toLocaleString('zh-CN') : '时间未知';
|
|
|
+ return when + ' · ' + size + ' · 下载后可用「导入备份」还原';
|
|
|
+ }
|
|
|
+
|
|
|
+ async function renderRecoveryPoints() {
|
|
|
+ const list = document.getElementById('recovery-points-list');
|
|
|
+ const count = document.getElementById('recovery-points-count');
|
|
|
+ const data = await dataRequest('/data/recovery-points');
|
|
|
+ const points = (data && Array.isArray(data.points)) ? data.points : [];
|
|
|
+ count.textContent = points.length + ' 条';
|
|
|
+ list.innerHTML = '';
|
|
|
+ if (!points.length) {
|
|
|
+ list.innerHTML = '<div class="data-empty">没有恢复点(执行“删除全部数据”时会自动生成一份)</div>';
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ points.forEach(item => {
|
|
|
+ const row = document.createElement('div'); row.className = 'data-row';
|
|
|
+ const main = document.createElement('div'); main.className = 'data-row-main';
|
|
|
+ const title = document.createElement('div'); title.className = 'data-row-title';
|
|
|
+ title.textContent = item.name;
|
|
|
+ const meta = document.createElement('div'); meta.className = 'data-row-meta';
|
|
|
+ meta.textContent = recoveryPointSummary(item);
|
|
|
+ main.append(title, meta);
|
|
|
+ const actions = document.createElement('div'); actions.className = 'plan-row-actions';
|
|
|
+ const download = document.createElement('button');
|
|
|
+ download.type = 'button'; download.className = 'small-delete'; download.textContent = '下载';
|
|
|
+ download.addEventListener('click', () => {
|
|
|
+ window.location.assign('/data/recovery-points/' + encodeURIComponent(item.name));
|
|
|
+ });
|
|
|
+ const remove = document.createElement('button');
|
|
|
+ remove.type = 'button'; remove.className = 'small-delete'; remove.textContent = '永久删除';
|
|
|
+ remove.addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除恢复点 ' + item.name + ' 吗?删除后这份数据再也找不回来。')) return;
|
|
|
+ const result = await dataRequest('/data/recovery-points/' + encodeURIComponent(item.name), { method:'DELETE' });
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('恢复点已删除', 'success');
|
|
|
+ await renderRecoveryPoints();
|
|
|
+ });
|
|
|
+ actions.append(download, remove);
|
|
|
+ row.append(main, actions);
|
|
|
+ list.appendChild(row);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadDataOverview() {
|
|
|
+ const data = await dataRequest('/data/overview');
|
|
|
+ if (data.error) return setDataStatus(data.error, 'error');
|
|
|
+ renderRecords(data.records || []);
|
|
|
+ renderDailyRecords(data.daily_records || []);
|
|
|
+ renderPlans(data.plans || []);
|
|
|
+ renderMemories(data.memories || []);
|
|
|
+ renderSorenessReports(data.soreness_reports || []);
|
|
|
+ renderHealthImports(data.health_imports || []);
|
|
|
+ await renderDataFileAudit();
|
|
|
+ await renderQuarantined();
|
|
|
+ await renderRecoveryPoints();
|
|
|
+ const profile = data.profile || {};
|
|
|
+ document.getElementById('profile-data-summary').textContent = data.profile_complete
|
|
|
+ ? '用户档案:' + (profile.height_cm || '--') + ' cm,目标 ' + (profile.goal || '--') + ',器械 ' + (profile.equipment || []).join('、')
|
|
|
+ : '用户档案尚未完善。';
|
|
|
+ const pendingButton = document.getElementById('delete-pending');
|
|
|
+ pendingButton.disabled = !data.has_pending_workout;
|
|
|
+ pendingButton.textContent = data.has_pending_workout
|
|
|
+ ? '删除待确认训练' + (data.pending_source ? '(' + data.pending_source + ')' : '')
|
|
|
+ : '无待确认训练';
|
|
|
+ }
|
|
|
+
|
|
|
+ async function openDataModal() {
|
|
|
+ $dataModal.classList.add('show');
|
|
|
+ $dataModal.setAttribute('aria-hidden', 'false');
|
|
|
+ document.body.style.overflow = 'hidden';
|
|
|
+ setDataStatus();
|
|
|
+ await Promise.all([loadDataOverview(), loadExternalModelSettings()]);
|
|
|
+ }
|
|
|
+
|
|
|
+ function closeDataModal() {
|
|
|
+ $dataModal.classList.remove('show');
|
|
|
+ $dataModal.setAttribute('aria-hidden', 'true');
|
|
|
+ document.body.style.overflow = '';
|
|
|
+ $dataButton.focus();
|
|
|
+ }
|
|
|
+
|
|
|
+ $dataButton.addEventListener('click', openDataModal);
|
|
|
+ document.getElementById('external-models-toggle').addEventListener('change', event => {
|
|
|
+ updateExternalModelSettings(event.target.checked);
|
|
|
+ });
|
|
|
+ $checkinButton.addEventListener('click', () => openCheckin());
|
|
|
+ document.getElementById('open-checkin').addEventListener('click', () => openCheckin());
|
|
|
+ $sessionRecoveryApply.addEventListener('click', () => refreshSessionIntroWithGarmin($sessionGarminHours.value));
|
|
|
+ $sessionGarminHours.addEventListener('keydown', event => {
|
|
|
+ if (event.key === 'Enter') {
|
|
|
+ event.preventDefault();
|
|
|
+ refreshSessionIntroWithGarmin($sessionGarminHours.value);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ $checkinModalClose.addEventListener('click', closeCheckin);
|
|
|
+ document.getElementById('checkin-cancel').addEventListener('click', closeCheckin);
|
|
|
+ $checkinModal.addEventListener('click', event => { if (event.target === $checkinModal) closeCheckin(); });
|
|
|
+ $checkinForm.addEventListener('submit', submitCheckin);
|
|
|
+ $addNutritionRecord.addEventListener('click', addManualNutritionRecord);
|
|
|
+ /* 改日期必须重新载入那一天的记录:否则表单里留着的是上一天的值,用户按下
|
|
|
+ 保存就把它们写进了另一个日期(BUG-09 的一个变体)。 */
|
|
|
+ document.getElementById('checkin-date').addEventListener('change', async event => {
|
|
|
+ const day = event.target.value;
|
|
|
+ if (!day) return;
|
|
|
+ const keepDate = day;
|
|
|
+ $checkinForm.reset();
|
|
|
+ document.getElementById('checkin-date').value = keepDate;
|
|
|
+ await loadCheckinInto(keepDate);
|
|
|
+ });
|
|
|
+ $overviewButton.addEventListener('click', openHealthOverview);
|
|
|
+ $healthModalClose.addEventListener('click', closeHealthOverview);
|
|
|
+ $healthModal.addEventListener('click', event => { if (event.target === $healthModal) closeHealthOverview(); });
|
|
|
+ $overviewDate.addEventListener('change', () => { if ($overviewDate.value) loadDailyOverview($overviewDate.value); });
|
|
|
+ document.getElementById('overview-prev').addEventListener('click', () => changeOverviewDay(-1));
|
|
|
+ document.getElementById('overview-next').addEventListener('click', () => changeOverviewDay(1));
|
|
|
+ $dataModalClose.addEventListener('click', closeDataModal);
|
|
|
+ $dataModal.addEventListener('click', event => { if (event.target === $dataModal) closeDataModal(); });
|
|
|
+ document.addEventListener('keydown', event => {
|
|
|
+ if (event.key === 'Escape' && $checkinModal.classList.contains('show')) { closeCheckin(); return; }
|
|
|
+ if (event.key === 'Escape' && $healthModal.classList.contains('show')) { closeHealthOverview(); return; }
|
|
|
+ if (event.key === 'Escape' && $dataModal.classList.contains('show')) closeDataModal();
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('export-backup').addEventListener('click', async () => {
|
|
|
+ const button = document.getElementById('export-backup');
|
|
|
+ button.disabled = true;
|
|
|
+ try {
|
|
|
+ const response = await fetch('/data/backup/export');
|
|
|
+ if (!response.ok) {
|
|
|
+ const error = await response.json().catch(() => ({}));
|
|
|
+ throw new Error(error.error || '备份导出失败');
|
|
|
+ }
|
|
|
+ const blob = await response.blob();
|
|
|
+ const disposition = response.headers.get('Content-Disposition') || '';
|
|
|
+ const match = disposition.match(/filename="?([^";]+)"?/i);
|
|
|
+ const url = URL.createObjectURL(blob);
|
|
|
+ const anchor = document.createElement('a');
|
|
|
+ anchor.href = url;
|
|
|
+ anchor.download = match ? match[1] : 'fithealth-backup.zip';
|
|
|
+ document.body.appendChild(anchor); anchor.click(); anchor.remove();
|
|
|
+ URL.revokeObjectURL(url);
|
|
|
+ setDataStatus('备份已导出', 'success');
|
|
|
+ } catch (error) {
|
|
|
+ setDataStatus(error.message || '备份导出失败', 'error');
|
|
|
+ } finally {
|
|
|
+ button.disabled = false;
|
|
|
+ }
|
|
|
+ });
|
|
|
+ document.getElementById('import-backup').addEventListener('click', () => {
|
|
|
+ document.getElementById('backup-file').click();
|
|
|
+ });
|
|
|
+ document.getElementById('backup-file').addEventListener('change', async event => {
|
|
|
+ const file = event.target.files && event.target.files[0];
|
|
|
+ event.target.value = '';
|
|
|
+ if (file) await handleBackupFile(file);
|
|
|
+ });
|
|
|
+
|
|
|
+ async function handleBackupFile(file) {
|
|
|
+ if (!file) return;
|
|
|
+ const inspectForm = new FormData(); inspectForm.append('file', file);
|
|
|
+ const inspectionResponse = await fetch('/data/backup/inspect', {method:'POST', body:inspectForm});
|
|
|
+ const inspection = await inspectionResponse.json().catch(() => ({}));
|
|
|
+ if (!inspectionResponse.ok || inspection.error) return setDataStatus(inspection.error || '备份文件校验失败', 'error');
|
|
|
+ const message = '将替换当前本地档案、记录、计划、记忆和健康数据。恢复前会自动生成一份恢复点,是否继续?';
|
|
|
+ if (!window.confirm(message)) return;
|
|
|
+ const importForm = new FormData();
|
|
|
+ importForm.append('file', file); importForm.append('confirm_restore', 'true');
|
|
|
+ const restoreResponse = await fetch('/data/backup/import', {method:'POST', body:importForm});
|
|
|
+ const restored = await restoreResponse.json().catch(() => ({}));
|
|
|
+ if (!restoreResponse.ok || restored.error) return setDataStatus(restored.error || '备份恢复失败', 'error');
|
|
|
+ if (restored.recovery_point?.name) window.alert('恢复完成。恢复前快照:' + restored.recovery_point.name);
|
|
|
+ window.location.reload();
|
|
|
+ }
|
|
|
+
|
|
|
+ document.getElementById('view-record').addEventListener('click', async () => {
|
|
|
+ const ids = [...document.querySelectorAll('#records-list input:checked')].map(item => item.value);
|
|
|
+ if (ids.length !== 1) {
|
|
|
+ setDataStatus('请选择一条训练记录后再查看', 'error');
|
|
|
+ updateRecordButtons();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const button = document.getElementById('view-record');
|
|
|
+ button.disabled = true;
|
|
|
+ await showSelectedTrainingRecord(ids[0]);
|
|
|
+ updateRecordButtons();
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('record-preview-close').addEventListener('click', () => {
|
|
|
+ document.getElementById('record-preview').classList.remove('show');
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('delete-records').addEventListener('click', async () => {
|
|
|
+ const ids = [...document.querySelectorAll('#records-list input:checked')].map(item => item.value);
|
|
|
+ if (!ids.length || !window.confirm('永久删除所选的 ' + ids.length + ' 条训练记录吗?')) return;
|
|
|
+ const result = await dataRequest('/data/records/delete-batch', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ ids }),
|
|
|
+ });
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('已删除 ' + result.deleted + ' 条训练记录', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('delete-plans').addEventListener('click', async () => {
|
|
|
+ const ids = [...document.querySelectorAll('#plans-list input:checked')].map(item => item.value);
|
|
|
+ if (!ids.length || !window.confirm('永久删除所选的 ' + ids.length + ' 份训练计划吗?')) return;
|
|
|
+ const result = await dataRequest('/plans/delete-batch', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ids})});
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('已删除 ' + result.deleted + ' 份训练计划', 'success'); await loadDataOverview();
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('plan-preview-close').addEventListener('click', () => document.getElementById('plan-preview').classList.remove('show'));
|
|
|
+ document.getElementById('plan-preview-download').addEventListener('click', () => {
|
|
|
+ if (previewedPlan) downloadMarkdown(previewedPlan.content, previewedPlan.filename);
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('clear-memories').addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除全部临时记忆吗?')) return;
|
|
|
+ const result = await dataRequest('/data/memories', { method:'DELETE' });
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('已清空临时记忆', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('delete-pending').addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久删除当前待确认训练吗?')) return;
|
|
|
+ const result = await dataRequest('/data/pending-workout', { method:'DELETE' });
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ editorBusy = false; selectedSets.clear();
|
|
|
+ await refreshWorkoutState(true);
|
|
|
+ setDataStatus('待确认训练已删除', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('reset-profile').addEventListener('click', async () => {
|
|
|
+ if (!window.confirm('永久清空用户档案并恢复默认器械吗?')) return;
|
|
|
+ const result = await dataRequest('/data/profile/reset', { method:'POST' });
|
|
|
+ if (result.error) { setDataStatus(result.error, 'error'); return; }
|
|
|
+ setDataStatus('用户档案已重置,下次对话将重新引导填写', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+
|
|
|
+ document.getElementById('reset-all').addEventListener('click', async () => {
|
|
|
+ const input = document.getElementById('reset-confirmation');
|
|
|
+ if (input.value.trim() !== '删除全部数据') return setDataStatus('请输入“删除全部数据”后再执行', 'error');
|
|
|
+ if (!window.confirm('此操作将永久删除训练计划、训练记录、健康与睡眠数据、待确认训练、用户档案和临时记忆。\n\n删除前会自动生成一份恢复点(完整快照),保留最近 3 份,可在「重置前恢复点」中下载或手动删除。确定继续吗?')) return;
|
|
|
+ const result = await dataRequest('/data/reset', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({ confirmation:input.value.trim() }),
|
|
|
+ });
|
|
|
+ /* DATA-14:**半删状态是 200 + partial,而不是 5xx**,所以不能像别处那样
|
|
|
+ 看到 error 就掉头返回。掉头返回会跳过下面的 refreshWorkoutState 与
|
|
|
+ loadDataOverview,前端于此停在删除前的旧视图上,而磁盘上七项已经没了
|
|
|
+ ——正是这条需求要修的"用户不知道究竟删了什么"。有 steps 就说明这次
|
|
|
+ 删除真的执行过,无论成败都要刷新视图并把逐项结果说清楚。 */
|
|
|
+ const executed = Array.isArray(result.steps);
|
|
|
+ if (result.error && !executed) {
|
|
|
+ setDataStatus(result.error, 'error');
|
|
|
+ // 一个字节都没删(恢复点写失败或维护冲突),视图无需刷新。
|
|
|
+ await renderRecoveryPoints();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ input.value = '';
|
|
|
+ editorBusy = false; selectedSets.clear();
|
|
|
+ await refreshWorkoutState(true);
|
|
|
+ const point = result.recovery_point || {};
|
|
|
+ if (result.partial) {
|
|
|
+ const failedSteps = result.steps.filter(step => step.error);
|
|
|
+ const failed = failedSteps.map(step => step.label).join('、');
|
|
|
+ setDataStatus('部分数据未能删除:' + failed + '。其余数据已删除。' + (result.recovery_hint || ''), 'error');
|
|
|
+ failedSteps.forEach(step => addNotify('清空「' + step.label + '」失败:' + step.error));
|
|
|
+ const retry = document.createElement('button'); retry.type = 'button'; retry.className = 'small-delete'; retry.textContent = '重试失败项目';
|
|
|
+ retry.addEventListener('click', async () => {
|
|
|
+ const retried = await dataRequest('/data/reset/retry', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({keys:failedSteps.map(step => step.key)})});
|
|
|
+ addNotify(retried.partial ? '部分项目仍失败' : '失败项目已重试成功', retried.partial ? 'notify-error' : 'notify-saved');
|
|
|
+ if (!retried.partial) retry.remove();
|
|
|
+ });
|
|
|
+ document.getElementById('data-status').appendChild(retry);
|
|
|
+ } else {
|
|
|
+ setDataStatus('全部本地数据已删除。恢复点 ' + (point.name || '(未知)') + ' 已保存,如需还原请在「重置前恢复点」中下载后走「导入备份」。', 'success');
|
|
|
+ }
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+
|
|
|
+ /* ── Chat messages ─────────────────────────────────────────────────── */
|
|
|
+ function addMsg(role, text, extraClass='', artifact=null) {
|
|
|
+ removeHint();
|
|
|
+ const el = document.createElement('div');
|
|
|
+ el.className = 'msg ' + role + (extraClass ? ' ' + extraClass : '');
|
|
|
+ const headerEl = document.createElement('div');
|
|
|
+ headerEl.className = 'msg-header';
|
|
|
+
|
|
|
+ if (role === 'user' || role === 'bot') {
|
|
|
+ const tag = document.createElement('div');
|
|
|
+ tag.className = 'role';
|
|
|
+ tag.textContent = role === 'user' ? '你' : '助手';
|
|
|
+ headerEl.appendChild(tag);
|
|
|
+ }
|
|
|
+
|
|
|
+ if (role === 'bot' && extraClass !== 'session-intro') {
|
|
|
+ const dlBtn = document.createElement('button');
|
|
|
+ dlBtn.className = 'btn-download';
|
|
|
+ dlBtn.title = '下载此回复为 Markdown 文件';
|
|
|
+ dlBtn.innerHTML = '<span>⬇️</span> 下载';
|
|
|
+ dlBtn.onclick = () => {
|
|
|
+ const blob = new Blob([text], { type: 'text/markdown' });
|
|
|
+ const url = URL.createObjectURL(blob);
|
|
|
+ const a = document.createElement('a');
|
|
|
+ a.href = url;
|
|
|
+ const recommended = text.match(/(?:建议保存文件名|推荐文件名)\s*[::]\s*[`“"]?([^`”"\n]+\.md)/i);
|
|
|
+ const dateStr = localDateISO().slice(2);
|
|
|
+ a.download = recommended ? recommended[1].trim() : `${dateStr}-训练计划.md`;
|
|
|
+ document.body.appendChild(a);
|
|
|
+ a.click();
|
|
|
+ document.body.removeChild(a);
|
|
|
+ URL.revokeObjectURL(url);
|
|
|
+ };
|
|
|
+ headerEl.appendChild(dlBtn);
|
|
|
+ }
|
|
|
+
|
|
|
+ if (headerEl.children.length > 0) {
|
|
|
+ el.appendChild(headerEl);
|
|
|
+ }
|
|
|
+ const body = document.createElement('div');
|
|
|
+ body.className = 'msg-body';
|
|
|
+ if (role === 'bot') {
|
|
|
+ if (window.marked && window.DOMPurify) {
|
|
|
+ const rendered = marked.parse(text);
|
|
|
+ body.innerHTML = DOMPurify.sanitize(rendered, {
|
|
|
+ USE_PROFILES: { html: true },
|
|
|
+ FORBID_TAGS: ['style', 'form', 'input', 'button', 'textarea'],
|
|
|
+ });
|
|
|
+ } else {
|
|
|
+ body.textContent = text;
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ body.textContent = text;
|
|
|
+ }
|
|
|
+ el.appendChild(body);
|
|
|
+ if (role === 'bot' && artifact && artifact.type === 'training_plan') {
|
|
|
+ el.appendChild(buildPlanSavePanel(artifact));
|
|
|
+ }
|
|
|
+ if (role === 'bot' && artifact && artifact.type === 'training_records') {
|
|
|
+ setViewerMode('training', artifact.default_date || localDateISO());
|
|
|
+ } else if (role === 'bot' && artifact && artifact.type === 'nutrition_records') {
|
|
|
+ setViewerMode('nutrition', artifact.default_date || localDateISO());
|
|
|
+ }
|
|
|
+ if (role === 'bot' && artifact && artifact.type === 'profile_update') {
|
|
|
+ el.appendChild(buildProfileUpdatePanel(artifact));
|
|
|
+ }
|
|
|
+ $chat.appendChild(el);
|
|
|
+ scrollBottom();
|
|
|
+ return el;
|
|
|
+ }
|
|
|
+
|
|
|
+ function buildPlanSavePanel(artifact) {
|
|
|
+ const panel = document.createElement('div'); panel.className = 'plan-save-panel';
|
|
|
+ const grid = document.createElement('div'); grid.className = 'plan-save-grid';
|
|
|
+ const date = document.createElement('input'); date.type='date'; date.value = artifact.suggested_date || localDateISO();
|
|
|
+ const subject = document.createElement('input'); subject.value = artifact.subject || '综合训练'; subject.maxLength=40;
|
|
|
+ const title = document.createElement('input'); title.value = artifact.title || '训练计划'; title.maxLength=100;
|
|
|
+ const memo = document.createElement('textarea'); memo.maxLength=1000;
|
|
|
+ memo.placeholder = '可记录训练反馈、动作/视频偏好、喜欢的 YouTube 频道,或直接粘贴要保留的视频链接。正向反馈会在近期计划中优先参考。';
|
|
|
+ grid.append(buildPlanSaveField('计划日期',date),buildPlanSaveField('训练科目',subject),buildPlanSaveField('计划标题',title),buildPlanSaveField('计划备忘录',memo,true));
|
|
|
+ const actions = document.createElement('div'); actions.className='plan-save-actions';
|
|
|
+ const save = document.createElement('button'); save.type='button'; save.className='data-action'; save.textContent='保存计划';
|
|
|
+ /* BUG-31:让 applyWorkflowState 能按后端的 workflow_state 禁用它。 */
|
|
|
+ save.dataset.planSave = '1';
|
|
|
+ const download = document.createElement('button'); download.type='button'; download.className='data-action'; download.textContent='下载到本地'; download.disabled=true;
|
|
|
+ const result = document.createElement('span'); result.className='plan-save-result';
|
|
|
+ save.addEventListener('click', async () => {
|
|
|
+ save.disabled=true; result.textContent='保存中...';
|
|
|
+ const response = await dataRequest('/plans', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({date:date.value,subject:subject.value,title:title.value,memo:memo.value,content:artifact.content,source:artifact.source,draft_id:artifact.draft_id||''})});
|
|
|
+ if (response.error) { save.disabled=false; result.textContent=response.error; return; }
|
|
|
+ save.textContent = response.duplicate ? '本地已有' : '已保存计划';
|
|
|
+ /* 保存完成后这个按钮就退休了;打上标记,别被后续的 applyWorkflowState 重新启用。 */
|
|
|
+ save.dataset.planSaveDone = '1';
|
|
|
+ save.disabled = true;
|
|
|
+ result.textContent = response.duplicate
|
|
|
+ ? '检测到相同内容:' + response.filename
|
|
|
+ : '已保存计划:' + response.filename;
|
|
|
+ date.disabled=true; subject.disabled=true; title.disabled=true; memo.disabled=true;
|
|
|
+ download.disabled = false;
|
|
|
+ download.dataset.content = response.content || artifact.content || '';
|
|
|
+ download.dataset.filename = response.filename || '训练计划.md';
|
|
|
+ await loadDataOverview();
|
|
|
+ addNotify(
|
|
|
+ response.duplicate
|
|
|
+ ? '本地已有相同训练计划:' + response.filename
|
|
|
+ : '训练计划已保存到本地:' + response.filename,
|
|
|
+ response.duplicate ? 'notify-skipped' : 'notify-saved',
|
|
|
+ );
|
|
|
+ });
|
|
|
+ download.addEventListener('click', () => {
|
|
|
+ downloadMarkdown(download.dataset.content, download.dataset.filename);
|
|
|
+ result.textContent = '已请求下载:' + download.dataset.filename;
|
|
|
+ });
|
|
|
+ actions.append(save,download,result); panel.append(grid,actions); return panel;
|
|
|
+ }
|
|
|
+
|
|
|
+ function buildProfileUpdatePanel(artifact) {
|
|
|
+ const panel = document.createElement('div');
|
|
|
+ panel.className = 'profile-update-panel';
|
|
|
+ const heading = document.createElement('strong');
|
|
|
+ heading.textContent = '检测到档案变更,请确认后保存';
|
|
|
+ const labels = {
|
|
|
+ weekly_weight_kg:'本周体重', height_cm:'身高', birth_date:'出生日期',
|
|
|
+ sex:'性别', goal:'健身目标', equipment:'可用器械',
|
|
|
+ };
|
|
|
+ const values = {
|
|
|
+ sex: {male:'男', female:'女'},
|
|
|
+ };
|
|
|
+ const list = document.createElement('div');
|
|
|
+ list.className = 'profile-update-list';
|
|
|
+ const updates = artifact.updates || {};
|
|
|
+ (artifact.fields || Object.keys(updates)).forEach(field => {
|
|
|
+ if (!(field in updates)) return;
|
|
|
+ const value = Array.isArray(updates[field])
|
|
|
+ ? updates[field].join('、')
|
|
|
+ : (values[field] && values[field][updates[field]]) || updates[field];
|
|
|
+ const line = document.createElement('div');
|
|
|
+ if (field === 'equipment' && artifact.equipment_diff) {
|
|
|
+ const diff = artifact.equipment_diff;
|
|
|
+ const modeLabel = {add:'新增', remove:'移除', replace:'替换'}[diff.mode] || '更新';
|
|
|
+ const added = (diff.added || []).join('、') || '无';
|
|
|
+ const removed = (diff.removed || []).join('、') || '无';
|
|
|
+ line.textContent = '可用器械(' + modeLabel + '):新增 ' + added + ';移除 ' + removed
|
|
|
+ + ';更新后 ' + (diff.after || []).join('、');
|
|
|
+ } else {
|
|
|
+ line.textContent = (labels[field] || field) + ':' + value;
|
|
|
+ }
|
|
|
+ list.appendChild(line);
|
|
|
+ });
|
|
|
+ const actions = document.createElement('div');
|
|
|
+ actions.className = 'profile-update-actions';
|
|
|
+ const confirm = document.createElement('button');
|
|
|
+ confirm.type = 'button'; confirm.className = 'confirm'; confirm.textContent = '确认保存';
|
|
|
+ const cancel = document.createElement('button');
|
|
|
+ cancel.type = 'button'; cancel.className = 'cancel'; cancel.textContent = '不保存';
|
|
|
+ const result = document.createElement('span'); result.className = 'profile-update-result';
|
|
|
+ confirm.addEventListener('click', async () => {
|
|
|
+ confirm.disabled = true; cancel.disabled = true; result.textContent = '保存中…';
|
|
|
+ const response = await dataRequest('/profile/confirm-update', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({updates}),
|
|
|
+ });
|
|
|
+ if (response.error) {
|
|
|
+ result.textContent = response.error; confirm.disabled = false; cancel.disabled = false; return;
|
|
|
+ }
|
|
|
+ result.textContent = '已保存';
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+ cancel.addEventListener('click', () => {
|
|
|
+ panel.remove();
|
|
|
+ addNotify('已取消保存本次档案变更。', 'notify-skipped');
|
|
|
+ });
|
|
|
+ actions.append(confirm, cancel, result); panel.append(heading, list, actions);
|
|
|
+ return panel;
|
|
|
+ }
|
|
|
+
|
|
|
+ function viewerItemLabel(item) {
|
|
|
+ return (item.date || '') + ' · ' + (item.name || item.sport || '数据组');
|
|
|
+ }
|
|
|
+
|
|
|
+ function buildNutritionField(labelText, name, value, options = {}) {
|
|
|
+ const field = document.createElement('label'); field.className = 'nutrition-field';
|
|
|
+ const label = document.createElement('span'); label.textContent = labelText;
|
|
|
+ const input = options.multiline ? document.createElement('textarea') : document.createElement('input');
|
|
|
+ input.name = name;
|
|
|
+ input.value = value == null ? '' : String(value);
|
|
|
+ if (!options.multiline && options.type !== 'text') {
|
|
|
+ input.type = 'number'; input.min = '0'; input.max = String(options.max || 20000);
|
|
|
+ input.step = options.step || '0.1'; input.inputMode = 'decimal';
|
|
|
+ }
|
|
|
+ if (options.maxlength) input.maxLength = options.maxlength;
|
|
|
+ field.append(label, input);
|
|
|
+ return field;
|
|
|
+ }
|
|
|
+
|
|
|
+ function nutritionFoodRow(food = {}) {
|
|
|
+ const row = document.createElement('div'); row.className = 'nutrition-item';
|
|
|
+ row.append(
|
|
|
+ buildNutritionField('食物', 'name', food.name || '', {type:'text', maxlength:80}),
|
|
|
+ buildNutritionField('份量', 'portion', food.portion || '', {type:'text', maxlength:80}),
|
|
|
+ buildNutritionField('热量 kcal', 'calories_kcal', food.calories_kcal ?? 0, {step:'1'}),
|
|
|
+ buildNutritionField('蛋白质 g', 'protein_g', food.protein_g ?? 0, {max:1000}),
|
|
|
+ buildNutritionField('碳水 g', 'carbs_g', food.carbs_g ?? 0, {max:2000}),
|
|
|
+ buildNutritionField('脂肪 g', 'fat_g', food.fat_g ?? 0, {max:1000}),
|
|
|
+ );
|
|
|
+ const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'nutrition-item-remove';
|
|
|
+ remove.textContent = '×'; remove.title = '移除食物'; remove.setAttribute('aria-label', '移除食物');
|
|
|
+ remove.addEventListener('click', () => {
|
|
|
+ const list = row.parentElement;
|
|
|
+ if (list && list.children.length <= 1) return;
|
|
|
+ row.remove();
|
|
|
+ recalculateNutritionMeal(list && list.closest('form'));
|
|
|
+ });
|
|
|
+ row.querySelectorAll('input').forEach(input => input.addEventListener('input', () => recalculateNutritionMeal(row.closest('form'))));
|
|
|
+ row.appendChild(remove);
|
|
|
+ return row;
|
|
|
+ }
|
|
|
+
|
|
|
+ function readNutritionFoodRows(form) {
|
|
|
+ return [...form.querySelectorAll('.nutrition-item')].map(row => {
|
|
|
+ const value = name => row.querySelector('[name="' + name + '"]').value;
|
|
|
+ return {
|
|
|
+ name:value('name').trim(), portion:value('portion').trim(),
|
|
|
+ calories_kcal:Number(value('calories_kcal')), protein_g:Number(value('protein_g')),
|
|
|
+ carbs_g:Number(value('carbs_g')), fat_g:Number(value('fat_g')),
|
|
|
+ };
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function recalculateNutritionMeal(form) {
|
|
|
+ if (!form || form.dataset.kind !== 'meal') return;
|
|
|
+ const totals = readNutritionFoodRows(form).reduce((sum, food) => ({
|
|
|
+ total_kcal:sum.total_kcal + (Number.isFinite(food.calories_kcal) ? food.calories_kcal : 0),
|
|
|
+ protein_g:sum.protein_g + (Number.isFinite(food.protein_g) ? food.protein_g : 0),
|
|
|
+ carbs_g:sum.carbs_g + (Number.isFinite(food.carbs_g) ? food.carbs_g : 0),
|
|
|
+ fat_g:sum.fat_g + (Number.isFinite(food.fat_g) ? food.fat_g : 0),
|
|
|
+ }), {total_kcal:0, protein_g:0, carbs_g:0, fat_g:0});
|
|
|
+ Object.entries(totals).forEach(([field, value]) => {
|
|
|
+ const output = form.querySelector('[data-total="' + field + '"]');
|
|
|
+ if (output) output.value = field === 'total_kcal' ? String(Math.round(value)) : String(Math.round(value * 10) / 10);
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function nutritionStatus(form, message, tone = '') {
|
|
|
+ const status = form.querySelector('.nutrition-editor-status');
|
|
|
+ status.className = 'nutrition-editor-status' + (tone ? ' ' + tone : '');
|
|
|
+ status.textContent = message;
|
|
|
+ }
|
|
|
+
|
|
|
+ async function saveNutritionEditor(form, item) {
|
|
|
+ const payload = {revision:item.revision};
|
|
|
+ if (item.kind === 'meal') {
|
|
|
+ payload.items = readNutritionFoodRows(form);
|
|
|
+ if (!payload.items.length || payload.items.some(food => !food.name || !food.portion)) {
|
|
|
+ nutritionStatus(form, '请填写每项食物的名称和份量。', 'error'); return;
|
|
|
+ }
|
|
|
+ if (payload.items.some(food => ['calories_kcal','protein_g','carbs_g','fat_g'].some(field => !Number.isFinite(food[field]) || food[field] < 0))) {
|
|
|
+ nutritionStatus(form, '营养数据必须是大于或等于 0 的数字。', 'error'); return;
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ for (const field of ['calories_kcal','protein_g','carbs_g','fat_g']) {
|
|
|
+ const value = form.elements[field].value;
|
|
|
+ const number = Number(value);
|
|
|
+ if (value !== '' && !Number.isFinite(number)) {
|
|
|
+ nutritionStatus(form, '营养数据必须是有效数字。', 'error'); return;
|
|
|
+ }
|
|
|
+ payload[field] = value === '' ? null : number;
|
|
|
+ }
|
|
|
+ payload.note = form.elements.note.value.trim();
|
|
|
+ }
|
|
|
+ const button = form.querySelector('[type="submit"]'); button.disabled = true;
|
|
|
+ nutritionStatus(form, '正在保存…');
|
|
|
+ const result = await dataRequest('/data/nutrition-records/' + encodeURIComponent(item.id), {
|
|
|
+ method:'PATCH', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload),
|
|
|
+ });
|
|
|
+ button.disabled = false;
|
|
|
+ if (result.error) {
|
|
|
+ if (result.code === 'STALE_RECORD_REVISION') {
|
|
|
+ nutritionStatus(form, '该营养记录已在其他页面更新,正在重新加载。', 'error');
|
|
|
+ await loadViewerDay();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ nutritionStatus(form, result.error, 'error');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const updated = result.record;
|
|
|
+ const index = viewerItems.findIndex(candidate => candidate.id === item.id);
|
|
|
+ if (updated && index >= 0) viewerItems[index] = updated;
|
|
|
+ viewerSelectedArtifact = updated || item;
|
|
|
+ renderNutritionViewerDetail(viewerSelectedArtifact);
|
|
|
+ nutritionStatus($viewerDetail.querySelector('form'), '已保存。', 'success');
|
|
|
+ addNotify('营养组修改已保存,并已同步当天营养合计。', 'notify-saved');
|
|
|
+ }
|
|
|
+
|
|
|
+ document.getElementById('add-soreness').addEventListener('click', async () => {
|
|
|
+ const region = window.prompt('受伤或酸痛区域(例如颈部、膝部、手腕、腿部)', '手臂');
|
|
|
+ if (region === null) return;
|
|
|
+ const level = window.prompt('程度(recovered/sore/painful)', 'sore');
|
|
|
+ if (level === null) return;
|
|
|
+ const result = await dataRequest('/data/soreness', {
|
|
|
+ method:'POST', headers:{'Content-Type':'application/json'},
|
|
|
+ body:JSON.stringify({region:region.trim(), level:level.trim(), evidence:'数据管理手动录入'}),
|
|
|
+ });
|
|
|
+ if (result.error) return setDataStatus(result.error, 'error');
|
|
|
+ setDataStatus('肌群酸痛记录已添加', 'success');
|
|
|
+ await loadDataOverview();
|
|
|
+ });
|
|
|
+
|
|
|
+ async function deleteNutritionEditor(form, item) {
|
|
|
+ if (!window.confirm('确定删除该营养组吗?删除后会同步扣除当天营养合计。')) return;
|
|
|
+ const buttons = form.querySelectorAll('button');
|
|
|
+ buttons.forEach(button => { button.disabled = true; });
|
|
|
+ nutritionStatus(form, '正在删除…');
|
|
|
+ const result = await dataRequest('/data/nutrition-records/' + encodeURIComponent(item.id), {
|
|
|
+ method:'DELETE', headers:{'Content-Type':'application/json'}, body:JSON.stringify({revision:item.revision}),
|
|
|
+ });
|
|
|
+ if (result.error) {
|
|
|
+ buttons.forEach(button => { button.disabled = false; });
|
|
|
+ nutritionStatus(form, result.error, 'error');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ addNotify('营养组已删除,并已同步当天营养合计。', 'notify-saved');
|
|
|
+ await loadViewerDay();
|
|
|
+ }
|
|
|
+
|
|
|
+ function renderNutritionViewerDetail(item) {
|
|
|
+ const form = document.createElement('form'); form.className = 'nutrition-editor'; form.dataset.kind = item.kind || 'manual';
|
|
|
+ const head = document.createElement('div'); head.className = 'nutrition-editor-head';
|
|
|
+ const title = document.createElement('h2'); title.textContent = item.name || '营养组';
|
|
|
+ const source = document.createElement('span'); source.className = 'nutrition-source';
|
|
|
+ source.textContent = item.source === 'food_photo_estimate' ? '照片估算数据(不含原图)' : (item.source === 'manual_meal' ? '手动餐次' : '手动记录');
|
|
|
+ head.append(title, source); form.appendChild(head);
|
|
|
+ const metrics = document.createElement('div'); metrics.className = 'nutrition-metrics';
|
|
|
+ const metricDefinitions = [
|
|
|
+ ['总摄入热量', 'calories_kcal', 'total_kcal', item.total_kcal, 20000, '1'],
|
|
|
+ ['蛋白质', 'protein_g', 'protein_g', item.protein_g, 1000, '0.1'],
|
|
|
+ ['碳水', 'carbs_g', 'carbs_g', item.carbs_g, 2000, '0.1'],
|
|
|
+ ['脂肪', 'fat_g', 'fat_g', item.fat_g, 1000, '0.1'],
|
|
|
+ ];
|
|
|
+ metricDefinitions.forEach(([label, inputName, totalName, value, max, step]) => {
|
|
|
+ const field = buildNutritionField(label + (label === '总摄入热量' ? ' kcal' : ' g'), inputName, value, {max, step});
|
|
|
+ if (item.kind === 'meal') {
|
|
|
+ const input = field.querySelector('input'); input.readOnly = true; input.dataset.total = totalName;
|
|
|
+ }
|
|
|
+ metrics.appendChild(field);
|
|
|
+ });
|
|
|
+ form.appendChild(metrics);
|
|
|
+ if (item.kind === 'meal') {
|
|
|
+ const list = document.createElement('div'); list.className = 'nutrition-item-list';
|
|
|
+ (item.items || []).forEach(food => list.appendChild(nutritionFoodRow(food)));
|
|
|
+ form.appendChild(list);
|
|
|
+ const add = document.createElement('button'); add.type = 'button'; add.className = 'data-action'; add.textContent = '添加食物';
|
|
|
+ add.addEventListener('click', () => { list.appendChild(nutritionFoodRow()); recalculateNutritionMeal(form); });
|
|
|
+ form.appendChild(add);
|
|
|
+ } else {
|
|
|
+ form.appendChild(buildNutritionField('备注', 'note', item.note || '', {multiline:true, maxlength:500}));
|
|
|
+ }
|
|
|
+ const actions = document.createElement('div'); actions.className = 'nutrition-editor-actions';
|
|
|
+ const status = document.createElement('span'); status.className = 'nutrition-editor-status'; status.textContent = '修改后保存到该日期的营养记录。';
|
|
|
+ const remove = document.createElement('button'); remove.type = 'button'; remove.className = 'data-action danger'; remove.textContent = '删除该记录';
|
|
|
+ remove.addEventListener('click', () => deleteNutritionEditor(form, item));
|
|
|
+ const save = document.createElement('button'); save.type = 'submit'; save.className = 'data-action'; save.textContent = '保存营养组';
|
|
|
+ actions.append(status, remove, save); form.appendChild(actions);
|
|
|
+ form.addEventListener('submit', event => { event.preventDefault(); saveNutritionEditor(form, item); });
|
|
|
+ $viewerDetail.classList.remove('empty'); $viewerDetail.replaceChildren(form);
|
|
|
+ recalculateNutritionMeal(form);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadViewerDay() {
|
|
|
+ const token = ++viewerLoadToken;
|
|
|
+ const requestedMode = viewerMode;
|
|
|
+ const day = $viewerDate.value || localDateISO();
|
|
|
+ $viewerDate.value = day;
|
|
|
+ $viewerSelect.innerHTML = '';
|
|
|
+ $viewerSelect.disabled = true;
|
|
|
+ viewerItems = [];
|
|
|
+ viewerSelectedArtifact = null;
|
|
|
+ $viewerDetail.classList.add('empty');
|
|
|
+ $viewerDetail.textContent = '正在加载数据…';
|
|
|
+ const endpoint = viewerMode === 'nutrition' ? '/data/nutrition-records?day=' : '/data/training-records?day=';
|
|
|
+ const response = await dataRequest(endpoint + encodeURIComponent(day));
|
|
|
+ if (token !== viewerLoadToken || requestedMode !== viewerMode) return;
|
|
|
+ if (response.error) { $viewerDetail.textContent = response.error; return; }
|
|
|
+ viewerItems = response.items || [];
|
|
|
+ if (!viewerItems.length) {
|
|
|
+ $viewerDetail.textContent = '该日期没有已保存的' + (viewerMode === 'nutrition' ? '营养组' : '训练组') + '。';
|
|
|
+ if (viewerMode === 'training' && savedRecordEditingTarget()) {
|
|
|
+ leaveSavedTrainingRecordMode(); hasWorkout = false; $wList.innerHTML = '<div class="workout-empty">该日期没有已保存的训练组</div>';
|
|
|
+ $setCount.textContent = '0 组'; $workoutActions.classList.remove('show'); $editorToolbar.classList.remove('show'); $workoutNoteWrap.classList.remove('show');
|
|
|
+ }
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ viewerItems.forEach(item => {
|
|
|
+ const option = document.createElement('option'); option.value = item.id; option.textContent = viewerItemLabel(item); $viewerSelect.appendChild(option);
|
|
|
+ });
|
|
|
+ $viewerSelect.disabled = false;
|
|
|
+ await loadViewerSelection(false);
|
|
|
+ }
|
|
|
+
|
|
|
+ async function loadViewerSelection(explicit = false) {
|
|
|
+ const item = viewerItems.find(candidate => candidate.id === $viewerSelect.value);
|
|
|
+ if (!item) return;
|
|
|
+ viewerSelectedArtifact = item;
|
|
|
+ if (viewerMode === 'nutrition') { renderNutritionViewerDetail(item); return; }
|
|
|
+ if (!explicit && hasWorkout && !savedRecordEditingTarget()) return;
|
|
|
+ if (savedRecordEditingTarget() === item.id && editorBusy) return;
|
|
|
+ await loadSavedTrainingRecord(item.id, false);
|
|
|
+ }
|
|
|
+
|
|
|
+ function setViewerMode(mode, dateValue = '', options = {}) {
|
|
|
+ const nextMode = mode === 'nutrition' ? 'nutrition' : 'training';
|
|
|
+ const changed = nextMode !== viewerMode;
|
|
|
+ viewerMode = nextMode;
|
|
|
+ $viewerTraining.classList.toggle('active', viewerMode === 'training');
|
|
|
+ $viewerNutrition.classList.toggle('active', viewerMode === 'nutrition');
|
|
|
+ $viewerContentTitle.textContent = viewerMode === 'nutrition' ? '营养组列表' : '训练组列表';
|
|
|
+ $trainingEditorArea.hidden = viewerMode !== 'training';
|
|
|
+ $viewerDetail.hidden = viewerMode === 'training';
|
|
|
+ if (dateValue) $viewerDate.value = dateValue;
|
|
|
+ if (changed && options.reload === false) {
|
|
|
+ viewerItems = [];
|
|
|
+ viewerSelectedArtifact = null;
|
|
|
+ $viewerSelect.replaceChildren();
|
|
|
+ $viewerSelect.disabled = true;
|
|
|
+ $viewerDetail.classList.add('empty');
|
|
|
+ $viewerDetail.textContent = '';
|
|
|
+ } else if (options.reload !== false) {
|
|
|
+ loadViewerDay();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function viewerModeForMessage(text) {
|
|
|
+ const normalized = String(text || '').replaceAll(' ', '');
|
|
|
+ if (['饮食','营养','摄入','餐食','碳水','蛋白质','脂肪','热量'].some(word => normalized.includes(word))) return 'nutrition';
|
|
|
+ if (['训练','运动','锻炼','动作组','训练组','卧推','深蹲','硬拉','跑步','跳绳'].some(word => normalized.includes(word))) return 'training';
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ $viewerTraining.addEventListener('click', () => setViewerMode('training'));
|
|
|
+ $viewerNutrition.addEventListener('click', () => setViewerMode('nutrition'));
|
|
|
+ $viewerDate.addEventListener('change', loadViewerDay);
|
|
|
+ $viewerSelect.addEventListener('change', () => loadViewerSelection(true));
|
|
|
+ $viewerDate.value = localDateISO();
|
|
|
+ loadViewerDay();
|
|
|
+
|
|
|
+ function buildPlanSaveField(labelText,input,full=false) {
|
|
|
+ const field=document.createElement('div'); field.className='plan-save-field';
|
|
|
+ if (full) field.classList.add('full');
|
|
|
+ const label=document.createElement('label'); label.textContent=labelText;
|
|
|
+ field.append(label,input); return field;
|
|
|
+ }
|
|
|
+
|
|
|
+ /* BUG-31:把后端的结构化校验结果与工作流状态真正用起来。
|
|
|
+ `plan_validation.violations` 是逐条违规明细(超限组数、缺必需元素、含禁止动作、
|
|
|
+ 未恢复肌群),比正文那段自然语言精确;`workflow_state` 则是"现在该不该让用户
|
|
|
+ 点保存"的权威信号——以前两者都只是躺在响应体里。 */
|
|
|
+ const PLAN_BLOCKING_WORKFLOW_STATES = new Set([
|
|
|
+ 'needs_clarification', 'constraint_conflict', 'validation_failed',
|
|
|
+ ]);
|
|
|
+
|
|
|
+ function renderPlanValidation(validation) {
|
|
|
+ if (!validation || typeof validation !== 'object') return;
|
|
|
+ const violations = Array.isArray(validation.violations) ? validation.violations : [];
|
|
|
+ if (validation.passed !== false && !violations.length) return;
|
|
|
+ const lines = violations.length
|
|
|
+ ? violations.map(item => '· ' + String(item)).join('\n')
|
|
|
+ : '(后端未给出明细)';
|
|
|
+ addNotify('这份计划没有通过确定性校验:\n' + lines, 'notify-error');
|
|
|
+ }
|
|
|
+
|
|
|
+ function applyWorkflowState(state) {
|
|
|
+ const value = String(state || '');
|
|
|
+ if (!value) return;
|
|
|
+ const blocked = PLAN_BLOCKING_WORKFLOW_STATES.has(value);
|
|
|
+ document.querySelectorAll('[data-plan-save]').forEach(button => {
|
|
|
+ if (button.dataset.planSaveDone === '1') return; // 已保存的按钮不再动
|
|
|
+ button.disabled = blocked;
|
|
|
+ button.title = blocked ? '当前存在未解决的冲突或待澄清项,暂不能保存计划' : '';
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ function addNotify(text, cls='', summaryText='') { const el = document.createElement('div');
|
|
|
+ el.className = 'msg system' + (cls ? ' ' + cls : '');
|
|
|
+ const body = document.createElement('div');
|
|
|
+ body.textContent = text;
|
|
|
+ el.appendChild(body);
|
|
|
+ if (summaryText) {
|
|
|
+ const sb = document.createElement('div');
|
|
|
+ sb.className = 'summary-block';
|
|
|
+ sb.innerHTML = '<strong>已保存摘要</strong>' + esc(summaryText);
|
|
|
+ el.appendChild(sb);
|
|
|
+ }
|
|
|
+ $chat.appendChild(el);
|
|
|
+ scrollBottom();
|
|
|
+ }
|
|
|
+
|
|
|
+ function showTyping() {
|
|
|
+ removeHint();
|
|
|
+ const el = document.createElement('div');
|
|
|
+ el.className = 'msg bot typing';
|
|
|
+ el.innerHTML = '<span></span><span></span><span></span>';
|
|
|
+ $chat.appendChild(el);
|
|
|
+ scrollBottom();
|
|
|
+ return () => el.remove();
|
|
|
+ }
|
|
|
+
|
|
|
+ function endSession() {
|
|
|
+ sessionEnded = true;
|
|
|
+ $msg.disabled = true;
|
|
|
+ $send.disabled = true;
|
|
|
+ $logout.disabled = true;
|
|
|
+ $overlay.classList.add('show');
|
|
|
+ if (pollTimer) clearInterval(pollTimer);
|
|
|
+ }
|
|
|
+
|
|
|
+ /* ── Send chat ─────────────────────────────────────────────────────── */
|
|
|
+ $form.addEventListener('submit', async (e) => {
|
|
|
+ e.preventDefault();
|
|
|
+ if (sessionEnded) return;
|
|
|
+ const text = $msg.value.trim();
|
|
|
+ if (!text && !pendingFoodImage) return;
|
|
|
+ const requestedViewerMode = viewerModeForMessage(text);
|
|
|
+ if (requestedViewerMode) setViewerMode(requestedViewerMode);
|
|
|
+ if (pendingFoodImage) {
|
|
|
+ const foodImage = pendingFoodImage;
|
|
|
+ clearPendingFoodImage();
|
|
|
+ $msg.value = '';
|
|
|
+ await analyzeFoodImage(foodImage, text);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const history = sessionConversationHistory.slice(-SESSION_HISTORY_MAX_ITEMS);
|
|
|
+ addMsg('user', text);
|
|
|
+ $msg.value = '';
|
|
|
+ $send.disabled = true;
|
|
|
+ const rm = showTyping();
|
|
|
+ const messageSource = pendingMessageSource;
|
|
|
+ const planContext = pendingPlanContext;
|
|
|
+ const submittedMemoryEntryIds = pendingMemoryEntryIds.slice();
|
|
|
+ pendingMessageSource = 'chat';
|
|
|
+ pendingPlanContext = null;
|
|
|
+ try {
|
|
|
+ const res = await fetch('/chat', {
|
|
|
+ method: 'POST',
|
|
|
+ headers: { 'Content-Type': 'application/json' },
|
|
|
+ body: JSON.stringify({ message: text, history: history, source: messageSource, plan_context: planContext, garmin_recovery_hours: sessionGarminRecoveryHours, soreness_prompt_regions:sorenessPromptRegions, pending_memory_entry_ids:submittedMemoryEntryIds }),
|
|
|
+ });
|
|
|
+ sorenessPromptRegions = [];
|
|
|
+ const data = await res.json().catch(() => ({}));
|
|
|
+ rm();
|
|
|
+ const reply = data.reply || data.error || '请求失败';
|
|
|
+ addMsg('bot', reply, res.ok ? '' : 'notify-error', data.artifact || null);
|
|
|
+ if (data.profile_update) addMsg('bot', '检测到档案更新,请确认是否保存。', '', data.profile_update);
|
|
|
+ /* BUG-31:后端算好的机器可读原因原先在前端零消费——用户只拿到一段自然语言,
|
|
|
+ 看不出到底违反了哪几条,而 `workflow_state` 本来就是"现在能不能保存"的权威
|
|
|
+ 信号。两者都渲染出来,并据 workflow_state 禁用保存入口。 */
|
|
|
+ renderPlanValidation(data.plan_validation);
|
|
|
+ applyWorkflowState(data.workflow_state);
|
|
|
+ if (data.memory_candidate) {
|
|
|
+ addNotify('已生成待确认记忆:' + (data.memory_candidate.summary || '请在数据管理中查看并确认。'), 'notify-saved');
|
|
|
+ }
|
|
|
+ if (data.memory_confirmation) pendingMemoryEntryIds = [];
|
|
|
+ if (Array.isArray(data.memory_candidates)) {
|
|
|
+ pendingMemoryEntryIds = data.memory_candidates.map(item => item && item.entry_id).filter(Boolean);
|
|
|
+ } else if (data.memory_candidate && data.memory_candidate.entry_id) {
|
|
|
+ pendingMemoryEntryIds = [data.memory_candidate.entry_id];
|
|
|
+ }
|
|
|
+ if (data.reply) {
|
|
|
+ rememberConversation('user', text);
|
|
|
+ rememberConversation('assistant', reply);
|
|
|
+ }
|
|
|
+ // 每次聊天后刷新训练状态(Agent 可能已调用 MergeSetsTool 等)
|
|
|
+ await refreshWorkoutState();
|
|
|
+ if (data.artifact && data.artifact.type === 'nutrition_records') {
|
|
|
+ setViewerMode('nutrition', data.artifact.default_date || localDateISO());
|
|
|
+ } else if (data.artifact && ['training_records', 'training_plan'].includes(data.artifact.type)) {
|
|
|
+ setViewerMode('training', data.artifact.default_date || data.artifact.suggested_date || localDateISO());
|
|
|
+ } else if (requestedViewerMode) {
|
|
|
+ setViewerMode(requestedViewerMode);
|
|
|
+ }
|
|
|
+ } catch (err) {
|
|
|
+ rm();
|
|
|
+ addMsg('bot', '请求失败:' + err.message);
|
|
|
+ } finally {
|
|
|
+ $send.disabled = false;
|
|
|
+ $msg.focus();
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ $msg.addEventListener('keydown', (e) => {
|
|
|
+ if (e.key !== 'Enter' || e.shiftKey || e.isComposing) return;
|
|
|
+ e.preventDefault();
|
|
|
+ $form.requestSubmit();
|
|
|
+ });
|
|
|
+
|
|
|
+ /* ── Upload zone ───────────────────────────────────────────────────── */
|
|
|
+ function setUploadState(state, text) {
|
|
|
+ $fileUploadButton.className = state ? state : '';
|
|
|
+ $fileUploadButton.title = text || '上传训练、健康数据或计划';
|
|
|
+ $fileUploadButton.setAttribute('aria-label', $fileUploadButton.title);
|
|
|
+ $fileIn.disabled = state === 'uploading';
|
|
|
+ $fileUploadButton.disabled = state === 'uploading';
|
|
|
+ }
|
|
|
+
|
|
|
+ async function handleFile(file) {
|
|
|
+ if (!file) return;
|
|
|
+ const name = file.name.toLowerCase();
|
|
|
+
|
|
|
+ if (!name.endsWith('.fit') && !name.endsWith('.md') && !name.endsWith('.txt')) {
|
|
|
+ setUploadState('err', '请选择 .fit、.zip、.csv 或 .md 格式的文件');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ const MiB = 1024 * 1024;
|
|
|
+ const isPlan = name.endsWith('.md') || name.endsWith('.txt');
|
|
|
+ if (isPlan && file.size > MiB) {
|
|
|
+ setUploadState('err', '训练计划文件不能超过 1 MiB');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (!isPlan && file.size > 50 * MiB) {
|
|
|
+ setUploadState('err', 'FIT 文件不能超过 50 MiB');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ let confirmedLargePlan = false;
|
|
|
+ if (isPlan && file.size > 256 * 1024) {
|
|
|
+ const sizeMiB = (file.size / MiB).toFixed(2);
|
|
|
+ confirmedLargePlan = window.confirm(
|
|
|
+ `该训练计划大小为 ${sizeMiB} MiB。大文件会占用更多解析时间和模型上下文,是否继续?`
|
|
|
+ );
|
|
|
+ if (!confirmedLargePlan) {
|
|
|
+ setUploadState('', '已取消大文件上传');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ setUploadState('uploading', '解析中,请稍候…');
|
|
|
+ const fd = new FormData();
|
|
|
+ fd.append('file', file);
|
|
|
+ if (isPlan) fd.append('confirm_large', String(confirmedLargePlan));
|
|
|
+
|
|
|
+ if (name.endsWith('.md') || name.endsWith('.txt')) {
|
|
|
+ try {
|
|
|
+ const res = await fetch('/upload_plan', { method: 'POST', body: fd });
|
|
|
+ const data = await res.json();
|
|
|
+ if (data.status === 'manual_confirmation_required') {
|
|
|
+ if (!window.confirm('当前已关闭外部模型,系统无法自动判断这是否为训练计划。是否仍按训练计划纳管?')) {
|
|
|
+ setUploadState('', '已取消手动纳管'); return;
|
|
|
+ }
|
|
|
+ setUploadState('done', file.name + ' 已按手动确认纳管');
|
|
|
+ const subject = data.subject || '综合训练';
|
|
|
+ pendingMessageSource = 'uploaded_plan';
|
|
|
+ pendingPlanContext = { suggested_date: localDateISO(), subject };
|
|
|
+ $msg.value = `我确认这是一份训练计划,科目是“${subject}”。请基于以下原文整理并生成可保存计划:\n\n${data.content}`;
|
|
|
+ $form.requestSubmit();
|
|
|
+ } else if (data.status === 'ok') {
|
|
|
+ if (data.valid) {
|
|
|
+ setUploadState('done', file.name + ' 校验通过');
|
|
|
+ const suggestedName = `${localDateISO().slice(2)}-${data.subject}.md`;
|
|
|
+ const prompt = `我上传了一份训练计划。系统初步识别训练科目为“${data.subject}”,请你结合计划内容复核科目。\n\n${data.content}\n\n请解析并优化计划;如果缺少教学视频链接,为每个单独动作补全2个参考视频。回复中必须明确告诉我最终识别的训练科目,并按 YY-MM-DD-训练科目.md 格式给出建议保存文件名(初步建议:${suggestedName})。计划会由界面的“保存到本地”按钮保存,无需询问用户是否保存。`;
|
|
|
+ pendingMessageSource = 'uploaded_plan';
|
|
|
+ pendingPlanContext = { suggested_date: localDateISO(), subject: data.subject };
|
|
|
+ $msg.value = prompt;
|
|
|
+ $form.requestSubmit();
|
|
|
+ } else {
|
|
|
+ setUploadState('err', '非训练计划文件');
|
|
|
+ addNotify('被鉴定网关拦截(原因:' + (data.reason || '非训练计划') + ')', 'notify-skipped');
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ setUploadState('err', data.message || '解析失败');
|
|
|
+ addMsg('bot', '上传失败:' + (data.message || '未知错误'));
|
|
|
+ }
|
|
|
+ } catch (err) {
|
|
|
+ setUploadState('err', '网络异常:' + err.message);
|
|
|
+ }
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ // FIT 文件逻辑
|
|
|
+ try {
|
|
|
+ if (hasWorkout && !savedRecordEditingTarget() && !window.confirm('导入新训练会覆盖当前待确认训练,继续吗?')) return;
|
|
|
+ if (hasWorkout && !savedRecordEditingTarget()) fd.append('overwrite_pending', 'true');
|
|
|
+ const res = await fetch('/upload_fit', { method: 'POST', body: fd });
|
|
|
+ const data = await res.json();
|
|
|
+
|
|
|
+ if (data.status === 'ok') {
|
|
|
+ setViewerMode('training');
|
|
|
+ setUploadState('done', file.name + ' 解析完成');
|
|
|
+ addMsg('bot', data.message);
|
|
|
+ if (data.workout) {
|
|
|
+ leaveSavedTrainingRecordMode();
|
|
|
+ renderWorkout(data.workout);
|
|
|
+ }
|
|
|
+ await refreshWorkoutState(true);
|
|
|
+ startPolling();
|
|
|
+ } else if (data.status === 'empty') {
|
|
|
+ /* BUG-10:文件读得动、解析没报错,只是没有可用分段。这既不是成功
|
|
|
+ (原实现按成功报,于是"整场训练被丢光"和"一切正常"长得一模一样),
|
|
|
+ 也不是上传失败——套上"上传失败:" 会让用户去重传一个传得好好的文件。*/
|
|
|
+ setUploadState('err', file.name + ' 未解析出训练分段');
|
|
|
+ addMsg('bot', data.message);
|
|
|
+ } else {
|
|
|
+ setUploadState('err', data.message || '解析失败');
|
|
|
+ addMsg('bot', '上传失败:' + (data.message || '未知错误'));
|
|
|
+ }
|
|
|
+ } catch (err) {
|
|
|
+ setUploadState('err', '网络异常:' + err.message);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async function handleHealthFiles(files) {
|
|
|
+ if (!files.length || files.length > 5) {
|
|
|
+ setUploadState('err', '每次请选择 1-5 个健康数据文件');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const MiB = 1024 * 1024;
|
|
|
+ for (const file of files) {
|
|
|
+ const name = file.name.toLowerCase();
|
|
|
+ if (!name.endsWith('.zip') && !name.endsWith('.csv')) {
|
|
|
+ setUploadState('err', '健康数据批次只能包含 .zip 或 .csv');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ const limit = name.endsWith('.zip') ? 50 * MiB : 2 * MiB;
|
|
|
+ if (file.size > limit) {
|
|
|
+ setUploadState('err', file.name + ' 超过大小限制');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ setUploadState('uploading', '正在解析并保存健康数据…');
|
|
|
+ const fd = new FormData();
|
|
|
+ files.forEach(file => fd.append('files', file));
|
|
|
+ try {
|
|
|
+ const response = await fetch('/upload_health', {method:'POST', body:fd});
|
|
|
+ const data = await response.json();
|
|
|
+ if (!response.ok || data.status === 'error') {
|
|
|
+ setUploadState('err', '健康数据导入失败');
|
|
|
+ addMsg('bot', data.message || '健康数据导入失败');
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ setUploadState('done', data.status === 'partial' ? '部分文件已导入' : '健康数据已导入');
|
|
|
+ addMsg('bot', data.message || '健康数据已解析并保存。');
|
|
|
+ if ((data.unprocessed_files || []).length) {
|
|
|
+ addNotify(
|
|
|
+ '未处理文件:' + data.unprocessed_files.map(item =>
|
|
|
+ (item.zip ? item.zip + ' › ' : '') + item.filename
|
|
|
+ ).join('、'),
|
|
|
+ 'notify-skipped',
|
|
|
+ );
|
|
|
+ }
|
|
|
+ if (data.workout) {
|
|
|
+ leaveSavedTrainingRecordMode();
|
|
|
+ renderWorkout(data.workout);
|
|
|
+ addNotify('已从压缩包识别到训练 FIT,已载入训练编辑区。', 'notify-saved');
|
|
|
+ startPolling();
|
|
|
+ } else if ((data.activities || []).length > 1) {
|
|
|
+ // BUG-08:跨多个 ZIP 的活动也要能逐个处理。后端现在只在全局恰好一个
|
|
|
+ // 活动时才自动载入,其余情况一律交给选择器,不再静默丢掉第 2 个之后的。
|
|
|
+ openActivityPicker(files, data.activities);
|
|
|
+ } else if ((data.activity_files || []).length > 1 && files.length === 1) {
|
|
|
+ // 兼容旧响应(只有扁平名字列表)
|
|
|
+ openActivityPicker(files, data.activity_files.map(name => ({zip: files[0].name, name})));
|
|
|
+ }
|
|
|
+ await refreshHealthTrend(false);
|
|
|
+ if ($healthModal.classList.contains('show')) await loadDailyOverview();
|
|
|
+ if ($dataModal.classList.contains('show')) await loadDataOverview();
|
|
|
+ } catch (err) {
|
|
|
+ setUploadState('err', '网络异常:' + err.message);
|
|
|
+ addMsg('bot', '健康数据上传失败:' + err.message);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function closeActivityPicker(clear = true) {
|
|
|
+ if (clear) {
|
|
|
+ activityPickerFiles = [];
|
|
|
+ activePickerActivity = '';
|
|
|
+ }
|
|
|
+ $activityPickerModal.classList.remove('show');
|
|
|
+ $activityPickerModal.setAttribute('aria-hidden', 'true');
|
|
|
+ document.body.style.overflow = '';
|
|
|
+ }
|
|
|
+
|
|
|
+ function activityKey(item) {
|
|
|
+ // 两个 ZIP 里可能有同名 FIT,所以键必须带上来源
|
|
|
+ return (item.zip || '') + '
|