🎮ArcadeLab

简易电路实验展示 · 物理课堂演示

by ElectricWizard16
8608 lines467.6 KB
▶ Play
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5, viewport-fit=cover">
<meta name="format-detection" content="telephone=no">
<meta name="theme-color" content="#12305a">
<title>简易电路实验展示 · 物理课堂演示</title>
<style>
  *{box-sizing:border-box}
  html,body{margin:0;padding:0}
  html{-webkit-text-size-adjust:100%;text-size-adjust:100%;color-scheme:light}
  body{
    font-family:"Microsoft YaHei","PingFang SC","Hiragino Sans GB","Segoe UI",system-ui,sans-serif;
    background:#eef3fa;color:#16233a;-webkit-font-smoothing:antialiased;
    overflow-x:hidden;
  }
  header{
    background:linear-gradient(90deg,#12305a,#25558f 60%,#2d6fae);
    color:#fff;padding:14px 22px;display:flex;align-items:baseline;gap:16px;flex-wrap:wrap;
  }
  header h1{margin:0;font-size:20px;letter-spacing:1px}
  header .sub{font-size:12.5px;opacity:.82}
  main{display:grid;grid-template-columns:156px minmax(0,1fr) clamp(300px,22vw,420px);gap:12px;padding:12px;align-items:start}
  /* 左侧读数长条:窄、常驻、内部可滚(元件很多时不挤占画布) */
  /* 显式指定三列归属(不依赖 DOM 顺序)*/
  main > .readout-strip{grid-column:1;grid-row:1}
  main > .stage{grid-column:2;grid-row:1}
  main > aside.panel{grid-column:3;grid-row:1}
  .readout-strip{align-self:start;position:sticky;top:12px}
  .readout-strip .card{padding:8px 8px 9px}
  .readout-strip .card h3{font-size:12px;margin:0 0 5px}
  .readout-strip .card h3::before{height:12px;width:3px}
  .readout-strip .readouts{max-height:calc(100vh - 200px);overflow:auto;gap:3px}
  .readout-strip .readouts .row{flex-direction:column;align-items:stretch;gap:0;padding:3px 6px;border-radius:6px}
  .readout-strip .readouts .name{font-size:10.5px;line-height:1.3}
  .readout-strip .readouts .val{font-size:12px;text-align:left;line-height:1.35}
  .readout-strip .cmp-title,.readout-strip .cmp-meta,.readout-strip .cmp-note{font-size:10px}
  @media (max-width: 1240px){
    main{grid-template-columns:132px minmax(0,1fr) clamp(280px,24vw,360px)}
    .readout-strip .readouts .val{font-size:11.5px}
  }
  body.mobile .readout-strip{display:none}     /* 手机端这张卡在"数据"抽屉里 */
  .stage{background:#fff;border-radius:14px;box-shadow:0 6px 22px rgba(20,45,90,.10);padding:12px;display:flex;flex-direction:column;gap:10px;min-width:0}
  .toolbar{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
  /* 演示电路下拉菜单 */
  .menugroup{position:relative}
  .menupop{
    position:absolute;right:0;top:calc(100% + 6px);z-index:50;min-width:260px;
    background:#fff;border:1px solid #dbe5f4;border-radius:12px;padding:8px;
    box-shadow:0 14px 40px rgba(12,30,60,.22);
  }
  .menupop[hidden]{display:none}
  #btnPresets.on{background:#2d6fae;border-color:#2d6fae;color:#fff}
  .mobile-presets{gap:8px}
  .mobile-presets button{font-size:14px;padding:12px 12px;min-height:56px}
  .mobile-presets button small{font-size:12px}
  .menutitle{font-size:12px;color:#7b8db0;padding:2px 8px 8px}
  .menulist{display:flex;flex-direction:column;gap:4px}
  .menulist button{
    display:grid;grid-template-columns:34px 1fr;align-items:center;gap:2px 8px;text-align:left;
    padding:8px 10px;border-radius:9px;font-size:13.5px;font-weight:600;min-height:0;
  }
  .menulist button small{grid-column:2;font-size:11.5px;color:#7b8db0;font-weight:400}
  .menulist .mglyph{grid-row:span 2;font-size:16px;color:#2d6fae;text-align:center}
  .caret{font-size:10px;opacity:.7;margin-left:2px}
  .ico-glyph{font-size:15px}
  /* 顶部小气泡提示(添加元件等操作反馈) */
  .toast{
    position:fixed;left:50%;top:12px;transform:translate(-50%,-14px);z-index:80;
    background:rgba(18,48,90,.94);color:#fff;font-size:13px;font-weight:600;
    padding:8px 16px;border-radius:20px;box-shadow:0 8px 24px rgba(10,25,50,.28);
    opacity:0;pointer-events:none;transition:opacity .18s ease,transform .18s ease;
  }
  .toast.on{opacity:1;transform:translate(-50%,0)}
  body.dark .toast{background:rgba(30,70,120,.95)}
  .toolbar button.ico{display:inline-flex;align-items:center;justify-content:center;gap:5px}
  .toolbar button.ico .icg{font-size:17px;line-height:1}
  .toolbar button.ico .lbl{font-size:13px;line-height:1;white-space:nowrap}
  .toolbar button.ico .lbl-m{display:none;font-size:10.5px;line-height:1;white-space:nowrap}
  body.dark .menupop{background:#152238;border-color:#2a4059}
  body.dark .menulist button small{color:#8ea6c4}
  body.dark .menulist .mglyph{color:#7fb6f0}
  /* 操作按钮图标放大一点,更好点 */
  .toolbar button.ico{font-size:15px;padding:9px 12px;min-height:42px}
  .toolbar button.ico .glyph{font-size:16px}
  @media (max-width:820px){
    .toolbar button.ico{font-size:16px;padding:9px 13px;min-height:44px}
  }
  .toolbar .group{display:flex;gap:8px;flex-wrap:wrap;align-items:center;padding:0 8px 0 0;border-right:1px solid #e3eaf5}
  .toolbar .group:last-child{border-right:none}
  .toolbar .cap{font-size:12px;color:#7b8db0;margin-right:2px}
  button{font-family:inherit;cursor:pointer;border-radius:9px;border:1px solid #cddcf0;background:#f6faff;color:#1d3763;font-size:13px;padding:6px 11px;transition:.15s}
  button[disabled]{opacity:.42;cursor:not-allowed}
  button[disabled]:hover{background:#fff;border-color:#dbe5f4;color:#5b6b86}
  button:hover{background:#e8f1ff;border-color:#9fc0ea}
  button.primary{background:#2d6fae;border-color:#2d6fae;color:#fff}
  button.primary:hover{background:#255c93}
  button.danger{background:#fff3f3;border-color:#f0c2c2;color:#a53434}
  button.danger:hover{background:#ffe6e6}
  button.on{background:#1d7f5f;border-color:#1d7f5f;color:#fff}
  .canvas-wrap{position:relative;border-radius:12px;overflow:hidden;border:1px solid #dbe5f4;background:#fbfdff;height:min(62vh,780px)}
  /* ===== 电脑版:底部操作条(撤销/重做/清空/缩放/缩略图/音效/删除元件)钉在画布下方,做得大一点 ===== */
  .toolbar button.only-desktop{display:none !important}
  /* 电脑模式才显示(不只看窗口宽度:手动切到手机版时也要隐藏,否则按钮与模式不一致) */
  body:not(.mobile) .toolbar button.only-desktop{display:inline-flex !important}
  @media (min-width: 901px) {
    .stage{position:relative;padding-bottom:92px}
    .toolbar .group-bottom{
      position:absolute;left:12px;right:12px;bottom:12px;
      display:flex;gap:8px;padding:0;border-right:none;justify-content:flex-start;
    }
    .toolbar .group-bottom .ico{
      flex:1 1 0;min-width:0;min-height:62px;flex-direction:column;gap:3px;
      justify-content:center;border-radius:11px;padding:4px 2px;
    }
    .toolbar .group-bottom .ico .icg{font-size:23px}
    .toolbar .group-bottom .ico .lbl{font-size:13px}
    .toolbar .group-bottom .zoomgroup{
      display:flex;flex:0 0 auto;align-items:center;gap:6px;
      border-left:1px solid #e3eaf5;border-right:1px solid #e3eaf5;padding:0 8px;
    }
    body.dark .toolbar .group-bottom .zoomgroup{border-left-color:#25384f;border-right-color:#25384f}
    .toolbar .group-bottom .zoomgroup .ico{min-height:62px;min-width:56px;flex:0 0 auto}
    .toolbar .group-bottom .zoomlabel{font-size:14px;min-width:46px;text-align:center}
    .toolbar .group-bottom #btnDelSel{flex:1.25 1 0}
    /* 由 body:not(.mobile) 统一控制(见下方),这里不再重复 */
    /* 上方剩下的按钮也放大一点 */
    .toolbar .group:not(.group-bottom) .ico{min-height:50px;padding:4px 12px;border-radius:11px}
    .toolbar .group:not(.group-bottom) .ico .icg{font-size:20px}
    .toolbar .group:not(.group-bottom) .ico .lbl{font-size:13.5px}
  }
  canvas{display:none;touch-action:none}
  /* 缩略图(右下角),可拖动左上角手柄调整大小 */
  .minimap{
    position:absolute;right:12px;bottom:12px;width:176px;height:112px;border-radius:9px;overflow:hidden;
    border:1px solid #cddcf0;background:rgba(255,255,255,.92);box-shadow:0 4px 14px rgba(20,45,90,.18);
    touch-action:none;z-index:4;
  }
  .minimap canvas{display:block;width:100%;height:100%;cursor:crosshair}
  /* 标题栏把手:拖它移动缩略图(画布区域仍然是"点击/拖动跳转视野") */
  .minimap .mm-bar{
    position:absolute;left:0;right:0;top:0;height:18px;z-index:3;
    display:flex;align-items:center;gap:4px;padding:0 20px 0 7px;
    font-size:10.5px;color:#5b7ba6;letter-spacing:.5px;
    background:rgba(238,245,254,.94);border-bottom:1px solid rgba(205,220,240,.9);
    cursor:move;user-select:none;touch-action:none;
  }
  .minimap .mm-bar .mm-grip{font-size:11px;color:#8fa6c4}
  .minimap.mm-dragging{box-shadow:0 8px 24px rgba(20,45,90,.30);border-color:#2d6fae}
  body.dark .minimap .mm-bar{background:rgba(17,32,58,.94);color:#8fb4dc;border-bottom-color:#2c4058}
  body.dark .minimap .mm-bar .mm-grip{color:#5f7fa6}
  .minimap .mm-handle{
    position:absolute;right:0;bottom:0;width:18px;height:18px;cursor:nwse-resize;z-index:4;
    background:linear-gradient(315deg,#2d6fae 0 44%,transparent 44%);
  }
  .minimap .mm-close{
    position:absolute;right:0;top:0;width:20px;height:20px;min-height:0;padding:0;line-height:1;
    border:none;border-radius:0 8px 0 8px;background:rgba(45,111,174,.9);color:#fff;font-size:13px;
    z-index:5;                                /* 必须在标题栏之上,否则会被栏的背景盖住 */
  }
  .minimap .mm-close:hover{background:#2d6fae}
  body.dark .minimap{background:rgba(11,20,32,.92);border-color:#2c4058}
  body.dark .minimap .mm-close{background:rgba(95,168,232,.9);color:#0b1420}
  .zoomlabel{display:inline-block;min-width:46px;text-align:center;font-size:12.5px;color:#25558f;font-weight:700;font-variant-numeric:tabular-nums}
  .hint{font-size:12.5px;color:#6c7f9e;line-height:1.7;background:#f5f9ff;border:1px dashed #d3e0f2;border-radius:10px;padding:8px 12px}
  .hint b{color:#25558f}
  .panel{display:flex;flex-direction:column;gap:12px}
  /* 右栏顺序(上→下):添加元件 → 选中元件 → 电路状态 → 课堂提示 */
  .panel > #paletteCard{order:-3}
  .panel > #inspectorCard{order:-2}
  .panel > #statusCard{order:-1}
  .panel > #tipsCard{order:3}
  .card{background:#fff;border-radius:12px;box-shadow:0 6px 22px rgba(20,45,90,.10);padding:9px 11px}
  .card h3{margin:0 0 6px;font-size:13.5px;color:#25558f;letter-spacing:.5px;display:flex;align-items:center;gap:6px}
  .card h3::before{content:"";width:4px;height:14px;border-radius:2px;background:#2d6fae}
  .badge{display:inline-block;padding:6px 14px;border-radius:20px;font-size:14px;font-weight:700;letter-spacing:1px;margin-bottom:10px}
  .badge.open{background:#eef2f8;color:#6c7f9e}
  .badge.on{background:#e2f7ee;color:#12734f}
  .badge.short{background:#ffe9e9;color:#c02a2a;animation:pulse 1s infinite}
  .badge.heavy{background:#fff4e0;color:#a4650a}          /* 重载:偏橙 */
  .badge.charge{background:#e6f0ff;color:#1d5fa8}          /* 充电中:偏蓝 */
  @keyframes pulse{50%{opacity:.55}}
  .kv{display:flex;justify-content:space-between;font-size:12.5px;padding:1.5px 0;color:#465a7a;line-height:1.5}
  /* 派生量一行三项(内阻分压 / 内部损耗 / 电源效率),省两行高度 */
  .kv-3{display:flex;gap:6px;font-size:11.5px;color:#465a7a;padding:2px 0 3px;line-height:1.4}
  .kv-3 span{flex:1 1 0;min-width:0;background:#f6faff;border-radius:7px;padding:3px 6px;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  .kv-3 b{color:#12294d;font-variant-numeric:tabular-nums}
  body.dark .kv-3{color:#a9bdd6}
  body.dark .kv-3 span{background:#12203a}
  body.dark .kv-3 b{color:#eaf2fd}
  .kv b{color:#12294d;font-variant-numeric:tabular-nums}
  .readouts{display:flex;flex-direction:column;gap:4px;font-size:12.5px}
  .readouts .row{display:flex;justify-content:space-between;align-items:center;background:#f6faff;border-radius:7px;padding:4px 9px}
  .readouts .name{color:#47597a}
  .readouts .val{font-weight:700;color:#12294d;font-variant-numeric:tabular-nums}
  .readouts .val.hot{color:#c9701a}
  .readouts .empty{color:#93a3bd;font-size:12.5px}
  .inspector{font-size:13px;display:grid;grid-template-columns:1fr 1fr;gap:8px 12px}
  /* 参数滑块自动两列;按钮行/说明/标题等横跨整行 */
  .inspector > *:not(.field){grid-column:1 / -1}
  .inspector > .fields{grid-column:1 / -1;display:grid;grid-template-columns:1fr 1fr;gap:8px 12px}
  /* 参数区两列排布:横排滑块、竖排说明,省一半高度 */
  .inspector .fields{display:grid;grid-template-columns:1fr 1fr;gap:8px 12px}
  .inspector .fields .field{min-width:0}
  .insp-title{font-weight:700;color:#1d3763}
  .insp-note{
    color:#6c7f9e;font-size:11.5px;line-height:1.55;opacity:.9;
    margin:10px 0 2px;padding:6px 0 6px 9px;border-left:2px solid rgba(120,150,190,.35);
  }
  .insp-empty{color:#93a3bd;font-size:12.5px;line-height:1.7}
  .inspector .field{display:flex;flex-direction:column;gap:3px}
  .inspector .btnrow{display:flex;gap:6px}
  .inspector .btnrow button{padding:4px 6px;font-size:12.5px}
  .inspector > button{padding:5px 6px}
  .inspector .btnrow button{flex:1 1 0}
  /* 长说明折叠,默认收起,点开才占地方 */
  .inspector details.note{border-left:2px solid rgba(120,150,190,.35);padding-left:9px}
  .inspector details.note summary{cursor:pointer;color:#6c7f9e;font-size:11.5px;list-style:none}
  .inspector details.note summary::-webkit-details-marker{display:none}
  .inspector details.note summary::before{content:'▸ ';font-size:10px}
  .inspector details.note[open] summary::before{content:'▾ '}
  .inspector details.note .insp-note{margin:4px 0 0;padding:0;border:0}
  .inspector .field label{display:flex;justify-content:space-between;color:#47597a}
  .inspector .field label span{font-weight:700;color:#1d3763;font-variant-numeric:tabular-nums}
  input[type=range]{width:100%;accent-color:#2d6fae}
  .tips{font-size:12.5px;line-height:1.6;color:#4a5d7d;max-height:132px;overflow:auto}
  /* 课堂提示整张卡可折叠:默认收起只占一行,要讲课时点开 */
  .card.tips-card > details > summary{
    cursor:pointer;list-style:none;color:#25558f;font-size:13.5px;font-weight:600;
    display:flex;align-items:center;gap:6px;letter-spacing:.5px;
  }
  .card.tips-card > details > summary::-webkit-details-marker{display:none}
  .card.tips-card > details > summary::before{content:'';width:4px;height:14px;border-radius:2px;background:#2d6fae}
  .card.tips-card > details > summary::after{content:'▾';margin-left:auto;color:#7b8db0}
  .card.tips-card > details:not([open]) > summary::after{content:'▸'}
  .card.tips-card > details[open] > summary{margin-bottom:8px}
  body.dark .card.tips-card > details > summary{color:#a9d0f5}
  .tips .sh{color:#c02a2a;font-weight:700}
  .tips .bad{color:#12734f;font-weight:700}
  .tips ul{margin:6px 0 0;padding-left:18px}
  .legend{display:flex;gap:14px;flex-wrap:wrap;font-size:12px;color:#6c7f9e;margin-top:2px}
  .legend i{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:4px;vertical-align:middle}
  /* 操作说明:放在面板下层的可折叠菜单,手机上默认收起,方便直接操作“添加元件” */
  .hintcard{background:#fff;border-radius:14px;box-shadow:0 6px 22px rgba(20,45,90,.10);overflow:hidden}
  .hintcard>summary{
    cursor:pointer;list-style:none;padding:12px 14px;font-size:13.5px;color:#25558f;font-weight:700;
    display:flex;align-items:center;gap:8px;touch-action:manipulation;
  }
  .hintcard>summary::-webkit-details-marker{display:none}
  .hintcard>summary::before{content:"";width:4px;height:14px;border-radius:2px;background:#2d6fae;flex:0 0 auto}
  .hintcard>summary::after{content:"展开 ▾";margin-left:auto;font-size:12px;color:#7b8db0;font-weight:500}
  .hintcard[open]>summary::after{content:"收起 ▴"}
  .hintcard .hintbody{padding:0 14px 12px}
  /* 操作学习:跟在目标旁边的提示气泡 */
  #learnTip{
    position:fixed;z-index:80;display:none;max-width:230px;
    padding:7px 11px;border-radius:10px;
    background:#ff9d2e;color:#241300;font-size:13px;font-weight:700;line-height:1.35;
    box-shadow:0 6px 20px rgba(0,0,0,.35);pointer-events:none;
  }
  #learnTip.on{display:block}
  #learnTip::after{
    content:'';position:absolute;right:-7px;top:14px;
    border:7px solid transparent;border-left-color:#ff9d2e;
  }
  /* 操作学习:要点按钮高亮脉冲 */
  .learn-hl.field{border-radius:10px;padding:6px 8px !important;background:rgba(255,157,46,.10)}
  /* 课堂提示里的补充说明与警告 */
  .tips .tip-dim{color:#8fa2bd;font-size:12px;line-height:1.6}
  .tips .tip-warn{
    margin-top:6px;padding:6px 9px;border-radius:8px;
    background:rgba(255,157,46,.12);border-left:3px solid rgba(255,157,46,.85);
    color:#8a5a12;font-size:12.5px;line-height:1.6;
  }
  body.dark .tips .tip-dim{color:#7f95b3}
  body.dark .tips .tip-warn{background:rgba(255,157,46,.14);color:#ffc061}

  .learn-hl{
    position:relative;z-index:60;
    box-shadow:0 0 0 3px #ff9d2e, 0 0 22px 6px rgba(255,157,46,.55) !important;
    animation:learnPulse 1.1s ease-in-out infinite;
  }
  @keyframes learnPulse{
    0%,100%{box-shadow:0 0 0 3px #ff9d2e,0 0 14px 3px rgba(255,157,46,.40) !important}
    50%{box-shadow:0 0 0 4px #ffb457,0 0 26px 9px rgba(255,157,46,.70) !important}
  }
  /* ===== 操作学习:确认窗口(居中)→ 进入后停靠画布左下角(横向长条,不挡画布) ===== */
  #learnOverlay.docked{
    background:transparent !important;
    backdrop-filter:none !important;              /* 关键:清掉整页模糊("雾化"来自 .lib-overlay 的 blur(2px)) */
    -webkit-backdrop-filter:none !important;
    align-items:flex-end !important; justify-content:flex-start !important;
    padding:0 0 102px 14px !important;       /* 上移:让开底部操作条,占用画布左下角 */
    pointer-events:none !important;          /* 关键:不再拦截画布上的点击 */
  }
  #learnOverlay.docked .learn-panel{
    pointer-events:auto;                     /* 只有长条本身可点 */
    width:min(720px,66vw);max-width:calc(100vw - 32px);
    border-radius:12px;box-shadow:0 10px 30px rgba(6,20,45,.35);
  }
  #learnOverlay.docked .learn-body{
    display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;
    min-height:0;padding:10px 14px 8px;
  }
  #learnOverlay.docked .learn-body .learn-step{flex:0 0 auto;margin:0}
  #learnOverlay.docked .learn-body h3{flex:0 0 auto;font-size:14.5px;margin:0}
  #learnOverlay.docked .learn-body p{flex:1 1 200px;font-size:12.5px;line-height:1.5}
  #learnOverlay.docked .learn-dots-wrap{padding:0 14px 6px}
  #learnOverlay.docked .learn-foot{padding:0 14px 12px;gap:8px}
  #learnOverlay.docked .learn-btn{min-height:38px;font-size:13px;flex:0 0 auto;padding:0 16px}
  #learnOverlay.docked .learn-foot{justify-content:flex-end}
  /* 底部留白用变量 --mstack:由 resize() 按"底部栏+元件栏+提示条"的真实高度算出 */
  body.mobile #learnOverlay.docked{padding:0 0 var(--mstack,104px) 8px !important}
  /* 抽屉打开时先把学习条藏起来(它在"添加元件"面板上面会让第 1 步点不到元件) */
  body.mobile #learnOverlay.hide-for-sheet{display:none !important}
  /* 手机端做紧凑:只留步号+标题+按钮,长说明交给画布上的注解 */
  body.mobile #learnOverlay.docked .learn-head{padding:5px 10px 3px}
  body.mobile #learnOverlay.docked .learn-head b{display:none}   /* 手机端省掉"操作学习"标题行,只留关闭按钮 */
  body.mobile #learnOverlay.docked .learn-head b{font-size:13px}
  body.mobile #learnOverlay.docked .learn-body{display:block;padding:7px 12px 4px}
  body.mobile #learnOverlay.docked .learn-body p{display:none}
  body.mobile #learnOverlay.docked .learn-body h3{font-size:13.5px;margin:2px 0 0}
  body.mobile #learnOverlay.docked .learn-step{font-size:11px}
  body.mobile #learnOverlay.docked .learn-dots-wrap{display:none}
  body.mobile #learnOverlay.docked .learn-foot{padding:0 12px 10px}
  body.mobile #learnOverlay.docked .learn-btn{min-height:42px;font-size:13.5px;flex:1;padding:0 10px}
  body.mobile #learnOverlay.docked .learn-panel{width:calc(100vw - 28px);max-width:calc(100vw - 28px)}
  /* 操作学习面板 */
  .learn-panel{
    width:min(560px,92vw);background:#fff;border-radius:16px;overflow:hidden;
    box-shadow:0 18px 50px rgba(6,20,45,.4);display:flex;flex-direction:column;
  }
  body.dark .learn-panel{background:#152238;color:#e8f0fb}
  .learn-head{display:flex;align-items:center;gap:8px;padding:12px 16px;border-bottom:1px solid #e3eaf5}
  .learn-head b{font-size:15px;color:#12294d}
  body.dark .learn-head{border-bottom-color:#2a4059}
  body.dark .learn-head b{color:#eaf2fd}
  .learn-head .lib-close{margin-left:auto}
  .learn-body{padding:16px 18px 6px;min-height:190px}
  .learn-step{font-size:12px;color:#2d6fae;font-weight:700;letter-spacing:.5px;margin-bottom:6px}
  .learn-body h3{font-size:17px;color:#12294d;margin:0 0 10px}
  body.dark .learn-body h3{color:#eaf2fd}
  .learn-body p{font-size:13.5px;line-height:1.75;color:#3c4c66;margin:0}
  body.dark .learn-body p{color:#c2d3e8}
  .learn-do{
    margin-top:12px;padding:9px 12px;border-radius:9px;background:#eaf2fd;color:#1f4e79;
    font-size:12.5px;font-weight:600;
  }
  body.dark .learn-do{background:#16263c;color:#9ec7f5}
  .learn-dots-wrap{padding:10px 18px 0}
  .learn-dots{display:flex;gap:5px;flex-wrap:wrap}
  .learn-dots i{width:18px;height:4px;border-radius:2px;background:#dbe5f4;display:block}
  .learn-dots i.on{background:#2d6fae}
  body.dark .learn-dots i{background:#2a4059}
  .learn-foot{display:flex;gap:10px;padding:14px 18px 16px}
  .learn-btn{
    flex:1;min-height:44px;border-radius:10px;font-size:14px;font-weight:600;
    border:1px solid #dbe5f4;background:#f6faff;color:#2c4a72;
  }
  .learn-btn.primary{background:#2d6fae;border-color:#2d6fae;color:#fff}
  .learn-btn:disabled{opacity:.45}
  body.dark .learn-btn{background:#1b2b42;border-color:#2c4058;color:#d7e5f7}
  body.dark .learn-btn.primary{background:#2d6fae;border-color:#2d6fae;color:#fff}

  /* 「关于 / 帮助」浮层内容排版 */
  .about-side{overflow:auto}
  .about-sidehead{font-size:11px;color:#7b8db0;padding:6px 4px;letter-spacing:1px}
  .about-nav{display:block;width:100%;text-align:left;background:transparent;border:none;color:#2c4a72;
    font-size:12.5px;padding:6px 8px;border-radius:8px;cursor:pointer;line-height:1.35}
  .about-nav:hover{background:#eaf2fd}
  body.dark .about-nav{color:#cfe0f5}
  body.dark .about-nav:hover{background:#1d3452}
  .about-title{font-size:20px;color:#12294d;margin:0 0 4px}
  body.dark .about-title{color:#eaf2fd}
  .about-lead{color:#5a6b85;font-size:13px;margin:0 0 10px}
  .about-h2{font-size:16px;color:#1f4e79;margin:18px 0 6px;padding-bottom:4px;border-bottom:1px solid #e3eaf5}
  body.dark .about-h2{color:#9ec7f5;border-bottom-color:#2a4059}
  .about-h3{font-size:13.5px;color:#2d6fae;margin:12px 0 4px}
  .about-main p{font-size:13px;line-height:1.7;color:#33445c;margin:5px 0}
  body.dark .about-main p{color:#c2d3e8}
  .about-ul,.about-ol{font-size:13px;line-height:1.7;color:#33445c;margin:5px 0 5px 18px;padding-left:8px}
  body.dark .about-ul,body.dark .about-ol{color:#c2d3e8}
  .about-tb{border-collapse:collapse;width:100%;margin:8px 0;font-size:12.5px}
  .about-tb th{background:#2d6fae;color:#fff;text-align:left;padding:6px 8px;border:1px solid #2d6fae}
  .about-tb td{padding:6px 8px;border:1px solid #dbe5f4;color:#33445c;vertical-align:top}
  body.dark .about-tb td{border-color:#2a4059;color:#c2d3e8}
  .about-pre{background:#f4f8fe;border:1px solid #dbe5f4;border-radius:8px;padding:10px;
    font-family:Consolas,"Courier New",monospace;font-size:11.5px;line-height:1.5;overflow:auto;color:#33445c}
  body.dark .about-pre{background:#101d2f;border-color:#2a4059;color:#c2d3e8}
  .about-hr{border:none;border-top:1px solid #e3eaf5;margin:14px 0}
  body.dark .about-hr{border-top-color:#2a4059}
  .about-q{font-size:13px;color:#5a6b85;border-left:3px solid #2d6fae;padding:2px 0 2px 10px;margin:8px 0}
  .about-note{font-size:12px;color:#7b8db0}
  .about-main code{font-family:Consolas,"Courier New",monospace;background:#eef4fd;color:#2d6fae;
    padding:1px 5px;border-radius:4px;font-size:12px}
  body.dark .about-main code{background:#16263c;color:#9ec7f5}
  /* 「关于 / 帮助」浮层内容排版 */
  .about-side{overflow:auto}
  .about-sidehead{font-size:11px;color:#7b8db0;padding:6px 4px;letter-spacing:1px}
  .about-nav{display:block;width:100%;text-align:left;background:transparent;border:none;color:#2c4a72;
    font-size:12.5px;padding:6px 8px;border-radius:8px;cursor:pointer;line-height:1.35}
  .about-nav:hover{background:#eaf2fd}
  body.dark .about-nav{color:#cfe0f5}
  body.dark .about-nav:hover{background:#1d3452}
  .about-title{font-size:20px;color:#12294d;margin:0 0 4px}
  body.dark .about-title{color:#eaf2fd}
  .about-lead{color:#5a6b85;font-size:13px;margin:0 0 10px}
  .about-h2{font-size:16px;color:#1f4e79;margin:18px 0 6px;padding-bottom:4px;border-bottom:1px solid #e3eaf5}
  body.dark .about-h2{color:#9ec7f5;border-bottom-color:#2a4059}
  .about-h3{font-size:13.5px;color:#2d6fae;margin:12px 0 4px}
  .about-main p{font-size:13px;line-height:1.7;color:#33445c;margin:5px 0}
  body.dark .about-main p{color:#c2d3e8}
  .about-ul,.about-ol{font-size:13px;line-height:1.7;color:#33445c;margin:5px 0 5px 18px;padding-left:8px}
  body.dark .about-ul,body.dark .about-ol{color:#c2d3e8}
  .about-tb{border-collapse:collapse;width:100%;margin:8px 0;font-size:12.5px}
  .about-tb th{background:#2d6fae;color:#fff;text-align:left;padding:6px 8px;border:1px solid #2d6fae}
  .about-tb td{padding:6px 8px;border:1px solid #dbe5f4;color:#33445c;vertical-align:top}
  body.dark .about-tb td{border-color:#2a4059;color:#c2d3e8}
  .about-pre{background:#f4f8fe;border:1px solid #dbe5f4;border-radius:8px;padding:10px;
    font-family:Consolas,"Courier New",monospace;font-size:11.5px;line-height:1.5;overflow:auto;color:#33445c}
  body.dark .about-pre{background:#101d2f;border-color:#2a4059;color:#c2d3e8}
  .about-hr{border:none;border-top:1px solid #e3eaf5;margin:14px 0}
  body.dark .about-hr{border-top-color:#2a4059}
  .about-q{font-size:13px;color:#5a6b85;border-left:3px solid #2d6fae;padding:2px 0 2px 10px;margin:8px 0}
  .about-note{font-size:12px;color:#7b8db0}
  .about-main code{font-family:Consolas,"Courier New",monospace;background:#eef4fd;color:#2d6fae;
    padding:1px 5px;border-radius:4px;font-size:12px}
  body.dark .about-main code{background:#16263c;color:#9ec7f5}
  .hint-mobile{display:none}                 /* 手机版提示只在手机版显示 */
  body.mobile .hint-mobile{display:block}
  body.mobile .hint-desktop{display:none}
  .palette{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
  .palette button{padding:8px 4px;font-size:12.5px;display:flex;flex-direction:column;align-items:center;gap:4px;line-height:1.2;min-height:50px}
  .palette button .glyph{font-size:18px}
  .palette .glyph{font-size:17px;line-height:1}
  /* 导体材料选择按钮 */
  .matgrid{display:grid;grid-template-columns:repeat(3,1fr);gap:5px;margin-bottom:2px}
  .matgrid button{padding:6px 2px;font-size:12px;min-height:34px}
  .matgrid button.on{background:#2d6fae;border-color:#2d6fae;color:#fff;font-weight:700}
  .btnrow{display:grid;grid-template-columns:1fr 1fr;gap:6px}
  /* 实验文件卡:保存 / 打开 / 导出图片(右侧栏常显;手机版搬进"📁文件"抽屉) */
  .file-acts{display:flex;flex-direction:column;gap:7px;margin-top:5px}
  .file-btn{display:flex;flex-direction:column;align-items:flex-start;gap:1px;width:100%;
    padding:8px 11px;border-radius:10px;border:1px solid #ccd7e6;background:#f6f9fd;
    cursor:pointer;font-size:13.5px;font-weight:600;color:#1b2b45;text-align:left;
    line-height:1.35;font-family:inherit}
  .file-btn small{font-weight:400;font-size:11.5px;color:#6b7f9e}
  .file-btn:hover{border-color:#25558f;color:#25558f}
  .file-btn:active{transform:translateY(1px)}
  body.dark .file-btn{background:#1a2a44;border-color:#2c4058;color:#dfe8f5}
  body.dark .file-btn small{color:#8fa3c0}
  body.dark .file-btn:hover{border-color:#4a90e2;color:#7db8ff}
  .btnrow button{padding:7px 4px;font-size:12.5px}
  /* 导体对比表 */
  .cmp{margin-top:10px;border-top:1px dashed #d3e0f2;padding-top:9px}
  .cmp-title{font-size:12.5px;color:#25558f;font-weight:700;margin-bottom:7px}
  .cmp-item{margin-bottom:7px}
  .cmp-line{display:flex;align-items:baseline;gap:6px;font-size:12px}
  .cmp-name{font-weight:700;color:#12294d;min-width:52px}
  .cmp-meta{color:#7b8db0;font-size:11.5px;flex:1}
  .cmp-val{font-weight:700;color:#1d3763;font-variant-numeric:tabular-nums}
  .cmp-track{height:7px;border-radius:4px;background:#eef3fa;overflow:hidden;margin-top:3px}
  .cmp-track i{display:block;height:100%;border-radius:4px}
  .cmp-note{font-size:11.5px;color:#7b8db0;margin-top:6px;line-height:1.6}
  footer{padding:6px 22px 22px;font-size:12px;color:#8b9cb8}

  /* ---------- 启动提示:脚本未运行(或被聊天软件内置预览过滤)时也能看到 ---------- */
  .boot{
    position:absolute;left:0;right:0;top:0;bottom:0;display:flex;align-items:center;justify-content:center;
    padding:22px;text-align:center;background:#fbfdff;color:#2563a8;font-size:14px;line-height:1.85;z-index:5;
  }
  .boot-inner{max-width:460px}
  .boot b{font-size:15px}
  .boot span{color:#7b8db0;font-size:12.5px}
  body.dark .boot .spinner{border-color:#1d3350;border-top-color:#5fa8e8}
  .boot .spinner{
    width:26px;height:26px;margin:0 auto 12px;border-radius:50%;
    border:3px solid #d6e4f7;border-top-color:#2d6fae;animation:spin 1s linear infinite;
  }
  @keyframes spin{to{transform:rotate(360deg)}}
  .noscript-tip{margin:14px;padding:16px;border-radius:12px;background:#fff;border:1px solid #f0c2c2;color:#a53434;font-size:14px;line-height:1.8}
  /* 窄屏显示短标签、宽屏显示完整标签 */
  .only-narrow{display:none}

  /* ================= 平板 / 手机适配(放在末尾以覆盖上面的基础样式) ================= */
  /* ================= 手机版布局(给触屏优化的界面) =================
     手机版把"添加元件 / 参数 / 数据"做成底部固定栏 + 上滑抽屉,
     解决"元件菜单离画布太远、要来回滚动"的问题;画布占满剩余高度。 */
  .mbar{display:none}
  .mhint{display:none}
  .msheet,.mscrim{display:none}
  body.mobile .panel{display:none}          /* 卡片都搬进抽屉了,右侧栏不再占位 */
  body.mobile footer{display:none}
  body.mobile main{padding:8px;gap:8px}
  /* 手机端:左条读数被藏起来了,栅格必须同时收回第一列,
     否则会留下一块 156px 的空白(画布被挤到右边) */
  body.mobile main{grid-template-columns:minmax(0,1fr)}
  body.mobile main > .readout-strip,
  body.mobile main > .stage,
  body.mobile main > aside.panel{grid-column:auto;grid-row:auto}
  body.mobile .stage{padding:8px;gap:8px;border-radius:12px}
  /* 顶部操作栏:一行放完、不横向滚动、也不挤占画布 */
  body.mobile .toolbar{
    flex-wrap:nowrap;overflow:visible;gap:3px;padding:0;margin-bottom:2px;
    justify-content:space-between;
  }
  body.mobile .toolbar .group{flex:1 1 auto;gap:3px;padding-right:0;border-right:none;justify-content:center}
  /* 手机上:图标在上、文字在下,文字保留(看得懂才知道点哪个) */
  body.mobile .toolbar button.ico{
    flex:1 1 0;min-width:0;min-height:46px;padding:3px 1px;
    flex-direction:column;gap:2px;justify-content:center;border-radius:10px;
  }
  body.mobile .toolbar button.ico .icg{font-size:19px}
  /* 中等宽度(平板/窄窗口):工具栏只留图标,避免换行后压住画布 */
  @media (max-width: 1080px) and (min-width: 901px){
    .toolbar button.ico .lbl{display:none}
    .toolbar button.ico{min-width:46px;padding:6px 8px}
  }
  body.mobile .toolbar button.ico .lbl{display:none}
  body.mobile .toolbar button.ico .lbl-m{display:inline;font-size:10.5px;opacity:.92}
  body.mobile .toolbar button.ico .caret{display:none}
  body.mobile .toolbar .zoomgroup{display:none}
  body.mobile .toolbar #btnZoomFit{display:none}   /* 手机底部栏已有「适应」,这里不重复 */
  body.mobile .toolbar #btnAnnotate,body.mobile .toolbar #btnAbout{display:none}   /* 手机端这两项在"数据"抽屉/学习关卡里 */          /* 缩放用双指捏合;"适应"在底部栏 */
  body.mobile .toolbar .menugroup{display:none}          /* 演示电路在底部栏 */
  /* 选中元件时底部"参数"按钮高亮提示(不自动弹抽屉) */
  .mbar .mbtn.ready{color:#c9701a;box-shadow:inset 0 0 0 2px #ff9d2e}
  body.mobile.dark .mbar .mbtn.ready{color:#ffb457;box-shadow:inset 0 0 0 2px #ffa93f}
  body.mobile .canvas-wrap{border-radius:10px}
  body.mobile .mbar{
    display:flex;position:fixed;left:0;right:0;bottom:0;z-index:40;gap:6px;
    padding:6px 8px calc(6px + env(safe-area-inset-bottom,0px));
    background:rgba(255,255,255,.97);border-top:1px solid #dbe5f4;
  }
  body.mobile.dark .mbar{background:rgba(11,20,32,.97);border-top-color:#25384f}
  /* 手机端常驻提示条:贴在底部操作栏上方 */
  body.mobile .mhint{
    display:flex;align-items:center;gap:8px;position:fixed;left:0;right:0;z-index:39;
    padding:5px 10px;background:rgba(45,111,174,.10);border-top:1px solid #dbe5f4;
    font-size:11.5px;line-height:1.5;color:#3c4c66;
  }
  body.mobile .mhint.off{display:none}
  .mhint-txt{flex:1;min-width:0}
  .mhint-x{
    flex:0 0 auto;width:24px;height:24px;min-height:0;padding:0;border-radius:50%;
    font-size:14px;line-height:1;background:transparent;border:none;color:#7b8db0;
  }
  body.mobile.dark .mhint{background:rgba(95,168,232,.12);border-top-color:#25384f;color:#b3c7de}
  body.mobile.dark .mhint-x{color:#93a9c6}
  .mbar .mbtn{
    flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px;
    font-size:11px;line-height:1.1;padding:6px 4px;min-height:48px;border-radius:10px;font-weight:600;
  }
  .mbar .mbtn.danger{background:#fdecec;border-color:#f3c7c7;color:#c0392b}
  body.dark .mbar .mbtn.danger{background:#3a2028;border-color:#6b3a44;color:#ff9c9c}
  .mbar .mbtn.subtle{background:transparent;border-color:#dbe5f4;color:#7b8db0}
  body.dark .mbar .mbtn.subtle{background:transparent;border-color:#2c4058;color:#93a9c6}
  .mbar-main{display:flex;flex:1;gap:6px}
  .mbar-act{display:none;flex:1;gap:6px}
  /* 选中元件后:整条底部栏切换成操作条 */
  .mbar.acting .mbar-main{display:none}
  .mbar.acting .mbar-act{display:flex}
  /* 选中导线时(wiremode):操作条只留"删除导线"和"完成",其余元件操作隐藏 */
  .mbar.acting.wiremode #mActParams,
  .mbar.acting.wiremode #mActRot,
  .mbar.acting.wiremode #mActFlip,
  .mbar.acting.wiremode #mActCopy{display:none !important}
  body.mobile .msheet{
    display:flex;flex-direction:column;position:fixed;left:0;right:0;bottom:0;z-index:45;
    max-height:64vh;background:#fff;border-radius:14px 14px 0 0;
    box-shadow:0 -10px 34px rgba(10,25,50,.28);transform:translateY(103%);transition:transform .2s ease;
  }
  body.mobile .msheet.on{transform:translateY(0)}
  body.mobile .msheet-body{padding-bottom:calc(70px + env(safe-area-inset-bottom,0px))}
  .msheet-head{display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:1px solid #e3eaf5}
  .msheet-head b{font-size:14px;color:#12294d}
  .msheet-head #mSheetClose{margin-left:auto;width:30px;height:30px;padding:0;border-radius:50%;min-height:0}
  .msheet-tip{font-size:11.5px;color:#7b8db0;padding:6px 14px 0}
  body.dark .msheet-tip{color:#93a9c6}
  .msheet-body{overflow:auto;-webkit-overflow-scrolling:touch;padding:10px 12px}
  body.mobile .msheet-body .card{box-shadow:none;padding:0;border-radius:0;background:transparent}
  body.mobile .msheet-body .card h3{margin-top:4px}
  body.mobile .mscrim{
    display:block;position:fixed;left:0;right:0;top:0;bottom:0;z-index:44;
    background:rgba(10,20,35,.38);opacity:0;pointer-events:none;transition:opacity .2s ease;
  }
  body.mobile .mscrim.on{opacity:1;pointer-events:auto}
  body.dark.mobile .msheet{background:#152238}
  body.dark.mobile .msheet-head{border-bottom-color:#2a4059}
  body.dark.mobile .msheet-head b{color:#eaf2fd}
  @media (max-width:1080px){
    main{grid-template-columns:minmax(0,1fr)}
    .canvas-wrap{max-height:none}
  }
  @media (max-width:820px){
    header{padding:10px 14px;gap:8px}
    header h1{font-size:17px;letter-spacing:.5px}
    header .sub{font-size:11.5px}
    main{padding:10px;gap:10px}
    .stage{padding:10px;border-radius:12px;gap:8px}
    .card{padding:12px;border-radius:12px}
    .toolbar{gap:6px}
    /* 演示电路下拉菜单 */
  .menugroup{position:relative}
  .menupop{
    position:absolute;right:0;top:calc(100% + 6px);z-index:50;min-width:260px;
    background:#fff;border:1px solid #dbe5f4;border-radius:12px;padding:8px;
    box-shadow:0 14px 40px rgba(12,30,60,.22);
  }
  .menupop[hidden]{display:none}
  #btnPresets.on{background:#2d6fae;border-color:#2d6fae;color:#fff}
  .mobile-presets{gap:8px}
  .mobile-presets button{font-size:14px;padding:12px 12px;min-height:56px}
  .mobile-presets button small{font-size:12px}
  .menutitle{font-size:12px;color:#7b8db0;padding:2px 8px 8px}
  .menulist{display:flex;flex-direction:column;gap:4px}
  .menulist button{
    display:grid;grid-template-columns:34px 1fr;align-items:center;gap:2px 8px;text-align:left;
    padding:8px 10px;border-radius:9px;font-size:13.5px;font-weight:600;min-height:0;
  }
  .menulist button small{grid-column:2;font-size:11.5px;color:#7b8db0;font-weight:400}
  .menulist .mglyph{grid-row:span 2;font-size:16px;color:#2d6fae;text-align:center}
  .caret{font-size:10px;opacity:.7;margin-left:2px}
  .ico-glyph{font-size:15px}
  /* 顶部小气泡提示(添加元件等操作反馈) */
  .toast{
    position:fixed;left:50%;top:12px;transform:translate(-50%,-14px);z-index:80;
    background:rgba(18,48,90,.94);color:#fff;font-size:13px;font-weight:600;
    padding:8px 16px;border-radius:20px;box-shadow:0 8px 24px rgba(10,25,50,.28);
    opacity:0;pointer-events:none;transition:opacity .18s ease,transform .18s ease;
  }
  .toast.on{opacity:1;transform:translate(-50%,0)}
  body.dark .toast{background:rgba(30,70,120,.95)}
  .toolbar button.ico{display:inline-flex;align-items:center;justify-content:center;gap:5px}
  .toolbar button.ico .icg{font-size:17px;line-height:1}
  .toolbar button.ico .lbl{font-size:13px;line-height:1;white-space:nowrap}
  body.dark .menupop{background:#152238;border-color:#2a4059}
  body.dark .menulist button small{color:#8ea6c4}
  body.dark .menulist .mglyph{color:#7fb6f0}
  /* 操作按钮图标放大一点,更好点 */
  .toolbar button.ico{font-size:15px;padding:9px 12px;min-height:42px}
  .toolbar button.ico .glyph{font-size:16px}
  @media (max-width:820px){
    .toolbar button.ico{font-size:16px;padding:9px 13px;min-height:44px}
  }
  .toolbar .group{gap:6px;padding-right:6px}
    button{font-size:12.5px;padding:8px 11px;min-height:38px;touch-action:manipulation}
    .palette button{min-height:54px}
    .hint{font-size:11.8px;line-height:1.75;padding:9px 11px}
    .legend{font-size:11.5px;gap:10px}
    .kv,.readouts,.inspector{font-size:12.5px}
    .card h3{font-size:13px;margin-bottom:8px}
    .badge{font-size:13px;padding:5px 12px}
    footer{padding:8px 14px 20px;font-size:11.5px}
  }
  @media (max-width:520px){
    header .sub{display:none}
    header h1{font-size:16px}
    .palette{grid-template-columns:repeat(2,1fr)}
    .toolbar .cap{display:none}
    .zoomlabel{min-width:40px}
    main{padding:8px;gap:8px}
    .stage{padding:8px}
    .card{padding:11px}
    .only-wide{display:none}
    .only-narrow{display:inline}
    button{padding:7px 9px;font-size:12px}
  }
  /* 横屏手机:让画布占满可用高度,电路看得更清楚 */
  @media (max-height:520px) and (orientation:landscape){
    .canvas-wrap{max-height:64vh}
  }

  /* ================= 元件图鉴(弹层) ================= */
  body.lib-open{overflow:hidden}
  .lib-overlay{
    position:fixed;left:0;right:0;top:0;bottom:0;z-index:60;background:rgba(12,24,42,.55);
    display:flex;align-items:center;justify-content:center;padding:18px;backdrop-filter:blur(2px);
  }
  .lib-overlay[hidden]{display:none}
  .lib-panel{
    background:#fff;border-radius:16px;width:min(1080px,100%);max-height:min(88vh,900px);
    display:flex;flex-direction:column;overflow:hidden;box-shadow:0 18px 50px rgba(8,20,40,.35);
  }
  .lib-head{
    display:flex;align-items:center;gap:10px;padding:14px 16px;border-bottom:1px solid #e3eaf5;
    background:linear-gradient(90deg,#12305a,#25558f);color:#fff;
  }
  .lib-head b{font-size:16px;letter-spacing:.5px}
  .lib-sub{font-size:12px;opacity:.8}
  .lib-close{
    margin-left:auto;min-height:0;width:30px;height:30px;padding:0;border-radius:50%;
    border:none;background:rgba(255,255,255,.18);color:#fff;font-size:18px;line-height:1;
  }
  .lib-close:hover{background:rgba(255,255,255,.32)}
  /* 简化电路图浮层 */
  .schem-wrap{
    flex:1;min-height:0;overflow:auto;background:#eef3fa;padding:16px;
    display:flex;align-items:flex-start;justify-content:center;
  }
  .schem-wrap canvas{
    display:block;background:#fff;border-radius:8px;
    box-shadow:0 4px 18px rgba(20,45,90,.14);
  }
  .schem-bar{
    display:flex;align-items:center;gap:10px;flex-wrap:wrap;
    padding:10px 14px;border-top:1px solid #e3eaf5;background:#f7faff;
  }
  .schem-bar button{min-height:0;padding:8px 14px;border-radius:9px;font-size:13px}
  .schem-bar #schemSave{background:#25558f;border-color:#25558f;color:#fff;font-weight:600}
  .schem-bar #schemSave:hover{background:#1d4674}
  .schem-note{font-size:12px;color:#6b7f9e;flex:1;min-width:180px}
  body.dark .schem-wrap{background:#0b1526}
  body.dark .schem-bar{background:#101d31;border-top-color:#22334a}
  body.dark .schem-note{color:#8ba3c0}
  .lib-body{display:flex;min-height:0;flex:1}
  .lib-side{
    flex:0 0 168px;border-right:1px solid #e3eaf5;padding:10px;overflow:auto;background:#f7faff;
    display:flex;flex-direction:column;gap:6px;
  }
  .lib-item{
    text-align:left;padding:9px 11px;border-radius:10px;border:1px solid #dbe5f4;background:#fff;
    color:#1d3763;font-size:13px;display:flex;flex-direction:column;gap:2px;min-height:0;
  }
  .lib-item:hover{background:#eef5ff;border-color:#a8c6ea}
  .lib-item.on{background:#2d6fae;border-color:#2d6fae;color:#fff}
  .lib-item.on .lib-cat{color:rgba(255,255,255,.8)}
  .lib-cat{font-size:11px;color:#7b8db0}
  .lib-main{flex:1;min-width:0;overflow:auto;padding:16px 18px 22px}
  .lib-title{font-size:19px;font-weight:700;color:#12294d;display:flex;align-items:center;gap:10px;flex-wrap:wrap}
  .lib-tag{font-size:11.5px;font-weight:500;color:#25558f;background:#e8f1ff;border-radius:20px;padding:3px 10px}
  .lib-figs{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin:14px 0 6px}
  .lib-fig{margin:0;background:#f7faff;border:1px solid #e3eaf5;border-radius:12px;padding:8px}
  .lib-fig figcaption{font-size:12px;color:#7b8db0;text-align:center;margin-bottom:4px}
  .lib-svg{display:block;width:100%;height:auto}
  .lib-desc{font-size:13.5px;line-height:1.9;color:#3c4c66;margin:10px 0 4px}
  .lib-h{font-size:13.5px;font-weight:700;color:#25558f;margin:16px 0 8px;display:flex;align-items:center;gap:6px}
  .lib-h::before{content:"";width:4px;height:14px;border-radius:2px;background:#2d6fae}
  .lib-table{width:100%;border-collapse:collapse;font-size:12.8px}
  .lib-table th{text-align:left;color:#465a7a;font-weight:600;padding:7px 10px;background:#f2f7ff;border-radius:8px 0 0 8px;width:34%;vertical-align:top}
  .lib-table td{padding:7px 10px;color:#1d3763;background:#fafcff;border-radius:0 8px 8px 0}
  .lib-table tr+tr th,.lib-table tr+tr td{margin-top:4px}
  .lib-variants{display:grid;grid-template-columns:repeat(auto-fill,minmax(196px,1fr));gap:10px}
  .lib-variant{background:#f7faff;border:1px solid #e3eaf5;border-radius:12px;padding:10px}
  .lib-vart{font-size:13px;font-weight:700;color:#12294d}
  .lib-varspec{font-size:12px;color:#2d6fae;margin-top:2px}
  .lib-varart{margin:6px 0 4px}
  .lib-varnote{font-size:12px;color:#6c7f9e;line-height:1.7}
  .lib-tips{margin:6px 0 0;padding-left:18px;font-size:12.8px;line-height:1.9;color:#3c4c66}
  /* 暗色 */
  body.dark .lib-panel{background:#152238}
  body.dark .lib-head{background:linear-gradient(90deg,#0b1729,#17456f)}
  body.dark .lib-side{background:#11203a;border-right-color:#2a4059}
  body.dark .lib-item{background:#1b2b42;border-color:#2c4058;color:#dbe9fc}
  body.dark .lib-item:hover{background:#22374f}
  body.dark .lib-item.on{background:#2d6fae;border-color:#2d6fae;color:#fff}
  body.dark .lib-cat{color:#8ea6c4}
  body.dark .lib-title{color:#eaf2fd}
  body.dark .lib-tag{background:#1d3350;color:#9ec7f5}
  body.dark .lib-fig{background:#11203a;border-color:#2a4059}
  body.dark .lib-desc,body.dark .lib-tips{color:#b8cbe4}
  body.dark .lib-h{color:#9ec7f5}
  body.dark .lib-h::before{background:#5fa8e8}
  body.dark .lib-table th{background:#1b2b42;color:#a9bdd6}
  body.dark .lib-table td{background:#152238;color:#dbe9fc}
  body.dark .lib-variant{background:#11203a;border-color:#2a4059}
  body.dark .lib-vart{color:#eaf2fd}
  body.dark .lib-varspec{color:#7fb6f0}
  body.dark .lib-varnote{color:#93a9c6}
  @media (max-width:760px){
    .lib-overlay{padding:0}
    .lib-panel{width:100%;max-height:100%;height:100%;border-radius:0}
    .lib-body{flex-direction:column}
    .lib-side{
      flex:0 0 auto;flex-direction:row;overflow-x:auto;overflow-y:hidden;gap:6px;
      border-right:none;border-bottom:1px solid #e3eaf5;padding:8px;
    }
    .lib-item{flex:0 0 auto;padding:7px 12px;align-items:center}
    .lib-cat{display:none}
    .lib-figs{grid-template-columns:1fr}
    .lib-main{padding:12px 12px 20px}
  }

  /* ================= 暗黑模式 ================= */
  body.dark{background:#0e1726;color:#e8f0fb;color-scheme:dark}
  body.dark header{background:linear-gradient(90deg,#0b1729,#123058 60%,#17456f)}
  body.dark header .sub{color:#9fb6d4}
  body.dark .stage,body.dark .card,body.dark .hintcard{background:#152238;box-shadow:0 6px 22px rgba(0,0,0,.35)}
  body.dark .canvas-wrap{border-color:#25384f;background:#0b1420}
  body.dark .hintcard>summary{color:#9ec7f5}
  body.dark .hintcard>summary::before{background:#5fa8e8}
  body.dark .hintcard>summary::after{color:#7f97b5}
  body.dark button{border-color:#2c4058;background:#1b2b42;color:#d7e5f7}
  body.dark button:hover{background:#22374f;border-color:#3f5f85}
  body.dark button.primary{background:#2d6fae;border-color:#2d6fae;color:#fff}
  body.dark button.danger{background:#3a2028;border-color:#6b3a44;color:#ff9c9c}
  body.dark button.danger:hover{background:#4a2731}
  body.dark button.on{background:#1d7f5f;border-color:#1d7f5f;color:#fff}
  body.dark .matgrid button.on{background:#2d6fae;border-color:#2d6fae;color:#fff}
  body.dark .toolbar .group{border-right-color:#25384f}
  body.dark .toolbar .cap,body.dark .zoomlabel{color:#8ea6c4}
  body.dark .zoomlabel{color:#9ec7f5}
  body.dark .hint{background:#12203a;border-color:#2b4666;color:#a9bdd6}
  body.dark .hint b{color:#9ec7f5}
  body.dark .legend{color:#8ea6c4}
  body.dark .kv{color:#a9bdd6}
  body.dark .kv b{color:#eaf2fd}
  body.dark .readouts .row{background:#12203a}
  body.dark .readouts .name{color:#a9bdd6}
  body.dark .readouts .val{color:#eaf2fd}
  body.dark .readouts .val.hot{color:#ffb457}
  body.dark .readouts .empty,body.dark .inspector .empty{color:#6f86a3}
  body.dark .inspector .field label{color:#a9bdd6}
  body.dark .inspector .field label span{color:#eaf2fd}
  body.dark .insp-title{color:#eaf2fd}
  body.dark .insp-note{color:#93a9c6}
  body.dark .insp-empty{color:#6f86a3}
  body.dark .card h3{color:#9ec7f5}
  body.dark .card h3::before{background:#5fa8e8}
  body.dark .badge.open{background:#1c2c42;color:#93a9c6}
  body.dark .badge.on{background:#123a2c;color:#5fd3a3}
  body.dark .badge.short{background:#3d1f26;color:#ff8080}
  body.dark .badge.heavy{background:#3d2f16;color:#ffc061}
  body.dark .badge.charge{background:#16263d;color:#7fb6f0}
  body.dark .cmp{border-top-color:#2b4666}
  body.dark .cmp-title{color:#9ec7f5}
  body.dark .cmp-name{color:#eaf2fd}
  body.dark .cmp-meta{color:#8ea6c4}
  body.dark .cmp-val{color:#dbe9fc}
  body.dark .cmp-track{background:#12203a}
  body.dark .cmp-note{color:#8ea6c4}
  body.dark .tips{color:#a9bdd6}
  body.dark .tips .bad{color:#5fd3a3}
  body.dark .tips .sh{color:#ff8080}
  body.dark .boot{background:#0b1420;color:#9ec7f5}
  body.dark .boot span{color:#7f97b5}
  body.dark .noscript-tip{background:#2a1a20;border-color:#6b3a44;color:#ff9c9c}
  body.dark footer{color:#6f86a3}
  body.dark ::-webkit-scrollbar{width:10px;height:10px}
  body.dark ::-webkit-scrollbar-track{background:#0e1726}
  body.dark ::-webkit-scrollbar-thumb{background:#2c4058;border-radius:5px}

  /* ================= 关卡系统(v2.0 M1) ================= */
  /* —— 启动页 / 关卡选择 / 结果面板(复用 lib-overlay 壳)—— */
  .hub-card{border:1.5px solid #cfd9e6;border-radius:14px;padding:22px 24px;cursor:pointer;
    background:#fff;box-shadow:0 8px 26px rgba(20,45,90,.12);transition:transform .12s ease,box-shadow .12s ease}
  .hub-card:hover{transform:translateY(-3px);box-shadow:0 14px 34px rgba(20,45,90,.2);border-color:#25558f}
  .hub-card h3{margin:6px 0 8px;font-size:21px;color:#1b2b45}
  .hub-card p{margin:0;font-size:13px;color:#5a6b82;line-height:1.7}
  .hub-card .hc-tag{font-family:Consolas,monospace;font-size:10.5px;letter-spacing:.16em;color:#2d6fae}
  .hub-card .hc-num{font-family:Consolas,monospace;font-size:30px;font-weight:700;color:#25558f;line-height:1}
  body.dark .hub-card{background:#1a2a44;border-color:#2c4058}
  body.dark .hub-card h3{color:#e8eef7}
  body.dark .hub-card p{color:#93a5bd}
  .pick-item{display:flex;align-items:center;gap:12px;padding:11px 14px;border:1px solid #d7dfec;border-radius:10px;
    margin:7px 0;cursor:pointer;background:#f7fafd}
  .pick-item:hover{border-color:#25558f;background:#eef4fd}
  .pick-item.locked{opacity:.55;cursor:not-allowed}
  .pick-item .pi-no{font-family:Consolas,monospace;font-size:15px;font-weight:700;color:#25558f;width:34px}
  .pick-item .pi-name{flex:1;font-size:13.5px;color:#1b2b45}
  .pick-item .pi-star{color:#c79c1e;font-size:13px;letter-spacing:2px}
  body.dark .pick-item{background:#16233a;border-color:#2c4058}
  body.dark .pick-item:hover{background:#1c2c48}
  body.dark .pick-item .pi-name{color:#e8eef7}
  .pick-skip{margin-left:auto;font-size:12px;font-weight:600;color:#25558f;background:#eaf1fb;
    border:1px solid #c3d4ee;border-radius:8px;padding:4px 10px;cursor:pointer;white-space:nowrap}
  .pick-skip:hover{background:#dceafc;border-color:#25558f}
  body.dark .pick-skip{color:#9fc3ef;background:#1c2c48;border-color:#2c4058}
  .goal-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:20px;
    border:1px solid #d7dfec;background:#f7fafd;font-size:12px;color:#47597a;margin:3px 5px 3px 0}
  .goal-chip.done{border-color:#12734f;background:#e6f6ef;color:#0d5c3e}
  .goal-chip.fail{border-color:#c02a2a;background:#fdecea;color:#a33}
  body.dark .goal-chip{background:#16233a;border-color:#2c4058;color:#b8c6da}
  body.dark .goal-chip.done{background:#123527;border-color:#2f7d54;color:#7fe0b0}
  body.dark .goal-chip.fail{background:#3a1d22;border-color:#7d3540;color:#ff9c9c}
  /* —— 题面条(画布上方)与判分条(画布下方)—— */
  #levelBar,#judgeBar{display:none}
  body.level-mode #levelBar,body.level-mode #judgeBar{display:flex}
  #levelBar{align-items:flex-start;gap:14px;padding:10px 14px;margin:0 0 8px;border:1px solid #d7dfec;
    border-radius:10px;background:#fff}
  #levelBar .lb-title{font-size:15px;font-weight:700;color:#1b2b45}
  #levelBar .lb-task{font-size:12.5px;color:#5a6b82;line-height:1.65;margin-top:3px}
  #judgeBar{align-items:center;gap:10px;padding:9px 12px;margin:8px 0 0;border:1px solid #d7dfec;
    border-radius:10px;background:#fff}
  #judgeBar .jb-note{font-size:12px;color:#7b8db0}
  body.dark #levelBar,body.dark #judgeBar{background:#1a2a44;border-color:#2c4058}
  body.dark #levelBar .lb-title{color:#e8eef7}
  body.dark #levelBar .lb-task{color:#93a5bd}
  /* 关卡模式收窄工具:去掉"清空/保存/演示电路"等逃生口(演示电路=直接载入答案,属于作弊口) */
  body.level-mode #btnClear,body.level-mode #fileCard,body.level-mode #mBtnFile,body.level-mode #btnOpenExp,
  body.level-mode #btnPresets,body.level-mode #mBtnPresets{display:none !important}
  /* 实验数据表与试验记录(v2.0):像实验记录那样列读数、多组对比 */
  .dtable{width:100%;border-collapse:collapse;font-size:11.5px;font-variant-numeric:tabular-nums}
  .dtable th{font-family:Consolas,monospace;font-size:9.5px;letter-spacing:.12em;color:#8296b0;text-align:left;
    padding:3px 5px;border-bottom:1px solid #d7dfec}
  .dtable td{padding:3px 5px;border-bottom:1px solid #eef2f8;color:#12294d;white-space:nowrap}
  .dtable .dname{font-weight:700}
  .dtable .dhot{color:#c9701a;font-weight:700}
  .trial-bar{display:flex;gap:6px;margin:8px 0 6px}
  .trial-bar button{flex:1;padding:6px 8px;font-size:11.5px;border-radius:7px;border:1px solid #cfd9e6;
    background:#eef4fd;color:#1b4b82;cursor:pointer}
  .trial-bar button:hover{border-color:#25558f}
  .trials{display:flex;flex-direction:column;gap:6px;max-height:190px;overflow:auto}
  .trial{border:1px solid #e3eaf4;border-radius:7px;padding:5px 8px;background:#f6faff}
  .trial-h{font-family:Consolas,monospace;font-size:10px;letter-spacing:.1em;color:#8296b0}
  .trial-r{display:flex;gap:8px;font-size:11px;font-variant-numeric:tabular-nums;color:#47597a;justify-content:space-between}
  body.dark .dtable th{border-color:#2c4058;color:#7d92ad}
  body.dark .dtable td{color:#eaf2fd;border-color:#1c2c48}
  body.dark .trial{background:#12203a;border-color:#2c4058}
  body.dark .trial-bar button{background:#1c2c48;border-color:#2c4058;color:#9fc2ff}
  /* 关卡「选结论」选项(做完实验选结论,判分一起查) */
  .choice-opt{margin:3px 6px 3px 0;padding:7px 13px;border:1px solid #d7dfec;border-radius:16px;background:#f7fafd;
    font-size:12.5px;color:#47597a;cursor:pointer}
  .choice-opt:hover{border-color:#25558f}
  .choice-opt.sel{border-color:#25558f;background:#eef4fd;color:#1b4b82;font-weight:700}
  body.dark .choice-opt{background:#16233a;border-color:#2c4058;color:#b8c6da}
  body.dark .choice-opt.sel{background:#1c2c48;color:#7fb8ff;border-color:#25558f}
  .res-badge{font-family:Consolas,monospace;font-size:11px;letter-spacing:.18em;padding:3px 9px;border-radius:3px}
  .res-badge.ok{background:#e6f6ef;color:#0d5c3e}
  .res-badge.no{background:#fdecea;color:#a33}
</style>
</head>
<body>
<header>
  <h1>简易电路实验展示</h1>
  <div class="sub">物理课堂演示 · 拖动元件与导线自由搭建,实时计算电流、电压与电功率</div>
</header>

<main>
  <section class="stage">
    <div class="toolbar">
      <!-- 底部操作条(电脑版钉在画布下方;手机版排在顶部一行里) -->
      <div class="group group-bottom">
        <button id="btnUndo" class="ico" title="撤销(Ctrl+Z)" disabled><span class="icg">↶</span><span class="lbl">撤销</span></button>
        <button id="btnRedo" class="ico" title="重做(Ctrl+Y)" disabled><span class="icg">↷</span><span class="lbl">重做</span></button>
        <button class="danger ico" id="btnClear" title="清空画布"><span class="icg">🗑</span><span class="lbl">清空</span></button>
        <span class="zoomgroup">
          <button id="btnZoomOut" class="ico" title="缩小(也可 Ctrl + 滚轮)"><span class="icg">-</span><span class="lbl">缩小</span></button>
          <span class="zoomlabel" id="zoomLabel">100%</span>
          <button id="btnZoomIn" class="ico" title="放大(也可 Ctrl + 滚轮)"><span class="icg">+</span><span class="lbl">放大</span></button>
        </span>
        <button id="btnMinimap" class="ico" title="显示 / 隐藏右下角缩略图"><span class="icg">🗺</span><span class="lbl">缩略图</span></button>
        <button id="btnSound" class="on ico" title="开关音效:电铃、电动机、开关、短路放电声"><span class="icg">🔊</span><span class="lbl" id="lblSound">音效开</span></button>
        <button id="btnDelSel" class="danger ico only-desktop" title="删除选中的元件(也可按 Delete 或右键)"><span class="icg">✖</span><span class="lbl">删除元件</span></button>
      </div>
      <!-- 上方保留的按钮 -->
      <div class="group">
        <button id="btnZoomFit" class="ico" title="把整个电路缩放居中显示"><span class="icg">⤢</span><span class="lbl">适应窗口</span></button>
        <button id="btnLearn" class="ico on" title="操作学习:跟着做一遍,几分钟上手全部操作"><span class="icg">🎓</span><span class="lbl">操作学习</span><span class="lbl-m">学习</span></button>
        <button id="btnLib" class="ico" title="元件图鉴:每种元件的介绍与配图"><span class="icg">📖</span><span class="lbl">元件图鉴</span><span class="lbl-m">图鉴</span></button>
        <button id="btnAnnotate" class="ico" title="注解:点画布添加说明框(半透明底白字);拖动可移动、右键删除"><span class="icg">📝</span><span class="lbl">注解</span><span class="lbl-m">注解</span></button>
        <button id="btnSchem" class="ico only-desktop" title="电路图:把实物连线自动画成标准电路图(可保存 PNG)"><span class="icg">📐</span><span class="lbl">电路图</span><span class="lbl-m">电路图</span></button>
        <button id="btnAbout" class="ico" title="关于 / 帮助:使用说明与常见问题"><span class="icg">❓</span><span class="lbl">帮助</span></button>
        <button id="btnHome" class="ico" title="返回主菜单(关卡模式 / 自由创造)"><span class="icg">⌂</span><span class="lbl">主菜单</span><span class="lbl-m">主页</span></button>
      </div>
      <div class="group">
        <button id="btnTheme" class="ico" title="切换暗色 / 亮色模式"><span class="icg">🌙</span><span class="lbl" id="lblTheme">暗色</span></button>
        <button id="btnLayout" class="ico" title="切换手机版 / 电脑版布局"><span class="icg">🖥</span><span class="lbl" id="lblLayout">电脑版</span></button>
      </div>
      <!-- 演示电路:收进一个独立菜单,不再占一整行 -->
      <div class="group menugroup">
        <button id="btnPresets" class="ico" title="选择演示电路"><span class="icg">📚</span><span class="lbl">演示电路</span><span class="caret">▾</span></button>
        <div class="menupop" id="presetMenu" hidden>
          <div class="menutitle">演示电路</div>
          <div class="menulist" id="presetList">
            <button data-preset="basic"><span class="mglyph">▭</span>基本电路<small>电源+开关+小灯泡</small></button>
            <button data-preset="series"><span class="mglyph">▭▭</span>串联<small>两灯串联,电流处处相等</small></button>
            <button data-preset="parallel"><span class="mglyph">⑃</span>并联<small>两灯并联,各支路电压相等</small></button>
            <button data-preset="meter"><span class="mglyph">A V</span>电流表·电压表<small>学会串并联接法</small></button>
            <button data-preset="short"><span class="mglyph">⚡</span>短路演示<small>危险操作,看看会发生什么</small></button>
            <button data-preset="fuse"><span class="mglyph">⊘</span>保险丝保护<small>超流自动熔断</small></button>
            <button data-preset="shortBulb"><span class="mglyph">◑</span>用电器短路<small>灯泡被短路为什么不亮(中考易错)</small></button>
            <button data-preset="ohmLaw"><span class="mglyph">Ω</span>伏安法测电阻<small>变阻器 + 电流表 + 电压表测 R = U / I</small></button>
            <button data-preset="rheostatControl"><span class="mglyph">⇥</span>滑动变阻器<small>滑片改变电阻 → 电流与亮度</small></button>
            <button data-preset="compareMaterials"><span class="mglyph">≡</span>不同导体对比<small>铜/铁/镍铬/铅笔芯</small></button>
            <button data-preset="compareSizes"><span class="mglyph">⇔</span>长度与粗细<small>R 与 L、S 的关系</small></button>
          </div>
        </div>
      </div>
    </div>

    <!-- 关卡:题面条(仅关卡模式显示) -->
    <div id="levelBar">
      <div style="flex:1">
        <div class="lb-title" id="lbTitle">第 1 关 · 认识电路</div>
        <div class="lb-task" id="lbTask">…</div>
        <div id="lbGoals" style="margin-top:6px"></div>
        <div id="lbChoices" style="margin-top:8px"></div>
      </div>
      <button class="ico" id="btnExitLevel" title="退出本关,回到关卡列表"><span class="icg">↩</span><span class="lbl">退出本关</span></button>
    </div>

    <div class="canvas-wrap" id="wrap">
      <canvas id="cv"></canvas>
      <div class="minimap" id="minimap">
        <div class="mm-bar" id="mmBar" title="拖动这里可以把缩略图挪到画布任意位置(靠近边缘会自动吸附)">
          <span class="mm-grip">⠿</span>缩略图
        </div>
        <canvas id="mmCanvas"></canvas>
        <div class="mm-handle" id="mmHandle" title="拖动调整缩略图大小"></div>
        <button class="mm-close" id="mmClose" title="隐藏缩略图">×</button>
      </div>
      <div class="boot" id="boot">
        <div class="boot-inner">
          <div class="spinner"></div>
          <b>正在加载电路面板…</b><br>
          <span>如果长时间停在这一屏,说明当前打开方式禁用了网页脚本(常见于微信、QQ 等聊天软件的内置“文件预览”)。<br>
          请把文件保存到手机,然后在<b>文件管理</b>里选择用「浏览器 / Chrome / Safari / 夸克」打开,或用电脑浏览器打开后投屏。</span>
        </div>
      </div>
    </div>

    <!-- 关卡:判分条(仅关卡模式显示,手动判分) -->
    <div id="judgeBar">
      <button class="ico" id="btnHint" title="给一条提示(不扣分,只记次数)"><span class="icg">💡</span><span class="lbl">提示</span></button>
      <button class="ico" id="btnExplain" title="查看本关解析"><span class="icg">📖</span><span class="lbl">解析</span></button>
      <button class="danger ico" id="btnRetry" title="清空画布,从头接一遍"><span class="icg">⟲</span><span class="lbl">重试本关</span></button>
      <span class="jb-note">做完后点「检查」判分 —— 判分前不会当场揭晓对错</span>
      <button class="ico on" id="btnJudge" title="检查是否达标(手动判分)" style="margin-left:auto"><span class="icg">✔</span><span class="lbl">检查</span></button>
    </div>

    <noscript>
      <div class="noscript-tip">本页面需要 JavaScript 才能运行电路仿真。请用手机自带浏览器(Chrome / Safari / 夸克等)打开本文件,不要使用聊天软件的内置预览。</div>
    </noscript>
  </section>

  <aside class="readout-strip">
    <div class="card" id="readoutCard">
      <h3>读数 · 实验数据</h3>
      <div class="readouts" id="readouts"><div class="empty">画布上还没有元件</div></div>
      <div class="trial-bar">
        <button id="btnRecord" title="把当前这组读数记入实验记录:多测几组,从数据里找规律">📷 记录本组数据</button>
        <button id="btnClearTrials" title="清空实验记录">清空</button>
      </div>
      <div class="trials" id="trialList"><div class="empty">多测几组、点「记录本组数据」,从数据里找规律</div></div>
    </div>
  </aside>

  <aside class="panel">
    <div class="card" id="paletteCard">
      <h3>添加元件</h3>
      <div class="palette" id="paletteQuick"></div>
      <div style="font-size:11px;color:#7b8db0;margin-top:6px;line-height:1.45">
        点击即添加到画布;接线点用于导线拐弯与分支交汇。
      </div>
    </div>

    <div class="card" id="statusCard">
      <h3>电路状态</h3>
      <div id="statusBadge" class="badge open">断路</div>
      <div class="kv"><span>电源输出电流 I</span><b id="statI">0 A</b></div>
      <div class="kv"><span>电源电动势 E</span><b id="statE">0 V</b></div>
      <div class="kv-3">
        <span>内阻分压 <b id="statIR">0 V</b></span>
        <span>内部损耗 <b id="statLoss">0 W</b></span>
        <span>效率 <b id="statEff">—</b></span>
      </div>
      <div class="kv"><span>电源两端电压 U</span><b id="statU">0 V</b></div>
      <div class="kv"><span>电源输出功率 P</span><b id="statP">0 W</b></div>
      <div class="kv"><span>外电路总电阻 R</span><b id="statR">—</b></div>
    </div>

    <div class="card" id="inspectorCard">
      <h3>选中元件</h3>
      <div class="inspector" id="inspector"><div class="empty insp-empty">点击画布上的元件,可调节它的参数</div></div>
    </div>

    <div class="card" id="fileCard">
      <h3>实验文件</h3>
      <div class="file-acts">
        <button id="btnSaveExp" class="file-btn" title="把当前电路存成 .json 文件(元件、导线、注释、视角一起存)">💾 保存实验<small>存成文件,可再打开、可发给同学</small></button>
        <button id="btnOpenExp" class="file-btn" title="打开之前保存的实验文件;打开前会先存一步撤销,打开也能撤销">📂 打开实验<small>选择 .json 文件;校验不过不会覆盖当前电路</small></button>
        <button id="btnExportImg" class="file-btn" title="把当前画面导出为高清 PNG(约 2400px 宽,不含选中框与缩略图)">🖼 导出图片<small>当前画面存成高清 PNG</small></button>
      </div>
    </div>

    <div class="card tips-card" id="tipsCard">
      <details>
        <summary>课堂提示(点击展开)</summary>
        <div class="tips" id="tipBox"></div>
        <!-- 操作说明已并入本卡片,不再单独占一张卡 -->
        <details class="hintcard" id="hintCard">
          <summary>操作说明(点击展开)</summary>
          <div class="hintbody">
            <!-- 手机版操作提示(body.mobile 时显示) -->
            <div class="hint hint-mobile">
              <b>连导线(最常用):</b><b>点一下</b>接线柱(蓝色小圆点)→ 它亮起、等待接另一端 → <b>再点另一个接线柱</b>就连上了(点得快也一样,不用等);点导线会自动插入接线点;点空白处或按 <b>Esc</b> 取消。<b>按住拖动 = 移动元件</b>(拖动不接线)。<br>
              <b>添加元件:</b>点底部 <b>+元件</b>,可以<b>连续点好几个</b>,加完再收起抽屉;
              新元件会落在抽屉上方看得见的地方,同时有<b>放置音效</b>、气泡提示和高亮闪烁。<br>
              <b>选中就能操作:</b>轻点元件选中后,<b>底部整条操作栏会变成操作条</b>——⚙参数 / ↻旋转 / ⇄对调+- / ⧉复制 / 🗑删除 / ✓完成;多选时是「整组旋转 / 删N个」。<br>
  <b>移动元件:</b>直接<b>拖动元件</b>即可移动(元件紧贴手指);点中元件后底部 <b>⚙参数</b>
              里可以调参数、<b>旋转</b>、<b>对调正负极</b>(电池、发光二极管)、删除。<br>
              <b>开关:</b>轻点开关即可通断,会有“咔哒”声。<br>
              <b>画面:</b><b>双指捏合</b>缩放、<b>双指拖动</b>平移;底部 <b>⤢适应</b> 一键把整个电路缩放居中;
              右下角<b>缩略图</b>可以点着跳转视野。<br>
              <b>撤销 / 重做:</b>顶部 <b>↶撤销</b> / <b>↷重做</b>,做错了随时回退。<br>
              <b>演示电路:</b>底部 <b>📚演示</b> 里有 11 个现成电路(串联、并联、电表、短路、保险丝、导体对比…)。<br>
              <b>音效:</b>开关“咔哒”、电铃“叮——”(<b>电流越大越响</b>)、电动机转动声、短路噼啪声;顶部 🔊 可静音。
            </div>
            <!-- 电脑版操作提示(电脑版布局时显示) -->
            <div class="hint hint-desktop">
              <b>操作:</b><b>点一下接线柱</b>(蓝色小圆点,它会亮起等待)→ <b>再点另一个接线柱</b>即可连导线,点导线会自动插入接线点;点空白或按 <b>Esc</b> 取消。<b>按住拖动 = 移动元件</b>(拖动一律不接线)
              &nbsp;·&nbsp; <b>撤销</b> ↶ / <b>重做</b> ↷(快捷键 Ctrl+Z / Ctrl+Y) &nbsp;·&nbsp; 接线点请拖它的<b>中心圆点</b>移动&nbsp;·&nbsp; 单击<b>开关</b>切换通断 &nbsp;·&nbsp; 选中元件后按 <b>R</b> 或点属性面板的<b>旋转</b>按钮可旋转(电池转 180° 即正负极对调)&nbsp;·&nbsp; 右键删除元件或导线<br>
              <b>批量操作:</b>在<b>空白处按住拖动</b>即可像框选文件一样<b>框选多个元件</b>,然后拖其中任意一个就能<b>整组移动</b>;按住 <b>Shift</b> 框选可追加、Shift 点击可单个加入/移出;<b>Ctrl+A</b> 全选、<b>Esc</b> 取消、<b>Delete</b> 一次删除、<b>R</b> 整组旋转<br>
              <b>视图:</b>手机、平板可<b>双指捏合</b>缩放、<b>双指拖动</b>平移画面;电脑用<b>缩放</b>按钮、<b>Ctrl + 滚轮</b>缩放,或用 <b>Ctrl/⌘ + 拖动</b>、<b>中键拖动</b>、<b>空格 + 拖动</b>平移<br>
              <b>音效:</b>开关有“咔哒”声,电铃会“叮——”响(<b>电流越大声音越响</b>),电动机有运转声,短路会迸火星并发出“噼啪”放电声(右上角 🔊 可一键静音)<br>
              <b>导体实验:</b>点“不同导体对比”可比较<b>铜/铁/镍铬合金/铅笔芯</b>的导电性能;点“长度与粗细”研究同种材料电阻与长度、横截面积的关系。选中“导体”元件即可换材料、改长度和粗细。
            </div>
            <div class="legend">
              <span><i style="background:#ff9d2e"></i>橙色箭头表示电流方向,箭头会沿导线移动,电流越大移动越快(电子实际移动方向与电流方向相反)</span>
              <span><i style="background:#2d6fae"></i>蓝色圆点表示接线柱</span>
            </div>
          </div>
        </details>

      </details>
    </div>

  </aside>
</main>

<!-- ================= 手机版:底部固定操作栏 + 抽屉 ================= -->
<div class="mbar" id="mbar">
  <!-- 常态:功能入口 -->
  <div class="mbar-main" id="mbarMain">
    <button class="mbtn" id="mBtnPalette" title="添加元件">+<span>元件</span></button>
    <button class="mbtn" id="mBtnInspector" title="选中元件的参数">⚙<span>参数</span></button>
    <button class="mbtn" id="mBtnData" title="电路状态与读数">📊<span>数据</span></button>
    <button class="mbtn" id="mBtnSchem" title="电路图:把实物连线自动画成标准电路图">📐<span>电路</span></button>
    <button class="mbtn" id="mBtnPresets" title="演示电路">📚<span>演示</span></button>
    <button class="mbtn" id="mBtnFit" title="把整个电路缩放居中显示">⤢<span>适应</span></button>
    <button class="mbtn" id="mBtnAbout" title="关于 / 帮助:使用说明与常见问题">❓<span>帮助</span></button>
    <button class="mbtn" id="mBtnFile" title="保存 / 打开实验、导出图片">📁<span>文件</span></button>
  </div>
  <!-- 选中元件后:整条变成操作条(删除 / 旋转 / 对调 / 复制) -->
  <div class="mbar-act" id="mbarAct">
    <button class="mbtn" id="mActParams" title="调参数(阻值、电压、材料…)">⚙<span>参数</span></button>
    <button class="mbtn" id="mActRot" title="旋转 90°(可连点)">↻<span id="mActRotLbl">旋转</span></button>
    <button class="mbtn" id="mActFlip" title="电池 / 发光二极管:对调正负极;其它元件:翻转 180°">⇄<span id="mActFlipLbl">对调+-</span></button>
    <button class="mbtn" id="mActCopy" title="复制所选元件(参数一起复制)">⧉<span>复制</span></button>
    <button class="mbtn danger" id="mActDel" title="删除所选元件">🗑<span id="mActDelLbl">删除</span></button>
    <button class="mbtn subtle" id="mActDone" title="取消选中,回到功能栏">✓<span>完成</span></button>
  </div>
</div>
<!-- 手机端常驻操作提示条(不用去抽屉里找) -->
<div class="mhint" id="mHint">
  <span class="mhint-txt">点接线柱 → 再点另一个 = 连导线 · 按住拖 = 移动元件 · 双指缩放/平移 · 底部 +元件 添加</span>
  <button class="mhint-x" id="mHintClose" title="收起提示">×</button>
</div>
<div class="mscrim" id="mScrim"></div>
<div class="msheet" id="mSheet">
  <div class="msheet-head">
    <b id="mSheetTitle">元件</b>
    <button id="mSheetClose" title="收起">×</button>
  </div>
  <div class="msheet-tip" id="mSheetTip"></div>
  <div class="msheet-body" id="mSheetBody"></div>
</div>

<footer>教学演示程序:把电源视为理想电源串联内阻 r,导线电阻忽略不计;灯泡灯丝电阻取设定值,未考虑温度变化;导体电阻按 R = ρL/S 计算(ρ 取 20℃ 附近的常用值),发光二极管用“导通压降 Vf + 内阻”的简化模型,滑动变阻器简化为两端变阻器(可口头补充说明)。</footer>

<!-- ================= 元件图鉴(菜单) ================= -->
<div class="lib-overlay" id="learnOverlay" hidden>
  <div class="learn-panel">
    <div class="learn-head">
      <b>🎓 操作学习</b>
      <button class="lib-close" id="learnClose" title="关闭">×</button>
    </div>
    <div class="learn-body" id="learnBody"></div>
    <div class="learn-dots-wrap" id="learnBar"></div>
    <div class="learn-foot">
      <button id="learnPrev" class="learn-btn">← 上一步</button>
      <button id="learnNext" class="learn-btn primary">下一步 →</button>
    </div>
  </div>
</div>

<div class="lib-overlay" id="hubOverlay" hidden>
  <div class="lib-panel" style="width:min(920px,100%)">
    <div class="lib-head">
      <b>⚡ 简易电路实验</b><span class="lib-sub">关卡模式 · 自由创造</span>
    </div>
    <div style="padding:22px">
      <div style="display:flex;gap:18px;flex-wrap:wrap">
        <div class="hub-card" id="hubLevels" style="flex:1;min-width:300px">
          <div class="hc-tag">MODE 01 // LEARNING</div>
          <h3>关卡模式</h3>
          <p>按章节逐关攻克。<br>亲手接线、亲眼看电流,做对才过关。</p>
          <div style="margin-top:16px;display:flex;align-items:baseline;gap:8px">
            <div class="hc-num" id="hubDone">0</div>
            <div style="font-family:Consolas,monospace;color:#7b8db0">/ <span id="hubTotal">28</span> 关</div>
            <button class="on" id="hubGoLevels" style="margin-left:auto">▶ 进入关卡</button>
          </div>
        </div>
        <div class="hub-card" id="hubFree" style="flex:1;min-width:300px">
          <div class="hc-tag">MODE 02 // SANDBOX</div>
          <h3>自由创造</h3>
          <p>无限画布、13 种元件、真实求解。<br>搭任意电路,可存可发、可导出电路图。</p>
          <div style="margin-top:16px;display:flex;align-items:baseline;gap:8px">
            <button class="on" id="hubGoFree">▶ 进入实验</button>
            <div style="font-family:Consolas,monospace;font-size:11px;color:#7b8db0;margin-left:auto">11 个演示电路 · 单文件离线</div>
          </div>
        </div>
      </div>
      <div style="margin-top:16px;display:flex;gap:10px;flex-wrap:wrap;align-items:center">
        <span class="tagline" style="font-size:11.5px;color:#7b8db0">快捷:</span>
        <button data-hub="presets">📚 演示电路库</button>
        <button data-hub="learn">🎓 操作学习</button>
        <button data-hub="lib">📖 元件图鉴</button>
        <button data-hub="about">❓ 使用手册</button>
      </div>
    </div>
  </div>
</div>

<div class="lib-overlay" id="pickOverlay" hidden>
  <div class="lib-panel" style="width:min(760px,100%)">
    <div class="lib-head">
      <b>关卡模式</b><span class="lib-sub">选择章节与关卡 · 进度自动保存</span>
      <button class="lib-close" id="pickClose" title="返回主菜单">×</button>
    </div>
    <div style="padding:18px 22px 24px" id="pickBody"></div>
  </div>
</div>

<div class="lib-overlay" id="resultOverlay" hidden>
  <div class="lib-panel" style="width:min(680px,100%)">
    <div class="lib-head">
      <b id="resTitle">检查结果</b><span class="lib-sub" id="resSub"></span>
      <button class="lib-close" id="resClose" title="关闭">×</button>
    </div>
    <div style="padding:20px 24px">
      <div id="resStars" style="font-size:26px;letter-spacing:8px;color:#c79c1e;margin-bottom:12px"></div>
      <div id="resGoals"></div>
      <div id="resExplain" style="margin-top:14px;padding:12px 14px;border:1px solid #d7dfec;border-radius:9px;background:#f7fafd;font-size:12.5px;line-height:1.75;color:#47597a"></div>
      <div style="margin-top:18px;display:flex;gap:10px;flex-wrap:wrap">
        <button class="danger" id="resRetry">⟲ 重试本关</button>
        <button id="resPick">返回关卡列表</button>
        <button class="on" id="resNext" style="margin-left:auto">下一关 ▶</button>
      </div>
    </div>
  </div>
</div>

<div class="lib-overlay" id="schemOverlay" hidden>
  <div class="lib-panel" style="width:min(1180px,100%)">
    <div class="lib-head">
      <b>电路图</b><span class="lib-sub" id="schemSub">由实物连线自动生成</span>
      <button class="lib-close" id="schemClose" title="关闭">×</button>
    </div>
    <div class="schem-wrap"><canvas id="schemCanvas"></canvas></div>
    <div class="schem-bar">
      <button id="schemSave">保存 PNG</button>
      <button id="schemRefresh">重新生成</button>
      <span class="schem-note" id="schemNote"></span>
    </div>
  </div>
</div>

<div class="lib-overlay" id="aboutOverlay" hidden>
  <div class="lib-panel">
    <div class="lib-head">
      <b>❓ 关于 / 帮助</b>
      <span class="lib-sub">这是什么 · 怎么操作 · 物理模型 · 常见问题</span>
      <button class="lib-close" id="aboutClose" title="关闭(Esc)">×</button>
    </div>
    <div class="lib-body">
      <div class="lib-side about-side">
        <div class="about-sidehead">目录</div>
        <button class="about-nav" data-goto="sec-一这是什么-0">一、这是什么</button>
        <button class="about-nav" data-goto="sec-二界面导览-1">二、界面导览</button>
        <button class="about-nav" data-goto="sec-三元件库13种-2">三、元件库(13 种)</button>
        <button class="about-nav" data-goto="sec-四内置11个演示电路-3">四、内置 11 个演示电路</button>
        <button class="about-nav" data-goto="sec-四之二最近版本新增的教学点v0041-4">四之二、最近版本新增的教学点(v0.0.41 起)</button>
        <button class="about-nav" data-goto="sec-四之三界面与交互v101起-5">四之三、界面与交互(v1.0.1 起)</button>
        <button class="about-nav" data-goto="sec-四之四电路图与实验文件-5b">四之四、简化电路图与实验文件(v1.0.34 起)</button>
        <button class="about-nav" data-goto="sec-五仿真与物理模型-6">五、仿真与物理模型</button>
        <button class="about-nav" data-goto="sec-六操作方式-7">六、操作方式</button>
        <button class="about-nav" data-goto="sec-七音效-8">七、音效</button>
        <button class="about-nav" data-goto="sec-八教学辅助功能-9">八、教学辅助功能</button>
        <button class="about-nav" data-goto="sec-九界面与视觉-10">九、界面与视觉</button>
        <button class="about-nav" data-goto="sec-十数据与隐私-11">十、数据与隐私</button>
        <button class="about-nav" data-goto="sec-十一分发与使用建议-12">十一、分发与使用建议</button>
        <button class="about-nav" data-goto="sec-十二技术说明-13">十二、技术说明</button>
        <button class="about-nav" data-goto="sec-十三已知边界-14">十三、已知边界</button>
        <button class="about-nav" data-goto="sec-十三之二版本与更新-15">十三之二、版本与更新</button>
        <button class="about-nav" data-goto="sec-十四常见问题-16">十四、常见问题</button>
      </div>
      <div class="lib-main about-main" id="aboutMain">
        <h1 class="about-title">简易电路实验展示网页</h1>
        <blockquote class="about-q"><b>当前版本 v1.0.10</b>(正式版第一版 v1.0.0 之后的第 10 次更新)| 完整更新记录见同目录 <code>circuit-lab-更新日志.md</code></blockquote>
<blockquote class="about-q">一个可以直接在浏览器里打开的初中物理电学演示与实验平台。</blockquote>
<blockquote class="about-q">单文件、离线可用、电脑与手机都能用。</blockquote>
<hr class="about-hr">
<h2 class="about-h2" id="sec-一这是什么-0">一、这是什么</h2>
<p>一个用于<b>物理课堂演示</b>与<b>学生自主实验</b>的交互式电路沙盒。老师点开就能用,不需要安装任何软件、不需要联网、不需要账号。</p>
<p>拖动元件、连接导线,页面会<b>实时计算</b>电流、电压、电功率,并用橙色箭头把电流方向和大小"画"出来——学生能直接看到"电流是怎样流动的"。</p>
<ul class="about-ul">
<li>文件:<code>circuit-lab.html</code>(单文件,约 221 KB)</li>
<li>打开方式:<b>双击即可</b>(用浏览器打开,推荐 Chrome / Edge / Safari)</li>
<li>依赖:<b>零外部依赖</b>,不加载任何网络资源,断网也能用</li>
</ul>
<pre class="about-pre">circuit-lab.html   ← 就这一个文件,拷到 U 盘、发给同事、传到班级群都能用</pre>
<hr class="about-hr">
<h2 class="about-h2" id="sec-二界面导览-1">二、界面导览</h2>
<h3 class="about-h3">电脑版</h3>
<pre class="about-pre">┌──────────────────────────────────────────────────────────────┐
│ 简易电路实验展示  物理课堂演示·拖动元件与导线自由搭建…        │
├──────────────────────────────────────────────────────────────┤
│ ↶撤销 ↷重做 🗑清空 │ - 100% + ⤢适应窗口 │ 🗺缩略图 📖元件图鉴 │
│ 🔊音效 ☀主题 🖥电脑版 │ 📚演示电路 ▾                          │
├──────────────────────────────────┬───────────────────────────┤
│                                  │ ▎添加元件                 │
│            无限画布              │  [13 种元件按钮]          │
│      (可缩放 / 平移 / 框选)     ├───────────────────────────┤
│                                  │ ▎电路状态 / 读数 / 元件参数│
│                                  ├───────────────────────────┤
│                                  │ ▎课堂提示 / 操作说明      │
└──────────────────────────────────┴───────────────────────────┘</pre>
<h3 class="about-h3">手机版</h3>
<p>针对触屏重排,不挤占画布:</p>
<pre class="about-pre">┌────────────────────────────┐
│ 简易电路实验展示            │
├────────────────────────────┤
│ ↶撤销 ↷重做 🗑清空 🗺缩略图 │  ← 一行 8 个按钮,图标在上文字在下
│ 📖图鉴 🔊音效 🌙主题 📱手机版│     不横向滚动,全部一眼可见
├────────────────────────────┤
│                            │
│         无限画布            │  ← 尽量多的空间留给电路
│                            │
├────────────────────────────┤
│ 长按接线柱 → 点另一个 = 连导线 · 双指缩放/平移 · …    ×│  ← 常驻操作提示
├────────────────────────────┤
│ +元件  ⚙参数  📊数据  📚演示  ⤢适应 │  ← 底部操作栏(点开为抽屉)
└────────────────────────────┘</pre>
<p>底部栏共 <b>8 个</b>:+元件 · ⚙参数 · 📊数据 · 📐电路(简化电路图)· 📚演示 · ⤢适应 · ❓帮助 · 📁文件(保存/打开实验、导出图片)</p>
<ul class="about-ul">
<li><b>自动识别</b>:触屏设备或窄屏自动进入手机版;也可以用顶部 🖥/📱 按钮<b>一键切换</b>(选择会记住)</li>
<li>手机端「数据」抽屉里有:电路状态、仪表读数、课堂提示、<b>手机专用操作说明</b>(默认展开)</li>
</ul>
<hr class="about-hr">
<h2 class="about-h2" id="sec-三元件库13种-2">三、元件库(13 种)</h2>
<table class="about-tb"><tr><th>分类</th><th>元件</th><th>可调参数</th></tr><tr><td>电源</td><td><b>电池</b></td><td>电压 1.5~6 V、内阻 0.1~2 Ω、<b>正负极可对调</b></td></tr><tr><td>控制</td><td><b>开关</b></td><td>断开 / 闭合(单击切换,有"咔哒"声)</td></tr><tr><td>控制</td><td><b>滑动变阻器</b></td><td>阻值连续可调</td></tr><tr><td>用电器</td><td><b>小灯泡</b></td><td>额定电压、额定功率、电阻(亮度随实际功率变化)</td></tr><tr><td>用电器</td><td><b>定值电阻</b></td><td>阻值</td></tr><tr><td>用电器</td><td><b>电动机</b></td><td>内阻(运转时有声音)</td></tr><tr><td>用电器</td><td><b>发光二极管 LED</b></td><td>导通压降(<b>只有真正形成闭合回路且有正向电流才发光</b>)</td></tr><tr><td>用电器</td><td><b>电铃</b></td><td>内阻(响铃,<b>电流越大声音越响</b>)</td></tr><tr><td>测量</td><td><b>电流表</b></td><td>串联接入;读数带电流方向(<b>→ / ←</b>),接反会标红提示"反接"</td></tr><tr><td>测量</td><td><b>电压表</b></td><td>并联接入;读数带正负号,表笔接反会标红提示"表笔接反"</td></tr><tr><td>保护</td><td><b>保险丝</b></td><td>额定电流(超流熔断并"啪"一声)</td></tr><tr><td>研究对象</td><td><b>导体</b></td><td><b>13 种材料</b> + 长度 + 横截面积</td></tr><tr><td>连接</td><td><b>接线点(接线柱)</b></td><td>用于导线拐弯、分支与汇合</td></tr></table>
<h3 class="about-h3">可选的 13 种导体材料</h3>
<p>银、铜、金、铝、铁、镍铬合金、铅笔芯、盐水、湿木、硅、干木、玻璃、橡胶</p>
<p>按 <b>R = ρL/S</b> 真实参与计算:材料不同、长度不同、粗细不同,电阻就不同,灯泡亮度也随之不同。</p>
<hr class="about-hr">
<h3 class="about-h3">画布上的元件编号</h3>
<p>画布中每个元件都带课本式编号,便于板书与口头讲解:</p>
<table class="about-tb"><tr><th>元件</th><th>编号</th><th>元件</th><th>编号</th></tr><tr><td>小灯泡</td><td><b>L</b>1、L2…</td><td>电流表</td><td><b>A</b>1</td></tr><tr><td>开关</td><td><b>S</b>1、S2…</td><td>电压表</td><td><b>V</b>1</td></tr><tr><td>电池(电源)</td><td><b>E</b>1、E2…</td><td>定值电阻</td><td><b>R</b>1</td></tr><tr><td>滑动变阻器</td><td><b>Rp</b>1</td><td>发光二极管</td><td><b>D</b>1</td></tr><tr><td>电动机</td><td><b>M</b>1</td><td>保险丝</td><td><b>F</b>1</td></tr></table>
<p>序号按"同类型元件的出现顺序"编排,<b>与右侧「仪表与用电器读数」区的编号完全一致</b>。</p>
<p>(电铃、导体、接线点没有通用字母符号,不编号;导体直接显示材料名。)</p>
<h2 class="about-h2" id="sec-四内置11个演示电路-3">四、内置 11 个演示电路</h2>
<p>点「📚 演示电路」即可载入(手机端在底部栏):</p>
<table class="about-tb"><tr><th>演示</th><th>内容</th><th>教学要点</th></tr><tr><td><b>基本电路</b></td><td>电源 + 开关 + 小灯泡</td><td>认识电路组成、通路/断路</td></tr><tr><td><b>串联</b></td><td>两灯串联</td><td>电流处处相等,U = U₁ + U₂</td></tr><tr><td><b>并联</b></td><td>两灯并联</td><td>各支路电压相等,I = I₁ + I₂</td></tr><tr><td><b>电流表·电压表</b></td><td>电阻 + 电流表 + 电压表</td><td>电流表串联、电压表并联的正确接法</td></tr><tr><td><b>短路演示</b></td><td>导线直接跨接电源两端</td><td><b>危险操作教育</b>:电流暴增、迸火星、保险丝熔断</td></tr><tr><td><b>保险丝保护</b></td><td>电源 + 开关 + 保险丝(0.4 A)+ 小灯泡</td><td>正常时 I≈0.29 A 灯正常亮;电压调到 6 V → 超流 → <b>保险丝熔断、电路断路、灯熄灭</b>(保护作用)</td></tr><tr><td><b>用电器短路</b></td><td>一条导线跨接左侧灯泡两端</td><td>局部短路:被短路的灯泡 U=0、I=0、<b>不亮</b>,另一个照常发光(中考易错)</td></tr><tr><td><b>滑动变阻器</b></td><td>滑动变阻器限流接法</td><td>滑片改变接入电阻 → 电流与灯泡亮度随之变化</td></tr><tr><td><b>伏安法测电阻</b></td><td>变阻器 + 电流表 + 电压表 + 待测电阻 Rx</td><td>读 U 与 I,验证 <b>R = U / I</b>(读数区会自动给出"实测 R = U / I")</td></tr><tr><td><b>不同导体对比</b></td><td>铜 / 铁 / 镍铬合金 / 铅笔芯 四条并联支路</td><td>人教版九年级 16.3「比较不同材料的导电性能」</td></tr><tr><td><b>长度与粗细</b></td><td>同种材料、不同 L 与 S</td><td>研究电阻与长度、横截面积的关系</td></tr></table>
<p>每个演示电路都<b>自动缩放居中</b>,元件间距经过压缩,手机上也能看清元件和名称。</p>
<hr class="about-hr">
<h2 class="about-h2" id="sec-四之二最近版本新增的教学点v0041-4">四之二、最近版本新增的教学点(v0.0.41 起)</h2>
<table class="about-tb"><tr><th>功能</th><th>说明</th></tr><tr><td><b>电动势与内阻分压</b></td><td>电路状态里同时显示 E、I·r、U,学生能直接看到 <b>U = E − I·r</b></td></tr><tr><td><b>内部损耗与电源效率</b></td><td>显示 <b>I²r</b> 与 <b>U/E</b>,内阻越大效率越低</td></tr><tr><td><b>实测 R = U / I</b></td><td>同时接了电流表和电压表时,读数区自动给出实测电阻</td></tr><tr><td><b>充电中提示</b></td><td>电流反向流入电池时,状态显示"充电中(电流反向)",I·r 标"反向"</td></tr><tr><td><b>重载 / 短路两级提示</b></td><td>外电路电阻接近内阻 → 重载;电流暴增且路端电压塌陷 → 短路</td></tr><tr><td><b>灯泡渐进烧断</b></td><td>实际功率超额定 1.2 倍亮 ⚠ 警告;超 1.5 倍并持续约 1.6 秒<b>灯丝烧断</b>(画布显示倒计时,及时降压可救回),可点「更换灯泡」恢复</td></tr><tr><td><b>串/并联自动识别</b></td><td>支持 2 个以上的灯泡,3 灯串联不会再被误判成混联</td></tr><tr><td><b>注解可锁定</b></td><td>Alt + 点击注解即可锁定,锁定后点击<b>穿透</b>到下面的元件</td></tr><tr><td><b>手机端可删导线</b></td><td>选中导线后,底部操作条切换为「删除导线 / 完成」</td></tr></table>
<h2 class="about-h2" id="sec-四之三界面与交互v101起-5">四之三、界面与交互(v1.0.1 起)</h2>
<table class="about-tb"><tr><th>调整</th><th>说明</th></tr><tr><td><b>参数卡常驻</b></td><td>「选中元件」固定在右侧栏最上方,选中任何元件都能立刻调参数</td></tr><tr><td><b>读数在左侧</b></td><td>「读数」做成页面左侧 156px 的窄长条(吸顶、内部可滚),元件很多也不挤压画布</td></tr><tr><td><b>右栏顺序</b></td><td>添加元件 → 选中元件 → 电路状态 → 课堂提示;<b>操作说明并入"课堂提示"</b>,右栏更清爽</td></tr><tr><td><b>元件按钮</b></td><td>元件面板 3 列大按钮(89×55),点击目标更大</td></tr><tr><td><b>元件编号</b></td><td>画布上标出 L1/L2、S1/S2、E1、A1、V1…(与读数区编号一致,见"画布上的元件编号")</td></tr><tr><td><b>电表表笔</b></td><td>电压表/电流表画出 <b>+/− 表笔标记</b>;接反时标记变红并标注「⚠ 表笔接反」</td></tr><tr><td><b>选中即滚入视口</b></td><td>在画布上点选元件(或学习关卡点名元件)时,参数卡片自动进入视野;添加元件等自动选中不会带动页面滚动</td></tr><tr><td><b>手机端不再有底部元件栏</b></td><td>v1.0.8 起移除,加元件统一走底部「+元件」抽屉(原来那条常驻栏会挡手);手机端画布同时铺满整屏</td></tr><tr><td><b>电表表笔标记</b></td><td>电压表/电流表画出 +/− 表笔,接反时变红并标注「⚠ 表笔接反」</td></tr><tr><td><b>开关与端子的点击判定</b></td><td>离元件中心更近时按"点元件本体"处理(保证缩放任意倍率下点开关都能正常通断)</td></tr></table>
<h2 class="about-h2" id="sec-四之四电路图与实验文件-5b">四之四、简化电路图与实验文件(v1.0.34 起)</h2>
<table class="about-tb"><tr><th>功能</th><th>说明</th></tr><tr><td><b>简化电路图</b></td><td>工具栏 <b>📐电路图</b>(手机底部「电路」):把实物连线自动画成<b>课本式标准电路图</b>——网表 → 串并联识别 → 自动布局 → 标准符号;图上带<b>电流方向箭头</b>(橙色三角,无电流不画、充电自动反向)与<b>读数</b>(元件 I=…、电源 I=…·U=…,开路时正好演示 U = E);可「保存 PNG」(离屏高倍重渲,打印不糊)。电桥等非串并联会退化为按连接关系示意</td></tr><tr><td><b>保存 / 打开实验</b></td><td>右侧栏「实验文件」→ <b>💾保存实验</b>:存成 JSON 文件(元件、导线、注释、参数、视角一起存),可再打开、可发给同学;<b>📂打开实验</b>:四道校验(格式/标识/版本/元件有效性),<b>文件不对绝不覆盖当前电路</b>,且打开操作本身可以撤销</td></tr><tr><td><b>导出图片</b></td><td><b>🖼导出图片</b>:把当前实物画面存成约 2400px 宽的高清 PNG(自动去掉选中框与缩略图),toast 会显示导出尺寸</td></tr><tr><td><b>双量程电表</b></td><td>选中电表 → 量程按钮组(电流表 <b>0.6/3 A</b>、电压表 <b>3/15 V</b>,两档互斥,相当于"改接正接线柱")</td></tr><tr><td><b>超量程提示</b></td><td>读数超过所选量程时<b>既报错又给真值</b>:读数照常显示只标红、画布电表画<b>红环</b>、提示卡建议换大量程——换档即解除</td></tr><tr><td><b>理想 / 实际电表</b></td><td>同一面板一键切换:理想表内阻 0 / ∞,实际表 0.02 Ω / 1 MΩ;面板实时显示<b>表负担</b>(电流表分压、电压表分流),切到理想后趋 0,直观理解"理想表不拆台"</td></tr></table>
<hr class="about-hr">
<h2 class="about-h2" id="sec-五仿真与物理模型-6">五、仿真与物理模型</h2>
<h3 class="about-h3">电路求解</h3>
<p>采用<b>节点法(改进节点分析)</b>:</p>
<ul class="about-ul">
<li>自动把导线连接的接线柱归并成同一个节点</li>
<li>每个节点加 1e-9 的漏电导,避免悬空节点导致矩阵奇异</li>
<li>高斯消元求解各节点电位,再算出每条导线、每个元件的电流</li>
<li>电池建模为<b>理想电压源 + 内阻</b>,所以能看到"路端电压随电流下降"的真实效果</li>
<li>支持并联、串联、混联、多电源、电表(电流表内阻、电压表内阻都按真实仪表处理)</li>
</ul>
<h3 class="about-h3">几个特意做真实的细节</h3>
<table class="about-tb"><tr><th>现象</th><th>程序里的处理</th></tr><tr><td><b>电流方向</b></td><td>自动测试逐一比对:<b>48 个箭头方向全部与求解结果一致</b>;对调电池正负极后 <b>47 个箭头全部反向</b>,且箭头前进方向就是它所指的方向(不会倒着走)</td></tr><tr><td><b>LED 单向导电</b></td><td>只有"正向电压 &gt; 导通压降"<b>且</b>"确实有电流流过(回路闭合)"才发光。只接一端 → 显示"有正向电压但回路没闭合 · 不发光"</td></tr><tr><td><b>短路</b></td><td>自动检测,画面迸火星、发出"噼啪"放电声,提示区给出安全教育文字</td></tr><tr><td><b>保险丝</b></td><td>电流超过额定值即熔断,断路并发出"啪"声</td></tr><tr><td><b>电铃</b></td><td>敲击音量随电流增大</td></tr><tr><td><b>灯泡亮度</b></td><td>按实际功率与额定功率之比发光</td></tr><tr><td><b>电池内阻</b></td><td>内阻越大,接上负载后路端电压掉得越明显</td></tr></table>
<h3 class="about-h3">性能</h3>
<p>单次求解约 <b>0.16 ms</b>(含 LED 的多次迭代),只在电路发生变化时求解,动画始终流畅。</p>
<hr class="about-hr">
<h2 class="about-h2" id="sec-六操作方式-7">六、操作方式</h2>
<h3 class="about-h3">电脑(鼠标 + 键盘)</h3>
<table class="about-tb"><tr><th>操作</th><th>方式</th></tr><tr><td>连导线</td><td><b>点一下接线柱</b>(它会亮起等待)→ <b>再点另一个接线柱</b>就连上了;点导线自动插入接线点;点空白处或按 Esc 取消。<b>按住拖动 = 移动元件</b>(拖动一律不接线)</td></tr><tr><td>移动元件</td><td>拖动元件本体</td></tr><tr><td>旋转</td><td>选中后按 <b>R</b> 或点参数面板的"旋转"(<b>电池转 180° 即正负极对调</b>)</td></tr><tr><td>删除</td><td>右键元件或导线</td></tr><tr><td>框选多个</td><td>空白处<b>按住拖动</b>(像框选文件);<b>Shift</b> 追加;<b>Ctrl+A</b> 全选</td></tr><tr><td>整组移动</td><td>框选后拖其中任意一个</td></tr><tr><td>整组旋转 / 删除</td><td><b>R</b> / <b>Delete</b></td></tr><tr><td>撤销 / 重做</td><td><b>Ctrl+Z</b> / <b>Ctrl+Y</b>(最多 120 步)</td></tr><tr><td>缩放</td><td>缩放按钮、<b>Ctrl + 滚轮</b></td></tr><tr><td>平移</td><td><b>Ctrl/⌘ + 拖动</b>、<b>中键拖动</b>、<b>空格 + 拖动</b></td></tr><tr><td><b>简化电路图</b></td><td>工具栏 <b>📐电路图</b>:把实物连线自动画成课本式标准电路图(带电流方向箭头与读数),可「保存 PNG」</td></tr><tr><td><b>保存 / 打开实验</b></td><td>右侧栏「实验文件」:<b>💾保存实验</b>(存成 JSON 文件)、<b>📂打开实验</b>(四道校验,文件不对<b>绝不覆盖当前电路</b>,打开也能撤销)、<b>🖼导出图片</b>(约 2400px 高清 PNG)</td></tr></table>
<h3 class="about-h3">手机 / 平板(触屏)</h3>
<table class="about-tb"><tr><th>操作</th><th>方式</th></tr><tr><td>连导线</td><td><b>点一下接线柱</b>(它会亮起等待)→ <b>再点另一个接线柱</b>就连上;点导线自动插入接线点;点空白取消。<b>按住拖动 = 移动元件</b>(拖动一律不接线)</td></tr><tr><td>移动元件</td><td>直接拖动元件本体(元件紧贴手指)</td></tr><tr><td><b>移动接线点</b></td><td><b>按住拖动</b></td></tr><tr><td><b>从接线点接线</b></td><td><b>点一下</b>接线点(中心或外圈都行)让它亮起,再点另一端即可;<b>按住拖动</b>仍是移动位置</td></tr><tr><td>缩放 / 平移</td><td><b>双指捏合</b>、<b>双指拖动</b></td></tr><tr><td><b>调参数 / 旋转 / 对调+- / 复制 / 删除</b></td><td>轻点元件选中后,<b>底部整条操作栏变成操作条</b>:<b>⚙参数</b> · ↻旋转 · ⇄对调+-(电池/发光二极管,其它元件是「翻转」)· ⧉复制 · 🗑删除 · ✓完成,一步到位;多选时变成「整组旋转 / 删N个」</td></tr><tr><td>调参数(阻值、电压、材料…)</td><td>操作条第一个按钮 <b>⚙参数</b>(未选中时是常态栏的 ⚙参数)</td></tr><tr><td>添加元件</td><td>底部 <b>+元件</b>,<b>可以连续点好几个</b>;新元件会落在抽屉上方看得见的位置</td></tr><tr><td><b>简化电路图</b></td><td>底部 <b>📐电路</b>:实物连线自动生成课本式电路图(带电流方向与读数),可「保存 PNG」</td></tr><tr><td><b>保存 / 打开实验 · 导出图片</b></td><td>底部 <b>📁文件</b> 抽屉:<b>💾保存实验</b>(JSON)、<b>📂打开实验</b>(校验不过不覆盖当前电路)、<b>🖼导出图片</b>(约 2400px 高清 PNG)</td></tr></table>
<blockquote class="about-q">接线点特意做成<b>一个小手势区分</b>:<b>按住拖 = 移动位置</b>,<b>点一下 = 让它亮起等着接另一端</b>(此时点另一个接线柱就连上、点导线自动插接线点)。两种意图互不干扰,也不会"拖不动"。</blockquote>
<h3 class="about-h3">添加元件时的反馈(手机与电脑一致)</h3>
<ol class="about-ol">
<li><b>放置音效</b>——低频"咚哒"一声,像把元件轻轻放在桌上</li>
<li><b>顶部气泡</b>——"已添加:小灯泡",连续添加时显示"(本次共 3 个)"</li>
<li><b>画布高亮</b>——新元件周围闪一圈橙色光环</li>
<li><b>自动纳入视野</b>——如果落点超出视野,画面自动平移把它带进来</li>
</ol>
<hr class="about-hr">
<h2 class="about-h2" id="sec-七音效-8">七、音效</h2>
<p>全部为 Web Audio 实时合成,不加载任何音频文件:</p>
<table class="about-tb"><tr><th>声音</th><th>触发</th></tr><tr><td>开关"咔哒"</td><td>切换开关</td></tr><tr><td>电铃"叮——"</td><td>电铃通电,<b>电流越大越响</b></td></tr><tr><td>电动机运转声</td><td>电动机通电</td></tr><tr><td>短路"噼啪"放电</td><td>检测到短路</td></tr><tr><td>保险丝熔断"啪"</td><td>超流熔断</td></tr><tr><td>放置"咚哒"</td><td>添加元件</td></tr></table>
<p>顶部 🔊 按钮可一键静音。</p>
<hr class="about-hr">
<h2 class="about-h2" id="sec-八教学辅助功能-9">八、教学辅助功能</h2>
<ul class="about-ul">
<li><b>实时读数</b>:电源输出电流、路端电压、输出功率、外电路总电阻;每个灯泡的功率与亮度百分比</li>
<li><b>课堂提示</b>:自动识别当前电路是串联还是并联,给出对应的电压电流规律、欧姆定律提示;短路时给出安全警示;没有电源时提示"需要电源"</li>
<li><b>元件图鉴(📖)</b>:13 个条目,按 7 个分类组织,每条包含</li>
<li><b>电路符号图</b> + <b>实物插画</b>(程序绘制的 SVG,不是网络图片)</li>
<li>原理说明(如"电池把化学能转化为电能…")</li>
<li>参数表(如"本程序可调电压 1.5~6 V")</li>
<li><b>规格变体</b>——例如电池条下列出 1.5V 干电池 / 3V 纽扣电池 / 9V 层叠电池 / 电池组,每个变体都有对应插画、规格和用途说明</li>
<li>注意事项(如"不要把电池两极直接用导线连接")</li>
<li><b>操作说明</b>:电脑版讲键鼠操作,手机版讲触屏手势,各显示各的,互不干扰</li>
</ul>
<hr class="about-hr">
<h2 class="about-h2" id="sec-九界面与视觉-10">九、界面与视觉</h2>
<ul class="about-ul">
<li><b>无限画布</b>:可以一直往四周扩展,配合右下角<b>缩略图</b>快速定位;缩略图可拖动、可缩放到任意大小、可隐藏</li>
<li><b>亮色 / 暗色主题</b>:一键切换(适合教室投影与暗光环境)</li>
<li><b>手机版 / 电脑版布局</b>:自动识别 + 一键切换,选择会记住</li>
<li><b>电流可视化</b>:橙色箭头沿导线流动,方向即电流方向,<b>速度随电流大小变化</b>;接线柱为蓝色圆点</li>
<li>手机端<b>常驻操作提示条</b>(可收起并记住),不用去菜单里翻</li>
</ul>
<hr class="about-hr">
<h2 class="about-h2" id="sec-十数据与隐私-11">十、数据与隐私</h2>
<ul class="about-ul">
<li>完全在本地运行,<b>不上传任何数据、不联网</b></li>
<li>只在浏览器 <code>localStorage</code> 里记住 5 项偏好:主题、缩略图显隐、布局模式、提示条状态</li>
<li>清空方式:浏览器设置里清除该页面站点数据即可</li>
</ul>
<hr class="about-hr">
<h2 class="about-h2" id="sec-十一分发与使用建议-12">十一、分发与使用建议</h2>
<table class="about-tb"><tr><th>场景</th><th>做法</th></tr><tr><td>教室投影演示</td><td>双击打开,按 F11 全屏;建议用「演示电路」菜单上课</td></tr><tr><td>学生自己练</td><td>把 <code>circuit-lab.html</code> 发到班级群,学生下载后用浏览器打开</td></tr><tr><td>U 盘 / 无网环境</td><td>直接拷贝该文件,无需任何其他文件</td></tr><tr><td>手机使用</td><td>用浏览器打开该文件;<b>不要用微信/QQ 内置预览</b>(会过滤脚本导致显示不出),请点右上角「用其他应用打开」并选择浏览器</td></tr></table>
<hr class="about-hr">
<h2 class="about-h2" id="sec-十二技术说明-13">十二、技术说明</h2>
<ul class="about-ul">
<li><b>纯前端单文件</b>:HTML + CSS + 原生 JavaScript,无框架、无构建、无外部资源</li>
<li><b>约 4350 行</b>,其中包含自绘的电路符号与实物插画(全部为程序生成的 SVG)</li>
<li><b>质量保障</b>:<b>23 个自动化测试套件、641 项断言</b>,覆盖</li>
<li>电路求解正确性(基尔霍夫定律、串并联规律、功率)</li>
<li>电流方向与箭头一致性、电池极性对调</li>
<li>LED 单向导电、短路、熔断、电铃音量</li>
<li>导体材料与 R = ρL/S</li>
<li>拖拽精度(0.00 px 误差)、缩放平移、无限画布、缩略图</li>
<li>撤销/重做、框选多选、旋转翻转</li>
<li>触屏两段式连线、接线点手势、手机版布局、工具栏与抽屉</li>
<li>主题、音效、元件图鉴、演示电路完整性</li>
</ul>
<hr class="about-hr">
<h2 class="about-h2" id="sec-十三已知边界-14">十三、已知边界</h2>
<ul class="about-ul">
<li>采用<b>直流稳态</b>模型:不含交流、电容电感、暂态过程</li>
<li>电流表、电压表按接近真实的仪表建模(电流表 0.02 Ω、电压表 1 MΩ),会像真实仪表那样轻微影响电路,但不涉及仪表精度等级与读数误差分析</li>
<li>不模拟磁场、通电导线受力、电磁感应等拓展内容</li>
<li>微信/QQ 内置浏览器会拦截脚本,<b>必须用系统浏览器打开</b></li>
</ul>
<hr class="about-hr">
<h2 class="about-h2" id="sec-十三之二版本与更新-15">十三之二、版本与更新</h2>
<ul class="about-ul">
<li>当前版本:<b>v1.0.45</b> (正式版基线 v1.0.0,此后每次修改 +0.0.1)</li>
<li>版本规则:每个版本的编号每次修改 +0.0.1;完整清单见 <code>circuit-lab-更新日志.md</code>(v1.0.11 起逐版可查)</li>
<li>自测规模:<b>47 个测试套件、1207 项断言</b>(含真实求解、真实渲染与像素级取证的回归守卫)</li>
</ul>
<h2 class="about-h2" id="sec-十四常见问题-16">十四、常见问题</h2>
<p><b>Q:打开后一片空白?</b></p>
<p>A:多半是用微信/QQ 内置浏览器打开的。请用系统浏览器(Chrome / Edge / Safari / 手机自带浏览器)打开该文件。</p>
<p><b>Q:手机上元件和文字太小?</b></p>
<p>A:点底部「⤢适应」一键缩放居中;或直接<b>双指捏合</b>放大。演示电路的元件间距已针对手机压缩过。</p>
<p><b>Q:点了接线柱没反应 / 连线失败?</b></p>
<p>A:<b>点一下</b>接线柱,它会亮起表示"等另一端",再点另一个接线柱就连上;点自己或点空白即取消。<b>按住拖动</b>会被当作"移动元件",不算接线。</p>
<p><b>Q:怎么保存实验、发给学生?</b></p>
<p>A:右侧栏「实验文件」→ <b>💾保存实验</b> 得到一个 JSON 文件;对方在同一位置 <b>📂打开实验</b> 即可(手机在底部 📁文件 抽屉里)。<b>🖼导出图片</b> 可把当前画面存成高清 PNG,插入试卷或课件。</p>
<p><b>Q:电表显示"超量程"?</b></p>
<p>A:读数超过了所选量程(比如 0.6 A 档测到 1.9 A)。读数会<b>标红并给出真值</b>,把量程改接到大量程(3 A / 15 V)即解除;选中电表还能切换<b>理想 / 实际</b>电表,对比内阻对电路的影响。</p>
<p><b>Q:「📐电路图」和实物图有什么区别?</b></p>
<p>A:实物图是接线的样子;电路图是<b>课本式的标准符号图</b>(程序按连线自动生成),带电流方向箭头与读数,适合对照讲串并联、示范画电路图。</p>
<p><b>Q:LED 接上为什么不亮?</b></p>
<p>A:LED 是单向导通的:需要①正向电压足够 <b>且</b> ②回路闭合确实有电流。只接一端、或接反了都不会亮——这正是它的教学价值。</p>
<p><b>Q:手机上怎么删除元件?</b></p>
<p>A:<b>轻点元件选中</b>,底部整条操作栏会立刻变成操作条:<b>⚙参数 · ↻旋转 · ⇄对调+- · ⧉复制 · 🗑删除 · ✓完成</b>。点红色「🗑删除」即可,同一行还能旋转、对调正负极、复制;<b>调参数也在这一行</b>(第一个按钮)。多选时显示「整组旋转 / 删N个」。点「✓完成」或点画布空白处即退出操作条。</p>
<p><b>Q:调转电池正负极怎么操作?</b></p>
<p>A:选中电池,按 <b>R</b>(或点参数面板的"旋转")转 180°。电流箭头会立刻反向。</p>
<hr class="about-hr">
<p class="about-note">文档对应版本:<code>circuit-lab.html</code> v1.0.45(单文件、离线可用;47 个测试套件 / 1207 项断言全部通过)</p>
      </div>
    </div>
  </div>
</div>
<div class="lib-overlay" id="libOverlay" hidden>
  <div class="lib-panel">
    <div class="lib-head">
      <b>📖 元件图鉴</b>
      <span class="lib-sub">选左侧元件 · 电路符号 / 实物示意 / 原理 / 常见规格</span>
      <button class="lib-close" id="libClose" title="关闭(Esc)">×</button>
    </div>
    <div class="lib-body">
      <div class="lib-side" id="libSide"></div>
      <div class="lib-main" id="libMain"></div>
    </div>
  </div>
</div>

<script>
/* =======================================================================
   一、电路求解器(纯函数,可单独测试)
   -----------------------------------------------------------------------
   方法:节点法(Nodal Analysis)
     · 导线把接线柱连通 -> 并查集合并成同一个节点
     · 电阻类元件(灯泡/电阻/闭合开关/电流表/电压表)用导纳 1/R 盖章
     · 电源(电动势 V、内阻 r)用诺顿等效:电流源 V/r 并联电导 1/r
     · 每个节点对地加 1e-9 的微小电导,避免孤立节点导致矩阵奇异
     · 高斯消元(列主元)求解节点电位
   ======================================================================= */
const Solver = (function () {
  'use strict';

  function gauss(A, b) {
    const n = b.length;
    if (n === 0) return [];
    const M = A.map(function (row, i) { return row.concat([b[i]]); });
    for (let c = 0; c < n; c++) {
      let p = c;
      for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
      if (p !== c) { const t = M[p]; M[p] = M[c]; M[c] = t; }
      const piv = M[c][c];
      if (Math.abs(piv) < 1e-15) continue;
      for (let r = c + 1; r < n; r++) {
        const f = M[r][c] / piv;
        if (f === 0) continue;
        for (let k = c; k <= n; k++) M[r][k] -= f * M[c][k];
      }
    }
    const x = new Array(n).fill(0);
    for (let r = n - 1; r >= 0; r--) {
      let s = M[r][n];
      for (let k = r + 1; k < n; k++) s -= M[r][k] * x[k];
      x[r] = Math.abs(M[r][r]) < 1e-15 ? 0 : s / M[r][r];
    }
    return x;
  }

  /**
   * input = {
   *   wires: [[termA, termB], ...]            // 导线:两端接线柱同名
   *   elements: [
   *     {id, kind:'R', R, a, b},              // 电阻、灯泡、电流表(小R)、电压表(大R)
   *     {id, kind:'open', a, b},              // 断开的开关
   *     {id, kind:'source', V, r, a, b}       // a = 正极接线柱, b = 负极接线柱
   *   ]
   * }
   */
  function solve(input) {
    const wires = input.wires || [];
    const elements = input.elements || [];

    const parent = new Map();
    function find(x) {
      if (!parent.has(x)) parent.set(x, x);
      let r = x;
      while (parent.get(r) !== r) r = parent.get(r);
      while (parent.get(x) !== r) { const nx = parent.get(x); parent.set(x, r); x = nx; }
      return r;
    }
    function union(a, b) { const ra = find(a), rb = find(b); if (ra !== rb) parent.set(ra, rb); }

    elements.forEach(function (e) { find(e.a); find(e.b); });
    wires.forEach(function (w) { union(w[0], w[1]); });

    const roots = [];
    const seen = new Set();
    parent.forEach(function (_, k) {
      const r = find(k);
      if (!seen.has(r)) { seen.add(r); roots.push(r); }
    });

    // 真实电源(virtual=true 的是发光二极管等非线性元件的等效模型,不参与"电源"统计)
    const sources = elements.filter(function (e) { return e.kind === 'source' && !e.virtual; });
    const groundRoot = sources.length ? find(sources[0].b) : (roots[0] || null);

    const idx = new Map();
    let n = 0;
    roots.forEach(function (r) { if (r !== groundRoot) idx.set(r, n++); });

    const A = [], b = [];
    for (let i = 0; i < n; i++) { A.push(new Array(n).fill(0)); b.push(0); }
    for (let i = 0; i < n; i++) A[i][i] += 1e-9;   // 微小对地电导,防奇异

    function rowOf(term) {
      const r = find(term);
      return r === groundRoot ? -1 : idx.get(r);
    }
    function addG(i, j, G) {
      if (i >= 0) { A[i][i] += G; if (j >= 0) A[i][j] -= G; }
      if (j >= 0) { A[j][j] += G; if (i >= 0) A[j][i] -= G; }
    }
    function inject(i, cur) { if (i >= 0) b[i] += cur; }

    elements.forEach(function (e) {
      const i = rowOf(e.a), j = rowOf(e.b);
      if (e.kind === 'R') {
        const R = Math.max(Number(e.R) || 1e-3, 1e-6);
        addG(i, j, 1 / R);
      } else if (e.kind === 'source') {
        const r = Math.max(Number(e.r) || 0.5, 1e-4);
        const V = Number(e.V) || 0;
        addG(i, j, 1 / r);
        inject(i, V / r);      // 电流由负极经电源内部流向正极,注入正极节点
        inject(j, -V / r);
      }
      // kind === 'open' 不做任何处理
    });

    const x = gauss(A, b);
    function vTerm(term) {
      const r = find(term);
      return r === groundRoot ? 0 : (x[idx.get(r)] || 0);
    }

    const results = new Map();
    let shortCircuit = false;
    let heavyLoad = false;      // 重载:外电路电阻接近/小于电源内阻(路端电压明显塌陷)
    const srcOut = [];
    elements.forEach(function (e) {
      const va = vTerm(e.a), vb = vTerm(e.b);
      if (e.kind === 'R') {
        const R = Math.max(Number(e.R) || 1e-3, 1e-6);
        const I = (va - vb) / R;
        results.set(e.id, { I: I, U: va - vb, P: Math.abs(I * (va - vb)) });
      } else if (e.kind === 'source') {
        const r = Math.max(Number(e.r) || 0.5, 1e-4);
        const V = Number(e.V) || 0;
        const U = va - vb;                    // 路端电压
        const I = V / r - U / r;              // 流出正极的电流
        results.set(e.id, { I: I, U: U, P: Math.abs(I * U), V: V, r: r });
        if (!e.virtual) {
          if (Math.abs(I) > 1.0 && Math.abs(U) < 0.5 * Math.abs(V)) shortCircuit = true;
          // 重载(比短路轻一级):外电路等效电阻 < 3 倍内阻 → 大量电压落在内阻上,
          // 多支路并联、灯泡太多时就是这种情况(课堂演示"并联支路越多总电流越大"很有用)
          if (!shortCircuit && r > 0 && Math.abs(I) > 1e-6) {
            const Rext = Math.abs(U / I);
            if (Rext < 3 * r) heavyLoad = true;
          }
          srcOut.push({ id: e.id, I: I, U: U, V: V, r: r });
        }
      } else {
        results.set(e.id, { I: 0, U: va - vb, P: 0 });
      }
    });

    return {
      ok: true,
      nodeCount: n,
      vOf: vTerm,
      netOf: function (term) { return find(term); },
      results: results,
      sources: srcOut,
      shortCircuit: shortCircuit, heavyLoad: heavyLoad
    };
  }

  /**
   * 计算每根导线上的电流(用于电流方向动画)
   * 原理:同一节点内,导线图取一棵生成树,子树注入电流之和 = 该子树到父节点的导线电流
   *   wires: [[termA, termB], ...]   与界面中的导线顺序一致
   *   inj  : Map(接线柱 -> 流入用电器内部的电流)
   * 返回:flows[i] > 0 表示电流沿 wires[i] 的 a -> b 方向
   */
  function wireFlows(sol, wires, inj) {
    const flows = new Array(wires.length).fill(0);
    const byNet = new Map();
    wires.forEach(function (w, i) {
      const r = sol.netOf(w[0]);
      if (!byNet.has(r)) byNet.set(r, []);
      byNet.get(r).push(i);
    });
    byNet.forEach(function (edgeIdxs) {
      const adj = new Map();
      function push(t, e, o) { if (!adj.has(t)) adj.set(t, []); adj.get(t).push({ e: e, o: o }); }
      edgeIdxs.forEach(function (i) {
        push(wires[i][0], i, wires[i][1]);
        push(wires[i][1], i, wires[i][0]);
      });
      const start = wires[edgeIdxs[0]][0];
      const visited = new Set([start]);
      const parentEdge = new Map(), parentTerm = new Map();
      const order = [start], stack = [start];
      while (stack.length) {
        const t = stack.pop();
        (adj.get(t) || []).forEach(function (nb) {
          if (!visited.has(nb.o)) {
            visited.add(nb.o); parentEdge.set(nb.o, nb.e); parentTerm.set(nb.o, t);
            order.push(nb.o); stack.push(nb.o);
          }
        });
      }
      const sum = new Map();
      for (let i = order.length - 1; i >= 0; i--) {
        const t = order[i];
        let s = inj.get(t) || 0;
        (adj.get(t) || []).forEach(function (nb) { if (parentTerm.get(nb.o) === t) s += (sum.get(nb.o) || 0); });
        sum.set(t, s);
      }
      order.forEach(function (t) {
        const pe = parentEdge.get(t);
        if (pe === undefined) return;
        const flow = -sum.get(t);                            // 由 t 流向父节点的电流
        flows[pe] = (wires[pe][0] === t) ? flow : -flow;     // 统一为 a->b 方向
      });
    });
    return flows;
  }

  return { solve: solve, gauss: gauss, wireFlows: wireFlows };
})();

/* =======================================================================
   一·五、音效引擎(Web Audio 实时合成,不依赖任何音频文件)
     · 开关:短促的"咔哒"声
     · 电铃:金属质感的"叮——",有电流时持续敲击
     · 电动机:低频嗡鸣 + 转动风声,转速随电流变化
     · 短路:持续的电流嗡嗡声 + 随机"噼啪"放电声
     · 保险丝熔断:"啪"的一声
   浏览器要求先有用户操作才允许出声,所以第一次点击画面时才真正启动音频。
   ======================================================================= */
const Sound = (function () {
  'use strict';
  let ac = null, master = null, ready = false;
  let unlocked = false, enabled = true;
  let motorOsc = null, motorGain = null, motorNoiseGain = null, motorFilter = null;
  let shortOsc = null, shortGain = null, shortNoiseGain = null;
  let bellTimer = 0, sparkTimer = 0;
  let lastMotor = -1, lastSpeed = -1, lastShort = -1;

  function noiseBuffer(sec) {
    const n = Math.max(1, Math.floor(ac.sampleRate * sec));
    const buf = ac.createBuffer(1, n, ac.sampleRate);
    const d = buf.getChannelData(0);
    for (let i = 0; i < n; i++) d[i] = Math.random() * 2 - 1;
    return buf;
  }

  function ensure() {
    if (ac) return ac;
    const AC = (typeof window !== 'undefined') && (window.AudioContext || window.webkitAudioContext);
    if (!AC) return null;
    try { ac = new AC(); } catch (e) { ac = null; return null; }
    master = ac.createGain();
    master.gain.value = 0.5;
    master.connect(ac.destination);

    // 电动机:锯齿波经低通 = 电机嗡鸣;带通噪声 = 转动风声
    motorOsc = ac.createOscillator();
    motorOsc.type = 'sawtooth';
    motorOsc.frequency.value = 90;
    motorFilter = ac.createBiquadFilter();
    motorFilter.type = 'lowpass';
    motorFilter.frequency.value = 520;
    motorFilter.Q.value = 3;
    motorGain = ac.createGain();
    motorGain.gain.value = 0;
    motorOsc.connect(motorFilter); motorFilter.connect(motorGain); motorGain.connect(master);
    motorOsc.start();

    const mn = ac.createBufferSource();
    mn.buffer = noiseBuffer(2); mn.loop = true;
    const nf = ac.createBiquadFilter();
    nf.type = 'bandpass'; nf.frequency.value = 950; nf.Q.value = 0.8;
    motorNoiseGain = ac.createGain();
    motorNoiseGain.gain.value = 0;
    mn.connect(nf); nf.connect(motorNoiseGain); motorNoiseGain.connect(master);
    mn.start();

    // 短路:50Hz 方波 = 电流嗡嗡声;高通噪声 = "滋滋"放电声
    shortOsc = ac.createOscillator();
    shortOsc.type = 'square';
    shortOsc.frequency.value = 50;
    const sf = ac.createBiquadFilter();
    sf.type = 'lowpass'; sf.frequency.value = 320;
    shortGain = ac.createGain();
    shortGain.gain.value = 0;
    shortOsc.connect(sf); sf.connect(shortGain); shortGain.connect(master);
    shortOsc.start();

    const sn = ac.createBufferSource();
    sn.buffer = noiseBuffer(2); sn.loop = true;
    const hf = ac.createBiquadFilter();
    hf.type = 'highpass'; hf.frequency.value = 2400;
    shortNoiseGain = ac.createGain();
    shortNoiseGain.gain.value = 0;
    sn.connect(hf); hf.connect(shortNoiseGain); shortNoiseGain.connect(master);
    sn.start();

    ready = true;
    return ac;
  }

  function resume() {
    const c = ensure();
    if (!c) return;
    unlocked = true;
    if (c.state === 'suspended' && c.resume) c.resume();
  }
  function setEnabled(on) {
    enabled = !!on;
    if (!enabled && ready) {
      const t = ac.currentTime;
      motorGain.gain.setTargetAtTime(0, t, 0.03);
      motorNoiseGain.gain.setTargetAtTime(0, t, 0.03);
      shortGain.gain.setTargetAtTime(0, t, 0.03);
      shortNoiseGain.gain.setTargetAtTime(0, t, 0.03);
      lastMotor = lastSpeed = lastShort = -1;
    }
  }
  const isEnabled = () => enabled;

  /* 开关"咔哒"声 */
  function click(strength) {
    if (!unlocked || !enabled) return;
    const c = ensure(); if (!c) return;
    const t = c.currentTime, k = strength === undefined ? 1 : strength;
    const s = c.createBufferSource();
    s.buffer = noiseBuffer(0.06);
    const f = c.createBiquadFilter();
    f.type = 'bandpass'; f.frequency.value = 2400 + Math.random() * 600; f.Q.value = 1.1;
    const g = c.createGain();
    g.gain.setValueAtTime(0.0001, t);
    g.gain.linearRampToValueAtTime(0.55 * k, t + 0.004);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.07);
    s.connect(f); f.connect(g); g.connect(master);
    s.start(t); s.stop(t + 0.12);

    const o = c.createOscillator();
    o.type = 'triangle';
    o.frequency.setValueAtTime(320, t);
    o.frequency.exponentialRampToValueAtTime(130, t + 0.05);
    const g2 = c.createGain();
    g2.gain.setValueAtTime(0.22 * k, t);
    g2.gain.exponentialRampToValueAtTime(0.001, t + 0.09);
    o.connect(g2); g2.connect(master);
    o.start(t); o.stop(t + 0.12);
  }

  /* 电铃:一次敲击(多个非谐波分音叠加,模拟金属铃碗) */
  function bellStrike(level) {
    if (!unlocked || !enabled) return;
    const c = ensure(); if (!c) return;
    const t = c.currentTime, base = 1150;
    const parts = [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.13]];
    for (let i = 0; i < parts.length; i++) {
      const o = c.createOscillator();
      o.type = 'sine';
      o.frequency.value = base * parts[i][0] * (1 + (Math.random() - 0.5) * 0.006);
      const g = c.createGain();
      const amp = 0.15 * parts[i][1] * level;
      g.gain.setValueAtTime(0.0001, t);
      g.gain.linearRampToValueAtTime(amp, t + 0.005);
      g.gain.exponentialRampToValueAtTime(0.0008, t + 0.85 / Math.sqrt(parts[i][0]));
      o.connect(g); g.connect(master);
      o.start(t); o.stop(t + 1.1);
    }
  }

  /* 火花/"噼啪"放电声 */
  function spark(level) {
    if (!unlocked || !enabled) return;
    const c = ensure(); if (!c) return;
    const t = c.currentTime, k = level === undefined ? 1 : level;
    const s = c.createBufferSource();
    s.buffer = noiseBuffer(0.12);
    const f = c.createBiquadFilter();
    f.type = 'highpass'; f.frequency.value = 1800 + Math.random() * 2600;
    const g = c.createGain();
    g.gain.setValueAtTime(0.0001, t);
    g.gain.linearRampToValueAtTime(0.3 * k, t + 0.002);
    g.gain.exponentialRampToValueAtTime(0.0008, t + 0.04 + Math.random() * 0.08);
    s.connect(f); f.connect(g); g.connect(master);
    s.start(t); s.stop(t + 0.2);

    const o = c.createOscillator();
    o.type = 'square';
    o.frequency.value = 2600 + Math.random() * 3000;
    const g2 = c.createGain();
    g2.gain.setValueAtTime(0.05 * k, t);
    g2.gain.exponentialRampToValueAtTime(0.0005, t + 0.05);
    o.connect(g2); g2.connect(master);
    o.start(t); o.stop(t + 0.08);
  }

  /* 保险丝熔断"啪" */
  function pop() {
    if (!unlocked || !enabled) return;
    click(1.4);
    spark(1.2);
    const c = ensure(); if (!c) return;
    const t = c.currentTime;
    const o = c.createOscillator();
    o.type = 'sawtooth';
    o.frequency.setValueAtTime(900, t);
    o.frequency.exponentialRampToValueAtTime(90, t + 0.16);
    const g = c.createGain();
    g.gain.setValueAtTime(0.18, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.2);
    o.connect(g); g.connect(master);
    o.start(t); o.stop(t + 0.22);
  }

  /* 放置元件的声音:一下"咚哒"——低频闷响 + 轻微敲击瞬态,像把元件轻放在桌上 */
  function place() {
    if (!unlocked || !enabled) return;
    const c = ensure(); if (!c) return;
    const t = c.currentTime;

    const thud = c.createOscillator();
    thud.type = 'sine';
    thud.frequency.setValueAtTime(185, t);
    thud.frequency.exponentialRampToValueAtTime(82, t + 0.14);
    const g1 = c.createGain();
    g1.gain.setValueAtTime(0.0001, t);
    g1.gain.exponentialRampToValueAtTime(0.34, t + 0.008);
    g1.gain.exponentialRampToValueAtTime(0.0001, t + 0.18);
    thud.connect(g1); g1.connect(master);
    thud.start(t); thud.stop(t + 0.2);

    const clk = c.createBufferSource();
    clk.buffer = noiseBuffer(0.05);
    const bp = c.createBiquadFilter();
    bp.type = 'bandpass';
    bp.frequency.value = 2400;
    bp.Q.value = 0.9;
    const g2 = c.createGain();
    g2.gain.setValueAtTime(0.22, t);
    g2.gain.exponentialRampToValueAtTime(0.0001, t + 0.05);
    clk.connect(bp); bp.connect(g2); g2.connect(master);
    clk.start(t); clk.stop(t + 0.06);
  }

  /* 每帧更新持续音(电动机 / 短路)与电铃敲击节奏 */
  function tick(dt, want) {
    if (!unlocked || !enabled || !ready) return;
    const t = ac.currentTime;
    const m = Math.max(0, Math.min(1, want.motor || 0));
    const sp = Math.max(0, Math.min(1, want.motorSpeed || 0));
    if (Math.abs(m - lastMotor) > 0.01 || Math.abs(sp - lastSpeed) > 0.02) {
      motorGain.gain.setTargetAtTime(0.17 * m, t, 0.08);
      motorNoiseGain.gain.setTargetAtTime(0.055 * m, t, 0.08);
      motorOsc.frequency.setTargetAtTime(72 + 120 * sp, t, 0.15);
      motorFilter.frequency.setTargetAtTime(380 + 820 * sp, t, 0.15);
      lastMotor = m; lastSpeed = sp;
    }
    if (want.bell > 0) {
      bellTimer -= dt;
      if (bellTimer <= 0) {
        bellStrike(want.bell);
        // 电流越大,铃锤敲得越响也越快
        bellTimer = 0.20 - 0.07 * Math.min(1, want.bell);
      }
    } else {
      bellTimer = 0;
    }
    const sh = Math.max(0, Math.min(1, want.short || 0));
    if (sh > 0) {
      if (Math.abs(sh - lastShort) > 0.02) {
        shortGain.gain.setTargetAtTime(0.1 * sh, t, 0.05);
        shortNoiseGain.gain.setTargetAtTime(0.07 * sh, t, 0.05);
        lastShort = sh;
      }
      sparkTimer -= dt;
      if (sparkTimer <= 0) { spark(0.5 + Math.random() * 0.5); sparkTimer = 0.05 + Math.random() * 0.12; }
    } else if (lastShort !== 0) {
      shortGain.gain.setTargetAtTime(0, t, 0.05);
      shortNoiseGain.gain.setTargetAtTime(0, t, 0.05);
      lastShort = 0;
      sparkTimer = 0;
    }
  }

  return {
    resume: resume, tick: tick, click: click, bellStrike: bellStrike, spark: spark, pop: pop, place: place,
    setEnabled: setEnabled, isEnabled: isEnabled,
    debug: function () { return { unlocked: unlocked, enabled: enabled, ready: ready, hasCtx: !!ac }; }
  };
})();

/* =======================================================================
   二、界面与交互
   ======================================================================= */
(function () {
  if (typeof document === 'undefined') return;   // 便于在 Node 中单测求解器

  /* ---------- 元件定义 ---------- */
  const VW = 1000, VH = 620;                      // 逻辑画布尺寸(仅作空内容时的默认包围盒)
  const DEFS = {
    battery:   { label: '电池',       w: 100, h: 58, terminals: [{ x: -48, y: 0 }, { x: 48, y: 0 }] },
    switch:    { label: '开关',       w: 100, h: 50, terminals: [{ x: -48, y: 0 }, { x: 48, y: 0 }] },
    bulb:      { label: '小灯泡',     w: 78,  h: 78, terminals: [{ x: -38, y: 0 }, { x: 38, y: 0 }] },
    resistor:  { label: '定值电阻',   w: 100, h: 46, terminals: [{ x: -48, y: 0 }, { x: 48, y: 0 }] },
    conductor: { label: '导体',       w: 132, h: 60, terminals: [{ x: -58, y: 0 }, { x: 58, y: 0 }] },
    rheostat:  { label: '滑动变阻器', w: 124, h: 56, terminals: [{ x: -56, y: 0 }, { x: 56, y: 0 }] },
    ammeter:   { label: '电流表',     w: 78,  h: 78, terminals: [{ x: -38, y: 0 }, { x: 38, y: 0 }] },
    voltmeter: { label: '电压表',     w: 78,  h: 78, terminals: [{ x: -38, y: 0 }, { x: 38, y: 0 }] },
    motor:     { label: '电动机',     w: 88,  h: 88, terminals: [{ x: -44, y: 0 }, { x: 44, y: 0 }] },
    led:       { label: '发光二极管', w: 92,  h: 62, terminals: [{ x: -46, y: 0 }, { x: 46, y: 0 }] },
    bell:      { label: '电铃',       w: 88,  h: 88, terminals: [{ x: -44, y: 0 }, { x: 44, y: 0 }] },
    fuse:      { label: '保险丝',     w: 96,  h: 46, terminals: [{ x: -48, y: 0 }, { x: 48, y: 0 }] },
    junction:  { label: '接线点',     w: 26,  h: 26, terminals: [{ x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 }] }
  };
  const PALETTE = [
    { type: 'battery',   glyph: '⎓', name: '电池' },
    { type: 'switch',    glyph: '⇄', name: '开关' },
    { type: 'bulb',      glyph: '☀', name: '小灯泡' },
    { type: 'resistor',  glyph: '▭', name: '电阻' },
    { type: 'conductor', glyph: '▤', name: '导体' },
    { type: 'rheostat',  glyph: '⇥', name: '变阻器' },
    { type: 'ammeter',   glyph: 'A', name: '电流表' },
    { type: 'voltmeter', glyph: 'V', name: '电压表' },
    { type: 'motor',     glyph: 'M', name: '电动机' },
    { type: 'led',       glyph: '⊳', name: '发光二极管' },
    { type: 'bell',      glyph: '♪', name: '电铃' },
    { type: 'fuse',      glyph: '⏛', name: '保险丝' },
    { type: 'junction',  glyph: '•', name: '接线点' }
  ];
  /* 不同材料的电阻率 ρ(单位 Ω·mm²/m,20℃ 附近的常用教学值)与显示颜色
     教材图 16.3-5 的导电性能顺序:银 > 铜 > 金 > 铝 > 铁 > 炭笔 > 盐水 > … > 半导体 > 绝缘体 */
  const MATERIALS = [
    { id: 'silver',    name: '银',        rho: 0.016, color: '#b8c4d0', kind: '金属' },
    { id: 'copper',    name: '铜',        rho: 0.017, color: '#c9702a', kind: '金属' },
    { id: 'gold',      name: '金',        rho: 0.024, color: '#c9a227', kind: '金属' },
    { id: 'aluminium', name: '铝',        rho: 0.029, color: '#9aa7b5', kind: '金属' },
    { id: 'iron',      name: '铁',        rho: 0.10,  color: '#6b7280', kind: '金属' },
    { id: 'nichrome',  name: '镍铬合金',  rho: 1.1,   color: '#8a8f98', kind: '合金' },
    { id: 'graphite',  name: '铅笔芯',    rho: 10,    color: '#3f3f46', kind: '非金属' },
    { id: 'saltwater', name: '盐水',      rho: 500,   color: '#3b82f6', kind: '溶液' },
    { id: 'wetwood',   name: '湿木',      rho: 1e4,   color: '#a16207', kind: '非金属' },
    { id: 'silicon',   name: '硅',        rho: 5e7,   color: '#64748b', kind: '半导体' },
    { id: 'drywood',   name: '干木',      rho: 1e9,   color: '#b08968', kind: '非金属' },
    { id: 'glass',     name: '玻璃',      rho: 1e12,  color: '#9fd3e8', kind: '绝缘体' },
    { id: 'rubber',    name: '橡胶',      rho: 1e15,  color: '#4b5563', kind: '绝缘体' }
  ];
  function materialOf(c) {
    for (let i = 0; i < MATERIALS.length; i++) if (MATERIALS[i].id === c.props.material) return MATERIALS[i];
    return MATERIALS[5];
  }
  // 导体电阻 R = ρ·L/S(ρ: Ω·mm²/m,L: m,S: mm²),限幅避免数值极端
  function resistanceOf(c) {
    const m = materialOf(c);
    const L = Math.max(0.01, Number(c.props.L) || 0.01);
    const S = Math.max(0.005, Number(c.props.S) || 0.005);
    return Math.min(1e9, Math.max(1e-6, m.rho * L / S));
  }

  // 画布配色(亮色 / 暗色两套,切换主题时整体替换)
  const THEMES = {
    light: {
      canvasBg: '#fbfdff', grid: '#e6edf8', gridBold: '#dbe5f4',
      wire: '#39558a', comp: '#1f3864', label: '#7b8db0',
      term: '#2d6fae', termHot: '#ff9d2e', current: '#ff9d2e',
      text: '#12294d', textSoft: '#465a7a', textFaint: '#5b6b86',
      fill: '#eef4ff', fillWarm: '#fffdf3', fillBell: '#fff6d8',
      white: '#ffffff', ring: '#ffffff',
      ok: '#12734f', warn: '#c9701a', danger: '#c02a2a', soft: '#8b9cb8'
    },
    dark: {
      canvasBg: '#0b1420', grid: '#152437', gridBold: '#1d3350',
      wire: '#7ba3d6', comp: '#d3e3f7', label: '#8ea6c4',
      term: '#5fa8e8', termHot: '#ff9d2e', current: '#ffa93f',
      text: '#eaf2fd', textSoft: '#b3c7de', textFaint: '#93a9c6',
      fill: '#16283e', fillWarm: '#2b2415', fillBell: '#332a14',
      white: '#101f31', ring: '#0b1420',
      ok: '#5fd3a3', warn: '#ffb457', danger: '#ff8080', soft: '#6f86a3'
    }
  };
  const COL = Object.assign({}, THEMES.light);

  /* ---------- 状态 ---------- */
  const state = {
    components: [],
    wires: [],
    selected: null,          // 主选中项:{kind:'component'|'wire'|'multi', id / index}
    selectedIds: [],         // 多选中的元件 id 列表(批量拖动/删除/旋转用)
    spaceDown: false,        // 按住空格时拖动 = 平移画面
    drag: null,
    pendingTerm: null,       // 保留字段(点击连线已移除,恒为 null)
    wireMode: null,          // 接线模式:{ from:{cid,ti} } —— 长按进入,松手后仍然有效,点另一端即可连上
    hoverTerm: null,
    mouse: { x: 0, y: 0 },
    dirty: true,
    solved: null,
    idSeq: 0,
    notes: [],               // 画布注解(半透明说明框:{id,x,y,w,text})
    annotate: false,         // 注解模式:点画布新增注解
    noteDrag: null,          // 正在拖动的注解
    tapTerm: null,           // 仅记录"按下的端点"(点击连线已移除;松手即清空,不触发任何连线)
    learnPick: null,         // 操作学习:本步要点名的元件(画布上一直高亮)
    sparks: [],              // 短路火花粒子
    events: [],              // 待播放的音效/特效事件
    lastStatus: 'open',
    mm: { w: 176, h: 112, hidden: false }   // 右下角缩略图尺寸与显隐
  };

  /* 指针是否已经"离开/抬起"。用于两段式连线:
     手指抬起后 state.mouse 还留着旧坐标,若照着它画虚线预览,
     画布上就会出现一条指向空处的橙色虚线(用户看到的就是这个)。 */
  let mouseStale = true;

  const canvas = document.getElementById('cv');
  const ctx = canvas.getContext('2d');
  const wrap = document.getElementById('wrap');
  const view = { scale: 1, baseScale: 1, zoom: 1, tx: 0, ty: 0, dpr: 1, rot: 0, theme: 'light' };
  let exportMode = false;   // 导出图片期间为 true:跳过选中框/框选/缩略图等界面元素

  /* ---------- 工具 ---------- */
  const key = (cid, ti) => cid + ':' + ti;
  const compById = id => state.components.find(c => c.id === id);
  const normRot = c => normDeg(c.rot || 0);                   // 元件旋转角:0/90/180/270
  const normDeg = d => ((((Number(d) || 0) % 360) + 360) % 360);   // 角度归一化到 0~359
  function termPos(c, i) {
    const t = DEFS[c.type].terminals[i];
    const r = normRot(c);
    if (r === 90) return { x: c.x - t.y, y: c.y + t.x };
    if (r === 180) return { x: c.x - t.x, y: c.y - t.y };
    if (r === 270) return { x: c.x + t.y, y: c.y - t.x };
    return { x: c.x + t.x, y: c.y + t.y };
  }
  function bounds(c) {
    const d = DEFS[c.type];
    const r = normRot(c);
    const vertical = (r === 90 || r === 270);
    const w = vertical ? d.h : d.w;
    const h = vertical ? d.w : d.h;
    return { x: c.x - w / 2, y: c.y - h / 2, w: w, h: h };
  }
  const fmt = (v, n) => {
    const a = Math.abs(v);
    if (a < 1e-3) return '0';
    if (a >= 1000) return v.toFixed(0);
    return v.toFixed(n === undefined ? (a < 1 ? 3 : 2) : n);
  };
  /* ---------- 多选辅助 ---------- */
  function isSelected(cid) { return state.selectedIds.indexOf(cid) >= 0; }
  function selSummary() {
    if (state.selectedIds.length === 0) return null;
    if (state.selectedIds.length === 1) return { kind: 'component', id: state.selectedIds[0] };
    return { kind: 'multi' };
  }
  function applySelection(ids) {
    state.selectedIds = ids.slice();
    state.selected = selSummary();
  }
  function clearSelection() { state.selectedIds = []; state.selected = null; }
  // 取消"点一下就开始连线"的待连接状态
  function clearPendingTerm() { state.pendingTerm = null; state.dirty = true; }
  let layoutMode = 'desktop';        // 'desktop' | 'mobile',由识别或用户切换决定
  function selectedComponents() {
    return state.selectedIds.map(id => compById(id)).filter(Boolean);
  }
  function selectAllComponents() {
    applySelection(state.components.map(c => c.id));
    renderInspector();
  }
  // 电阻显示:绝缘体电阻极大,用科学计数法更易读(如 1.0×10⁹ Ω)
  const SUP = { '0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹', '-': '⁻' };
  function sup(n) { return String(n).split('').map(ch => SUP[ch] || ch).join(''); }
  function fmtOhm(R) {
    if (!isFinite(R)) return '∞ Ω';
    if (R >= 1e6) {
      const e = R.toExponential(1).split('e');
      return e[0] + '×10' + sup(Number(e[1])) + ' Ω';
    }
    return fmt(R, R < 1 ? 3 : 2) + ' Ω';
  }
  function dist2Seg(px, py, x1, y1, x2, y2) {
    const dx = x2 - x1, dy = y2 - y1;
    const L2 = dx * dx + dy * dy;
    let t = L2 ? ((px - x1) * dx + (py - y1) * dy) / L2 : 0;
    t = Math.max(0, Math.min(1, t));
    const qx = x1 + t * dx, qy = y1 + t * dy;
    return Math.hypot(px - qx, py - qy);
  }

  /* ---------- 新建元件 / 预设电路 ---------- */
  function makeComp(type, x, y) {
    const c = { id: 'c' + (++state.idSeq), type: type, x: x, y: y, rot: 0, props: {} };
    if (type === 'battery') c.props = { V: 3, r: 0.5 };
    if (type === 'bulb') c.props = { R: 10, rated: 1.0 };
    if (type === 'resistor') c.props = { R: 20 };
    if (type === 'conductor') c.props = { material: 'nichrome', L: 1, S: 0.1 };
    if (type === 'rheostat') c.props = { R: 20, max: 50 };
    if (type === 'motor') c.props = { R: 15 };
    if (type === 'led') c.props = { Vf: 1.8, R: 30 };
    if (type === 'bell') c.props = { R: 12 };
    if (type === 'fuse') c.props = { Imax: 0.5 };
    if (type === 'switch') c.props = { closed: false };
    return c;
  }
  /* —— 关卡器材篮子(v2.0):关卡模式下"只能用给定器材"——
     添加元件与复制元件共用 basketRoom 判定;删除自动腾出名额;
     接线点(junction)是接线工具不是器材,不限量。 —— */
  function levelGearItem(type) {
    if (!state.level) return null;
    try {
      const lv = examLevelById(state.level.id);
      if (!lv) return null;
      return (lv.level.gear || []).find(g => g.type === type) || null;
    } catch (e) { return null; }
  }
  function basketRoom(type) {
    const gi = levelGearItem(type);
    if (!gi || gi.free) return true;
    const placed = state.components.filter(c => c.type === type).length;
    return placed < gi.n;
  }
  function addComp(type, x, y) {
    if (state.pendingTerm) { state.pendingTerm = null; state.dirty = true; }   // 添加元件时取消未完成的连线
    if (!basketRoom(type)) {
      const def = DEFS[type];
      showToast('本关「' + ((def && def.label) || '元件') + '」已用完,放不下了(见题面器材)');
      return null;
    }
    pushUndo('添加' + ((DEFS[type] && DEFS[type].label) || '元件'));
    const c = makeComp(type, x, y);
    state.components.push(c);
    state.selected = { kind: 'component', id: c.id };
    state.selectedIds = [c.id];
    state.dirty = true;
    // 放置反馈:声音 + 气泡 + 画布上闪烁一下;如果跑到视野外就顺手挪进来
    Sound.place();
    const label = (DEFS[type] && DEFS[type].label) || '元件';
    const now = Date.now();
    if (!state.addStreak || now - state.addStreak.t > 4000) state.addStreak = { n: 0, t: now };
    state.addStreak.n++;
    state.addStreak.t = now;
    showToast('已添加:' + label + (state.addStreak.n > 1 ? '(本次共 ' + state.addStreak.n + ' 个)' : ''));
    state.flash = { id: c.id, t: 0 };
    ensureVisible(c);
    if (typeof refreshPalette === 'function') refreshPalette();
    // 注意:抽屉保持打开,方便连续添加多个元件;新元件会被放进"没被抽屉遮住"的区域
    renderInspector();
    return c;
  }
  // 手机端底部抽屉打开时,画布下半部分被遮住 → 返回"真正看得见"的那块高度
  function unobstructedCanvasHeight() {
    const full = canvas.clientHeight || 480;
    if (layoutMode !== 'mobile' || !sheetOpenKind) return full;
    const sheet = document.getElementById('mSheet');
    if (!sheet || !sheet.getBoundingClientRect) return full;
    const r = sheet.getBoundingClientRect();
    const sh = r.height || sheet.offsetHeight || 0;
    if (sh <= 0) return full;
    // 抽屉吸在屏幕底部:收起时 rect.top 是被 translateY 推出去的假值,必须按高度倒推
    const sheetTop = (window.innerHeight || 0) - sh;
    const ct = canvas.getBoundingClientRect().top;
    if (!(sheetTop > ct)) return full;
    return Math.max(120, sheetTop - ct - 16);    // 抽屉上沿以上的区域
  }
  // 让某个元件出现在"看得见"的范围内(不在就平移到它)
  function ensureVisible(c) {
    const b = bounds(c);
    const w = canvas.clientWidth || 800;
    const h = unobstructedCanvasHeight();        // 抽屉打开时只用没被遮住的上半部分
    // 用"未被遮挡区域"换算成世界坐标,判断元件是否已经看得见
    const x0 = (0 - view.tx) / view.scale, x1 = (w - view.tx) / view.scale;
    const y0 = (0 - view.ty) / view.scale, y1 = (h - view.ty) / view.scale;
    const pad = 40;
    if (b.x > x0 + pad && b.x + b.w < x1 - pad && b.y > y0 + pad && b.y + b.h < y1 - pad) return;
    const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
    view.tx = w / 2 - cx * view.scale;
    view.ty = h / 2 - cy * view.scale;           // 居中到"看得见"的那块区域
  }
  // 顶部小气泡提示(1.6 秒后自动消失)
  let toastTimer = 0;
  function showToast(text) {
    let el = document.getElementById('toast');
    if (!el) {
      el = document.createElement('div');
      el.id = 'toast';
      el.className = 'toast';
      if (document.body && document.body.appendChild) document.body.appendChild(el);
    }
    el.textContent = text;
    setElClass(el, 'on', true);
    if (toastTimer) clearTimeout(toastTimer);
    toastTimer = setTimeout(() => setElClass(el, 'on', false), 1600);
  }
  function addWire(cidA, tiA, cidB, tiB) {
    if (cidA === cidB && tiA === tiB) return;
    const dup = state.wires.some(w =>
      (w.a.cid === cidA && w.a.ti === tiA && w.b.cid === cidB && w.b.ti === tiB) ||
      (w.a.cid === cidB && w.a.ti === tiB && w.b.cid === cidA && w.b.ti === tiA));
    if (dup) return;
    pushUndo('连接导线');
    state.wires.push({ a: { cid: cidA, ti: tiA }, b: { cid: cidB, ti: tiB } });
    state.dirty = true;
  }

  const PRESETS = {
    basic: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 140), makeComp('switch', 200, 140), j(300, 140), makeComp('bulb', 420, 140), j(540, 140),
        j(120, 440), makeComp('battery', 320, 440), j(540, 440)
      ];
      const ids = comps.map(c => c.id);
      const wires = [
        [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 3], [ids[2], 1, ids[3], 0],
        [ids[3], 1, ids[4], 3], [ids[4], 2, ids[7], 0], [ids[7], 3, ids[6], 1],
        [ids[6], 0, ids[5], 1], [ids[5], 2, ids[0], 2]
      ];
      return { comps: comps, wires: wires };
    },
    /* 内部预设(不进演示菜单):单灯回路 —— 章 0「拖动元件」关的起点 */
    lamp: function () {
      const b = makeComp('battery', 320, 440);
      const l = makeComp('bulb', 320, 160);
      return { comps: [b, l], wires: [[b.id, 1, l.id, 0], [l.id, 1, b.id, 0]] };
    },
    series: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 140), makeComp('bulb', 220, 140), j(320, 140), makeComp('bulb', 440, 140), j(540, 140),
        j(120, 440), makeComp('battery', 320, 440), j(540, 440)
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 3], [ids[2], 1, ids[3], 0],
          [ids[3], 1, ids[4], 3], [ids[4], 2, ids[7], 0], [ids[7], 3, ids[6], 1],
          [ids[6], 0, ids[5], 1], [ids[5], 2, ids[0], 2]
        ]
      };
    },
    parallel: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 120), makeComp('bulb', 320, 120), j(520, 120),
        j(120, 280), makeComp('bulb', 320, 280), j(520, 280),
        j(120, 420), makeComp('battery', 320, 420), j(520, 420)
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 3],
          [ids[3], 1, ids[4], 0], [ids[4], 1, ids[5], 3],
          [ids[0], 2, ids[3], 0], [ids[3], 2, ids[6], 0],
          [ids[2], 2, ids[5], 0], [ids[5], 2, ids[8], 0],
          [ids[6], 1, ids[7], 0], [ids[7], 1, ids[8], 3]
        ]
      };
    },
    meter: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 120), makeComp('resistor', 220, 120), j(340, 120), makeComp('ammeter', 460, 120), j(560, 120),
        makeComp('voltmeter', 220, 260),
        j(120, 420), makeComp('battery', 340, 420), j(560, 420)
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          // 电表接法:电流表串在主干上、电压表并在电阻两端;+ 柱(端子 1)朝高电位侧。
          // 注意导线要"左接左、右接右",不要交叉(交叉会打结,看着像接错了)
          [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 3], [ids[2], 1, ids[3], 0], [ids[3], 1, ids[4], 3],
          [ids[5], 0, ids[1], 0], [ids[5], 1, ids[1], 1],
          [ids[4], 2, ids[8], 0], [ids[8], 3, ids[7], 1], [ids[7], 0, ids[6], 1], [ids[6], 2, ids[0], 2]
        ]
      };
    },
    short: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 120), makeComp('bulb', 320, 120), j(520, 120),
        j(120, 400), makeComp('battery', 320, 400), j(520, 400),
        j(220, 400), j(400, 400), j(220, 500), j(400, 500)
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 3],
          [ids[2], 2, ids[5], 0], [ids[5], 3, ids[7], 1],
          [ids[7], 3, ids[4], 1], [ids[4], 0, ids[6], 1],
          [ids[6], 3, ids[3], 1], [ids[3], 2, ids[0], 2],
          /* 短路导线:直接跨接电源两端 */
          [ids[6], 2, ids[8], 0], [ids[8], 1, ids[9], 3], [ids[9], 0, ids[7], 2]
        ]
      };
    },

    /* 实验一:不同导体的对比(教材 16.3 图 16.3-5 的导电性能)
       四条并联支路:材料不同、长度和粗细完全相同,各自串一只相同的小灯泡,
       灯泡越亮、电流越大 → 该材料导电性能越强 */
    /* 用电器被短路(局部短路)——中考高频易错点 */
    shortBulb: function () {
      const j = (x, y) => makeComp('junction', x, y);
      // 两个灯泡串联:L1(左,将被短路,不亮)→ J_mid → L2(右,照常发光)
      // 另在 L1 两端引出两个接线点,用一条导线直接连通 → L1 两端电压为 0
      const comps = [
        j(120, 120),            // 0 左上
        makeComp('bulb', 320, 120),   // 1 L1(被短路)
        j(520, 120),            // 2 中间
        makeComp('bulb', 720, 120),   // 3 L2(正常发光)
        j(920, 120),            // 4 右上
        j(120, 460),            // 5 左下
        makeComp('battery', 560, 460),// 6 电源
        j(920, 460),            // 7 右下
        j(280, 120),            // 8  L1 左端子抽头(落在 20 格线上;与端子差 2px,肉眼看不出)
        j(360, 120),            // 9  L1 右端子抽头
        j(280, 300),            // 10 短路导线左下
        j(360, 300)             // 11 短路导线右下
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          /* 主回路:电源 − → 左上 → L1 → 中间 → L2 → 右上 → 右下 → 电源 + */
          [ids[5], 2, ids[0], 2],
          [ids[0], 1, ids[8], 0], [ids[8], 0, ids[1], 0],      // 左上 → 抽头 → L1 左端
          [ids[1], 1, ids[9], 0], [ids[9], 0, ids[2], 3],      // L1 右端 → 抽头 → 中间
          [ids[2], 0, ids[3], 0],                              // 中间 → L2 左端
          [ids[3], 1, ids[4], 3],                              // L2 右端 → 右上
          [ids[4], 2, ids[7], 0],                              // 右上 → 右下
          [ids[7], 3, ids[6], 1],                              // 右下 → 电源 +
          [ids[6], 0, ids[5], 1],                              // 电源 − → 左下
          /* 短路导线:把 L1 两端直接连通(这才是"用电器短路") */
          [ids[8], 0, ids[10], 0], [ids[10], 0, ids[11], 0], [ids[11], 0, ids[9], 0]
        ],
        notes: [
          { id: 'ns1', x: 500, y: 190, w: 320, text: '【用电器短路】一条导线把左边灯泡的两端直接连通\n电流几乎全部走导线 → 这个灯泡不亮\n电源没有被短路,不属于危险操作' },
          { id: 'ns2', x: 120, y: 520, w: 420, text: '考点:局部短路后,被短路的用电器两端电压为 0、电流为 0、不工作;\n其余用电器照常工作。中考常考"哪个灯亮、哪个灯灭"。' }
        ]
      };
    },
    /* 伏安法测电阻(教材经典实验):滑动变阻器调电流,电流表读 I、电压表读 U,R = U / I */
    ohmLaw: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 240),                        // 0  左上
        makeComp('rheostat', 380, 240),     // 1  滑动变阻器(改变电流)
        j(680, 240),                        // 2  Rx 左侧抽头
        makeComp('resistor', 800, 240),     // 3  待测电阻 Rx
        j(920, 240),                        // 4  Rx 右侧抽头
        j(1080, 240),                       // 5  右上
        j(1080, 640),                       // 6  右下
        makeComp('ammeter', 920, 640),      // 7  电流表(串联)
        j(800, 640),                        // 8
        makeComp('battery', 620, 640),      // 9  电源
        j(440, 640),                        // 10
        makeComp('switch', 300, 640),       // 11 开关
        j(120, 640),                        // 12 左下
        j(680, 380),                        // 13 电压表左侧抽头
        makeComp('voltmeter', 800, 380),    // 14 电压表(并联在 Rx 两端)
        j(920, 380)                         // 15 电压表右侧抽头
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          /* 主回路(全部串联):电源 − → 开关 → 左下 → 左上 → 变阻器 → Rx → 右上 → 右下 → 电流表 → 电源 + */
          [ids[12], 0, ids[0], 0],
          [ids[0], 1, ids[1], 0],
          [ids[1], 1, ids[2], 0], [ids[2], 0, ids[3], 0],
          [ids[3], 1, ids[4], 0], [ids[4], 0, ids[5], 3],
          [ids[5], 2, ids[6], 0],
          [ids[6], 3, ids[7], 0], [ids[7], 1, ids[8], 0],        // A:电流从 + 柱(ti1)流出为正常
          [ids[8], 0, ids[9], 1], [ids[9], 0, ids[10], 0],
          [ids[10], 0, ids[11], 1], [ids[11], 0, ids[12], 0],
          /* 电压表并联在 Rx 两端:左接左、右接右(不打结),且 + 柱(ti1)朝高电位 → 读数取正 */
          [ids[2], 0, ids[13], 0], [ids[13], 0, ids[14], 0],
          [ids[14], 1, ids[15], 0], [ids[15], 0, ids[4], 0]
        ],
        notes: [
          { id: 'no1', x: 120, y: 380, w: 420, text: '【伏安法测电阻】\n电流表串联读 I,电压表并联在 Rx 两端读 U\n算出 R = U / I,与 Rx 的标称值比较' },
          { id: 'no2', x: 620, y: 760, w: 460, text: '拖动变阻器改变接入电阻 → I 与 U 同时改变,但 U / I 基本不变(这就是"电阻是导体本身的性质")\n!!注意:电流表要串联、电压表要并联,接线时开关必须断开' }
        ]
      };
    },
    /* 保险丝保护:电流超过保险丝额定值就熔断,起到保护作用 */
    fuse: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 200),                        // 0 左上
        Object.assign(makeComp('fuse', 300, 200), { props: { Imax: 0.4 } }),   // 1 保险丝(额定 0.4 A)
        j(460, 200),                        // 2
        makeComp('bulb', 640, 200),         // 3 小灯泡
        j(820, 200),                        // 4 右上
        j(820, 520),                        // 5 右下
        j(120, 520),                        // 6 左下
        makeComp('battery', 300, 520),      // 7 电源 3 V
        j(460, 520),                        // 8
        Object.assign(makeComp('switch', 640, 520), { props: { closed: true } })   // 9 开关(默认闭合,便于直接看效果)
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 0], [ids[2], 0, ids[3], 0],
          [ids[3], 1, ids[4], 0], [ids[4], 2, ids[5], 0], [ids[5], 3, ids[9], 1],
          [ids[9], 0, ids[8], 0], [ids[8], 0, ids[7], 1], [ids[7], 0, ids[6], 0],
          [ids[6], 1, ids[0], 0]
        ],
        notes: [
          { id: 'fz1', x: 120, y: 300, w: 320, text: '【保险丝保护】\n保险丝串联在干路上,额定 0.4 A\n正常时 I≈0.29 A,灯正常发光' },
          { id: 'fz2', x: 460, y: 300, w: 320, text: '把电压调到 6 V → I 超过 0.4 A\n!!保险丝"啪"地熔断 → 电路断路\n灯熄灭(这就是保险丝的保护作用)' }
        ]
      };
    },
    /* 滑动变阻器:限流接法,滑片改变电阻 → 电流与灯泡亮度随之变化 */
    rheostatControl: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const comps = [
        j(120, 140), makeComp('rheostat', 300, 140), j(480, 140), makeComp('bulb', 640, 140), j(800, 140),
        j(120, 460), makeComp('battery', 460, 460), j(800, 460)
      ];
      const ids = comps.map(c => c.id);
      return {
        comps: comps,
        wires: [
          [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 3], [ids[2], 1, ids[3], 0], [ids[3], 1, ids[4], 3],
          [ids[4], 2, ids[7], 0], [ids[7], 3, ids[6], 1], [ids[6], 0, ids[5], 1], [ids[5], 2, ids[0], 2]
        ],
        notes: [
          { id: 'nr1', x: 520, y: 300, w: 320, text: '【滑动变阻器·限流接法】\n选中变阻器,在"参数"里拖动滑片改变接入电阻:\n电阻变大 → 电流变小 → 灯泡变暗' },
          { id: 'nr2', x: 120, y: 560, w: 430, text: '考点:串联电路中 R 总 = R 滑 + R 灯,I = U / R 总。\n移动滑片时先判断电阻增减,再用欧姆定律推电流、电压分配。' }
        ]
      };
    },
    compareMaterials: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const busL = 100, busR = 520;
      const rows = [120, 220, 340, 440];
      const mats = ['copper', 'iron', 'nichrome', 'graphite'];
      const comps = [];
      const L = [], R = [], CD = [], BL = [];
      rows.forEach(function (y, i) {
        const jl = j(busL, y), jr = j(busR, y);
        const cd = makeComp('conductor', 230, y);
        cd.props = { material: mats[i], L: 1, S: 0.02 };
        const bl = makeComp('bulb', 400, y);
        comps.push(jl, cd, bl, jr);
        L.push(jl); CD.push(cd); BL.push(bl); R.push(jr);
      });
      const bl0 = j(busL, 560), br0 = j(busR, 560);
      const bat = makeComp('battery', 300, 560);
      comps.push(bl0, bat, br0);
      const wires = [];
      for (let i = 0; i < rows.length; i++) {
        wires.push([L[i].id, 1, CD[i].id, 0]);
        wires.push([CD[i].id, 1, BL[i].id, 0]);
        wires.push([BL[i].id, 1, R[i].id, 3]);
      }
      for (let i = 0; i < rows.length - 1; i++) {
        wires.push([L[i].id, 2, L[i + 1].id, 0]);      // 左侧竖线
        wires.push([R[i].id, 2, R[i + 1].id, 0]);      // 右侧竖线
      }
      wires.push([L[rows.length - 1].id, 2, bl0.id, 0]);
      wires.push([R[rows.length - 1].id, 2, br0.id, 0]);
      wires.push([bl0.id, 1, bat.id, 0]);
      wires.push([bat.id, 1, br0.id, 3]);
      return { comps: comps, wires: wires };
    },

    /* 实验二:同种材料(镍铬合金),研究电阻与长度、横截面积的关系 */
    compareSizes: function () {
      const j = (x, y) => makeComp('junction', x, y);
      const busL = 100, busR = 520;
      const rows = [120, 280, 440];
      const specs = [
        { L: 0.5, S: 0.02 },     // 甲:较短
        { L: 1.0, S: 0.02 },     // 乙:长度加倍 → 电阻加倍、电流减半
        { L: 1.0, S: 0.04 }      // 丙:横截面积加倍 → 电阻减半
      ];
      const comps = [];
      const LJ = [], RJ = [], CD = [], BL = [];
      rows.forEach(function (y, i) {
        const jl = j(busL, y), jr = j(busR, y);
        const cd = makeComp('conductor', 230, y);
        cd.props = { material: 'nichrome', L: specs[i].L, S: specs[i].S };
        const bl = makeComp('bulb', 400, y);
        comps.push(jl, cd, bl, jr);
        LJ.push(jl); CD.push(cd); BL.push(bl); RJ.push(jr);
      });
      const bl0 = j(busL, 580), br0 = j(busR, 580);
      const bat = makeComp('battery', 300, 580);
      comps.push(bl0, bat, br0);
      const wires = [];
      for (let i = 0; i < rows.length; i++) {
        wires.push([LJ[i].id, 1, CD[i].id, 0]);
        wires.push([CD[i].id, 1, BL[i].id, 0]);
        wires.push([BL[i].id, 1, RJ[i].id, 3]);
      }
      for (let i = 0; i < rows.length - 1; i++) {
        wires.push([LJ[i].id, 2, LJ[i + 1].id, 0]);
        wires.push([RJ[i].id, 2, RJ[i + 1].id, 0]);
      }
      wires.push([LJ[rows.length - 1].id, 2, bl0.id, 0]);
      wires.push([RJ[rows.length - 1].id, 2, br0.id, 0]);
      wires.push([bl0.id, 1, bat.id, 0]);
      wires.push([bat.id, 1, br0.id, 3]);
      return { comps: comps, wires: wires };
    }
  };

  // 把一组元件朝它们的中心收拢(k<1 变小):整体等比,横平竖直的导线不会歪
  function compactComponents(list, k) {
    if (!list || !list.length || k === 1) return null;
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    list.forEach(c => {
      const b = bounds(c);
      x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y);
      x1 = Math.max(x1, b.x + b.w); y1 = Math.max(y1, b.y + b.h);
    });
    const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;
    list.forEach(c => {
      c.x = Math.round((cx + (c.x - cx) * k) / 20) * 20;
      c.y = Math.round((cy + (c.y - cy) * k) / 20) * 20;
    });
    return { cx: cx, cy: cy };
  }
  // 元件之间是否有实际重叠(留 4px 容差)
  function overlapCount(list) {
    let cnt = 0;
    // 端子/元件的点击判定范围比外框大(触摸时最大外扩 36px),所以判定重叠时要加上安全边距,
    // 否则两个元件贴太近会互相抢点击(点 LED 选到别的元件、连线连到隔壁端子)。
    const PAD = 28;
    const inflate = function (r) { return { x: r.x - PAD, y: r.y - PAD, w: r.w + PAD * 2, h: r.h + PAD * 2 }; };
    for (let i = 0; i < list.length; i++) {
      const a = inflate(bounds(list[i]));
      for (let j = i + 1; j < list.length; j++) {
        const b = inflate(bounds(list[j]));
        const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
        const oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
        if (ox > 4 && oy > 4) cnt++;
      }
    }
    return cnt;
  }
  // 自动挑一个"能收多紧就收多紧、但不重叠"的比例
  function autoCompact(list) {
    if (!list || list.length < 2) return null;
    const orig = list.map(function (c) { return { x: c.x, y: c.y }; });
    const restore = function () { list.forEach(function (c, i) { c.x = orig[i].x; c.y = orig[i].y; }); };
    if (overlapCount(list) > 0) return null;              // 原始布局就有重叠 → 不动
    let best = null;
    for (let k = 0.75; k < 0.999; k += 0.03) {
      restore();
      const ctr = compactComponents(list, k);
      if (!ctr) break;
      if (overlapCount(list) === 0) { best = { k: k, cx: ctr.cx, cy: ctr.cy }; break; }   // 第一个不重叠的 = 能收的最紧比例
      // 还重叠就继续试更大的比例
    }
    if (!best) { restore(); return null; }
    restore();
    compactComponents(list, best.k);                       // 定稿
    return best;
  }
  /* 内部预设:两灯串联 + 开关并在灯1两端(用电器短路关卡的预置电路,不进演示菜单)。
     开关断开 = 两灯串联都亮;闭合 = L1 被短路(不亮)、L2 分得全部电压更亮。 */
  PRESETS.seriesShort = function () {
    const j = (x, y) => makeComp('junction', x, y);
    const comps = [
      j(120, 140), makeComp('bulb', 220, 140), j(320, 140), makeComp('bulb', 440, 140), j(540, 140),
      j(120, 440), makeComp('battery', 320, 440), j(540, 440),
      makeComp('switch', 220, 300)               // 并在 L1 两端(初始断开)
    ];
    const ids = comps.map(c => c.id);
    return {
      comps: comps,
      wires: [
        [ids[0], 1, ids[1], 0], [ids[1], 1, ids[2], 3], [ids[2], 1, ids[3], 0],
        [ids[3], 1, ids[4], 3], [ids[4], 2, ids[7], 0], [ids[7], 3, ids[6], 1],
        [ids[6], 0, ids[5], 1], [ids[5], 2, ids[0], 2],
        [ids[8], 0, ids[0], 2], [ids[8], 1, ids[2], 2]   // 开关跨接 L1 两端
      ]
    };
  };

  function loadPreset(name) {
    if (state.pendingTerm) { state.pendingTerm = null; state.dirty = true; }   // 清掉未完成的连线
    pushUndo('载入预设');
    // 预设内部的连线不各记一条历史,整次载入只算一步
    const spec = withoutHistory(() => (PRESETS[name] ? PRESETS[name]() : null));
    state.components = []; state.wires = []; state.selected = null; state.drag = null;
    state.notes = (spec && spec.notes) ? JSON.parse(JSON.stringify(spec.notes)) : [];
    state.learnPresetLoaded = true;
    if (!spec) { state.dirty = true; renderInspector(); return; }
    state.components = spec.comps;
    // 元件别铺得太开:自动收拢到"不重叠的前提下最紧"(注解跟着一起收)
    const ctr = autoCompact(state.components);
    if (ctr && ctr.k < 1 && state.notes) {
      state.notes.forEach(nt => {
        nt.x = Math.round((ctr.cx + (nt.x - ctr.cx) * ctr.k) / 20) * 20;
        nt.y = Math.round((ctr.cy + (nt.y - ctr.cy) * ctr.k) / 20) * 20;
      });
    }
    // idSeq 只能单调递增:预设元件已经分配过更大的编号,若在此处改小会导致新元件 ID 重复
    state.idSeq = Math.max(state.idSeq, state.components.length + 10);
    withoutHistory(() => { spec.wires.forEach(w => addWire(w[0], w[1], w[2], w[3])); });
    state.dirty = true;
    renderInspector();
    if (typeof fitView === 'function') fitView();     // 载入预设后自动缩放居中
    // 清掉可能残留的学习高亮;若正在学习,则按当前步骤重新贴一遍
    try {
      document.querySelectorAll('.learn-hl').forEach(el => setElClass(el, 'learn-hl', false));
      if (learnOn) learnHighlight();
    } catch (e) { }
  }

  /* ---------- 组装求解输入 ---------- */
  function buildInput(ledState) {
    const elements = [], wires = [];
    state.wires.forEach(w => wires.push([key(w.a.cid, w.a.ti), key(w.b.cid, w.b.ti)]));
    state.components.forEach(c => {
      const t0 = key(c.id, 0);
      if (c.type === 'junction') {
        const ts = DEFS.junction.terminals.map((_, i) => key(c.id, i));
        for (let i = 1; i < ts.length; i++) wires.push([ts[0], ts[i]]);
        return;
      }
      const t1 = key(c.id, 1);
      if (c.type === 'battery') elements.push({ id: c.id, kind: 'source', V: c.props.V, r: c.props.r, a: t1, b: t0 });
      else if (c.type === 'switch') elements.push(c.props.closed
        ? { id: c.id, kind: 'R', R: 0.005, a: t0, b: t1 }
        : { id: c.id, kind: 'open', a: t0, b: t1 });
      else if (c.type === 'bulb') elements.push(c.props.burned
        ? { id: c.id, kind: 'open', a: t0, b: t1 }                      // 灯丝已烧断 → 断路
        : { id: c.id, kind: 'R', R: c.props.R, a: t0, b: t1 });
      else if (c.type === 'resistor') elements.push({ id: c.id, kind: 'R', R: c.props.R, a: t0, b: t1 });
      else if (c.type === 'conductor') elements.push({ id: c.id, kind: 'R', R: resistanceOf(c), a: t0, b: t1 });
      else if (c.type === 'rheostat') elements.push({ id: c.id, kind: 'R', R: Math.max(0.5, c.props.R), a: t0, b: t1 });
      else if (c.type === 'motor') elements.push({ id: c.id, kind: 'R', R: c.props.R, a: t0, b: t1 });
      else if (c.type === 'bell') elements.push({ id: c.id, kind: 'R', R: c.props.R, a: t0, b: t1 });
      else if (c.type === 'fuse') elements.push(c.props.broken
        ? { id: c.id, kind: 'open', a: t0, b: t1 }
        : { id: c.id, kind: 'R', R: 0.01, a: t0, b: t1 });
      else if (c.type === 'led') {
        // 发光二极管:正向电压超过 Vf 才导通,导通后用"1.8V 压降 + 内阻"的等效模型
        if (ledState && ledState.get(c.id)) {
          elements.push({ id: c.id, kind: 'source', virtual: true, V: c.props.Vf, r: c.props.R, a: t1, b: t0 });
        } else {
          elements.push({ id: c.id, kind: 'open', a: t0, b: t1 });
        }
      }
      // 理想电表:电流表内阻≈0(用1e-3 Ω 代替 0,避免 1/0)、电压表≈∞(1e8 Ω,数值仍良态)
      else if (c.type === 'ammeter') elements.push({ id: c.id, kind: 'R', R: c.props.ideal ? 1e-3 : 0.02, a: t0, b: t1 });
      else if (c.type === 'voltmeter') elements.push({ id: c.id, kind: 'R', R: c.props.ideal ? 1e8 : 1e6, a: t0, b: t1 });
    });
    return { wires: wires, elements: elements };
  }

  /* ---------- 导线电流(用于流动动画) ----------
     注意:接线点的四个接线柱在电气上是同一个节点,计算导线电流时要把它们
     合并成同一个顶点,否则同一节点内的导线会断开,部分导线算不出电流。 */
  function flowKey(cid, ti) {
    const c = compById(cid);
    if (c && c.type === 'junction') return cid + ':0';
    return key(cid, ti);
  }
  function computeWireFlows(sol, inj) {
    // 接线点内部的 4 个端子恒导通,所以 flowKey 把它们折叠成同一个键(cid:0);
    // 这样"物理导线 + 接线点内部短路"合并成一张图,电流箭头才能顺着接线点继续走。
    const wires = state.wires.map(w => [flowKey(w.a.cid, w.a.ti), flowKey(w.b.cid, w.b.ti)]);
    return Solver.wireFlows(sol, wires, inj);
  }

  /* ---------- 求解 + 统计 ---------- */
  function solveOnce() {
    /* 发光二极管是非线性元件。判定"是否发光"必须同时满足两个条件:
         ① 两端有正向电压 —— 把它当作截止求解,开路电压 > Vf;
         ② 真的有电流流过 —— 把它当作导通求解,电流明显大于 0。
       只满足①而②不满足,说明回路没有闭合(例如只接了一端、或另一根线没连上):
       这时不能发光,因为发光靠的是电流做功,而电流必须有闭合回路。 */
    const leds = state.components.filter(c => c.type === 'led');
    const ledOn = new Map(), ledVOpen = new Map();
    leds.forEach(c => { ledOn.set(c.id, false); ledVOpen.set(c.id, 0); });
    for (let iter = 0; iter < 6; iter++) {
      let changed = false;
      leds.forEach(c => {
        const offMap = new Map(ledOn); offMap.set(c.id, false);
        const sOff = Solver.solve(buildInput(offMap));
        const vOpen = sOff.vOf(key(c.id, 1)) - sOff.vOf(key(c.id, 0));   // 阳极 - 阴极
        ledVOpen.set(c.id, vOpen);
        let on = false;
        if (vOpen > c.props.Vf) {
          const onMap = new Map(ledOn); onMap.set(c.id, true);
          const sOn = Solver.solve(buildInput(onMap));
          const r = sOn.results.get(c.id) || { I: 0 };
          on = Math.abs(r.I) > 1e-6;                                     // 必须真的有电流
        }
        if (!!ledOn.get(c.id) !== on) { ledOn.set(c.id, on); changed = true; }
      });
      if (!changed) break;
    }
    const sol = Solver.solve(buildInput(ledOn));

    const info = new Map(), inj = new Map();
    state.components.forEach(c => {
      const r = sol.results.get(c.id) || { I: 0, U: 0, P: 0 };
      let I01 = r.I, U01 = r.U;                          // 约定:由接线柱0 -> 接线柱1 的内部电流
      if (c.type === 'battery') U01 = sol.vOf(key(c.id, 1)) - sol.vOf(key(c.id, 0));
      if (c.type === 'led') I01 = -r.I;                  // LED 的等效电源以阳极为正极,符号取反
      info.set(c.id, { I: I01, U: U01, P: Math.abs(I01 * U01), raw: r, ledOn: !!ledOn.get(c.id), ledVOpen: ledVOpen.get(c.id) || 0 });
      if (c.type !== 'junction') {
        inj.set(key(c.id, 0), I01);
        inj.set(key(c.id, 1), -I01);
      }
    });
    const flows = computeWireFlows(sol, inj);

    // 保险丝:电流超过额定值即熔断(熔断后下一次求解按断路处理)
    let fuseBlew = false;
    state.components.forEach(c => {
      if (c.type !== 'fuse' || c.props.broken) return;
      const d = info.get(c.id);
      if (d && Math.abs(d.I) > c.props.Imax) {
        c.props.broken = true;
        fuseBlew = true;
        state.dirty = true;         // 熔断改了元件属性 → 明确置脏,防止面板与画面不一致
        state.events.push({ type: 'fuse-blow', x: c.x, y: c.y });
      }
    });
    return { sol: sol, info: info, flows: flows, fuseBlew: fuseBlew };
  }

  function solveNow() {
    let s = solveOnce();
    for (let i = 0; i < 3 && s.fuseBlew; i++) s = solveOnce();   // 熔断后重算

    let status = 'open', battI = 0, battU = 0, battP = 0, battV = 0, extR = null;
    s.sol.sources.forEach(src => {
      if (Math.abs(src.I) > Math.abs(battI)) { battI = src.I; battU = src.U; battV = src.V; }
    });
    if (s.sol.sources.length > 0) {
      battP = Math.abs(battI * battU);
      if (s.sol.shortCircuit) status = 'short';
      else if (s.sol.heavyLoad) status = 'heavy';     // 重载:没到短路,但外电路电阻已接近内阻
      else if (battI < -1e-6) status = 'charge';      // 电流流进电池 → 正在被充电(I·r 为负)
      else if (Math.abs(battI) > 1e-3) status = 'on';
      else status = 'open';
      if (Math.abs(battI) > 1e-6) extR = Math.abs(battU / battI);
    }
    // 刚发生短路:触发火花与放电音效
    if (status === 'short' && state.lastStatus !== 'short') {
      state.events.push({ type: 'short' });
      state.components.forEach(c => {
        if (c.type === 'battery') state.events.push({ type: 'short', x: c.x, y: c.y });
      });
    }
    state.lastStatus = status;
    s.status = status; s.battI = battI; s.battU = battU; s.battP = battP; s.battV = battV; s.extR = extR;
    // 电动势 E 与内阻分压 I·r:让学生直观看到 U = E − I·r(内阻"偷"走了多少电压)
    s.battE = battV;
    s.battIR = battV - battU;
    return s;
  }
  function ensureSolved() {
    if (!state.dirty && state.solved) return state.solved;
    state.solved = solveNow();
    state.dirty = false;
    updatePanel(state.solved);
    return state.solved;
  }

  /* ---------- 短路火花粒子 ---------- */
  function spawnSparksAt(x, y, count, power) {
    for (let i = 0; i < count; i++) {
      const a = Math.random() * Math.PI * 2;
      const v = (40 + Math.random() * 180) * (power || 1);
      state.sparks.push({
        x: x + (Math.random() - 0.5) * 10,
        y: y + (Math.random() - 0.5) * 10,
        vx: Math.cos(a) * v,
        vy: Math.sin(a) * v - 60,
        life: 0.18 + Math.random() * 0.4,
        max: 0.58
      });
    }
    if (state.sparks.length > 500) state.sparks.splice(0, state.sparks.length - 500);
  }
  let sparkAcc = 0;
  // 短路时沿大电流导线不断迸出火星
  function updateSparks(s, dt) {
    if (s && s.status === 'short') {
      sparkAcc += (12 + Math.min(70, Math.abs(s.battI) * 9)) * dt;
      const hot = [];
      state.wires.forEach((w, i) => { if (Math.abs(s.flows[i]) > 1.2) hot.push(i); });
      while (sparkAcc >= 1) {
        sparkAcc -= 1;
        if (!hot.length) break;
        const i = hot[Math.floor(Math.random() * hot.length)];
        const w = state.wires[i];
        const ca = compById(w.a.cid), cb = compById(w.b.cid);
        if (!ca || !cb) continue;
        const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
        const t = 0.1 + Math.random() * 0.8;
        spawnSparksAt(pa.x + (pb.x - pa.x) * t, pa.y + (pb.y - pa.y) * t, 2, 1);
      }
    } else {
      sparkAcc = 0;
    }
    for (let i = state.sparks.length - 1; i >= 0; i--) {
      const p = state.sparks[i];
      p.life -= dt;
      if (p.life <= 0) { state.sparks.splice(i, 1); continue; }
      p.vy += 420 * dt;
      p.vx *= 0.985;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
    }
  }
  function drawSparks() {
    state.sparks.forEach(p => {
      const a = Math.max(0, Math.min(1, p.life / p.max));
      const tx = p.x - p.vx * 0.014, ty = p.y - p.vy * 0.014;
      ctx.strokeStyle = 'rgba(255,196,60,' + (0.85 * a) + ')';
      ctx.lineWidth = 2.6;
      ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(p.x, p.y); ctx.stroke();
      ctx.fillStyle = 'rgba(255,248,210,' + (0.9 * a) + ')';
      ctx.beginPath(); ctx.arc(p.x, p.y, 1.6 + a * 1.4, 0, Math.PI * 2); ctx.fill();
    });
  }
  // 从求解结果推导送进音效引擎的目标量
  function audioTargets(s) {
    let motor = 0, speed = 0, bell = 0, shortLevel = 0;
    if (s) {
      state.components.forEach(c => {
        const d = s.info.get(c.id);
        if (!d) return;
        const I = Math.abs(d.I);
        if (c.type === 'motor' && I > 1e-3) {
          const k = Math.min(1, I / 0.3);
          motor = Math.max(motor, 0.35 + 0.65 * k);
          speed = Math.max(speed, k);
        }
        // 电铃音量随电流变化:0.05 A 起响,0.25 A 及以上为满音量(对数刻度更接近人耳感受)
        if (c.type === 'bell') bell = Math.max(bell, bellVolume(I));
      });
      if (s.status === 'short') shortLevel = Math.min(1, Math.abs(s.battI) / 4);
    }
    return { motor: motor, motorSpeed: speed, bell: bell, short: shortLevel };
  }
  // 电铃"音量"变量:由通过它的电流换算(0 = 不响,1 = 满音量)
  function bellVolume(I) {
    if (!(I > 5e-3)) return 0;
    const k = Math.log(Math.max(I, 5e-3) / 0.05) / Math.log(0.25 / 0.05);
    return Math.max(0.12, Math.min(1, k));
  }
  // 处理待播放的事件(短路起弧、保险丝熔断)
  function drainEvents() {
    while (state.events.length) {
      const ev = state.events.shift();
      if (ev.type === 'short') {
        Sound.spark(1);
        if (typeof ev.x === 'number') spawnSparksAt(ev.x, ev.y, 26, 1.3);
      } else if (ev.type === 'fuse-blow') {
        Sound.pop();
        if (typeof ev.x === 'number') spawnSparksAt(ev.x, ev.y, 20, 1.1);
      } else if (ev.type === 'bulb-burn') {
        Sound.pop();                                   // 灯丝烧断的"啪"
        if (typeof ev.x === 'number') spawnSparksAt(ev.x, ev.y, 26, 1.35);
        if (ev.cid) state.flash = { id: ev.cid, t: 0 };   // 没有 id 就不闪(防御)
        showToast('灯泡过载:实际 ' + fmt(ev.P, 2) + ' W 超过额定 ' + ev.rated + ' W,灯丝已烧断');
      }
    }
  }

  /* ---------- 面板 ---------- */
  const elBadge = document.getElementById('statusBadge');
  const elE = document.getElementById('statE'), elIR = document.getElementById('statIR');
  const elLoss = document.getElementById('statLoss'), elEff = document.getElementById('statEff');
  const elI = document.getElementById('statI'), elU = document.getElementById('statU');
  const elP = document.getElementById('statP'), elR = document.getElementById('statR');
  const elReadouts = document.getElementById('readouts');
  const elZoomLabel = document.getElementById('zoomLabel');
  const elInspector = document.getElementById('inspector');
  const elTips = document.getElementById('tipBox');

  function labelOf(c) {
    const names = {
      bulb: '灯泡 L', resistor: '电阻 R', rheostat: '滑动变阻器 Rp', ammeter: '电流表 A',
      voltmeter: '电压表 V', battery: '电源 E', switch: '开关 S', motor: '电动机 M',
      led: '发光二极管 D', bell: '电铃', fuse: '保险丝 F'
    };
    const same = state.components.filter(x => x.type === c.type);
    return (names[c.type] || DEFS[c.type].label) + (same.indexOf(c) + 1);
  }

  // 画布标签用的"编号前缀"(L1、S1、E1…)。
  // 序号规则与 labelOf 完全一致(同类型元件按出现顺序),保证画布与读数区编号对得上。
  function tagOf(c) {
    const codes = {
      bulb: 'L', resistor: 'R', rheostat: 'Rp', ammeter: 'A', voltmeter: 'V',
      battery: 'E', switch: 'S', motor: 'M', led: 'D', fuse: 'F'
    };
    const code = codes[c.type];
    if (!code) return '';                      // 电铃/导体/接线点没有通用字母,不编号
    const same = state.components.filter(x => x.type === c.type);
    return code + (same.indexOf(c) + 1) + ' ';
  }

  // 电表"是否接反"的唯一判据(画布与读数区共用,避免两处写反)
  // 端子 1 = + 柱;求解器 I=(v0−v1)/R、U=v0−v1 → 正接时 I<0 / U<0
  function meterReversed(c, d) {
    if (!d) return false;
    return c.type === 'ammeter' ? (d.I > 1e-6) : (d.U > 1e-6);
  }

  /* 双量程电表(改接正接线柱,两档互斥):电流表 0.6/3 A,电压表 3/15 V。
     量程只决定"读数是否超量程"的校验与提示,不改求解(内阻见理想开关)。 */
  function meterRanges(c) { return c.type === 'ammeter' ? [0.6, 3] : [3, 15]; }
  function meterRange(c) {
    const def = c.type === 'ammeter' ? 0.6 : 3;
    const r = c.props && c.props.range;
    return (typeof r === 'number' && r > 0) ? r : def;
  }
  // 超量程:既报错又给真值 —— 读数照常显示,只是标红 + 提示换大量程
  function meterOver(c, d) {
    if (!d || (c.type !== 'ammeter' && c.type !== 'voltmeter')) return false;
    const v = Math.abs(c.type === 'ammeter' ? d.I : d.U);
    return v > meterRange(c) + 1e-9;
  }

  function updatePanel(s) {
    if (!s) return;
    const map = { open: ['断路', 'open'], on: ['通路', 'on'], short: ['短路!', 'short'], heavy: ['重载(电压明显下降)', 'heavy'], charge: ['充电中(电流反向)', 'charge'] };
    elBadge.textContent = map[s.status][0];
    elBadge.className = 'badge ' + map[s.status][1];
    elI.textContent = fmt(s.battI, 3) + ' A';
    if (elE) elE.textContent = fmt(s.battE, 3) + ' V';
    if (elIR) elIR.textContent = ((s.battIR < -1e-6) ? '反向 ' : '') + fmt(Math.abs(s.battIR), 3) + ' V';
    // 内部损耗 I²r 与电源效率 U/E(初中/高中都很实用的两个量)
    const rIn = (Math.abs(s.battI) > 1e-6) ? Math.abs(s.battIR / s.battI) : null;
    if (elLoss) elLoss.textContent = (rIn === null) ? '0 W' : fmt(Math.abs(s.battI) * Math.abs(s.battI) * rIn, 3) + ' W';
    if (elEff) elEff.textContent = (Math.abs(s.battE) > 1e-6)
      ? (s.battI < -1e-6 ? '充电中' : Math.round(Math.abs(s.battU) / Math.abs(s.battE) * 100) + '%')
      : '—';
    elU.textContent = fmt(s.battU, 3) + ' V';
    elP.textContent = fmt(s.battP, 3) + ' W';
    elR.textContent = s.extR === null ? '—' : fmt(s.extR, 2) + ' Ω';

    const rows = [];
    state.components.forEach(c => {
      if (c.type === 'junction') return;                    // 接线点无读数
      const d = s.info.get(c.id) || { I: 0, U: 0, P: 0 };
      let txt = '', hot = false;
      if (c.type === 'ammeter') {
        // 电流表"正进负出":+ 柱(端子 1)进、− 柱(端子 0)出为正常
        const rev = meterReversed(c, d);
        const over = meterOver(c, d);                     // 超量程:标红 + 换档提示,真值照常显示
        hot = rev || over;
        txt = (rev ? '← ' : '→ ') + fmt(Math.abs(d.I), 3) + ' A' + (rev ? '(反接)' : '') +
          (over ? ' ⚠ 超量程(量程 0~' + meterRange(c) + ' A,应换 0~3 A)' : '');
      } else if (c.type === 'voltmeter') {
        // 电压表显示正负:+ 柱接高电位显示 "+",接反显示 "−"
        const rev = meterReversed(c, d);
        const over = meterOver(c, d);
        hot = rev || over;
        txt = (d.U <= 0 ? '+' : '−') + fmt(Math.abs(d.U), 3) + ' V' + (rev ? '(表笔接反)' : '') +
          (over ? ' ⚠ 超量程(量程 0~' + meterRange(c) + ' V,应换 0~15 V)' : '');
      } else if (c.type === 'bulb') {
        if (c.props.burned) {
          txt = '灯丝已烧断(需更换灯泡)'; hot = true;
        } else {
          const rated = c.props.rated || 1.0;
          const ratio = d.P / rated;
          const over = ratio > 1.5;                       // 超过额定 1.5 倍视为过载
          const bright = Math.min(100, Math.round(ratio * 100));
          hot = (over || ratio > 1.2);
          txt = '亮度 ' + bright + '%' + (over ? ' ⚠ 过载(额定 ' + rated + ' W,实际 ' + fmt(d.P, 2) + ' W)' : '');
        }
      } else if (c.type === 'battery') {
        txt = (Math.abs(d.I) > 1e-4 ? '供电' : '未接通') + ' · E=' + fmt(c.props.V, 2) + ' V';
      } else if (c.type === 'switch') {
        txt = c.props.closed ? '闭合' : '断开(无电流)';
      } else if (c.type === 'resistor' || c.type === 'rheostat') {
        txt = 'R=' + c.props.R + 'Ω';
      } else if (c.type === 'conductor') {
        const mat = materialOf(c);
        txt = mat.name + ' · R=' + fmtOhm(resistanceOf(c));
      } else if (c.type === 'motor') {
        const on = Math.abs(d.I) > 1e-3;
        hot = on;
        txt = on ? '转动中' : '未转动';
      } else if (c.type === 'led') {
        const on = !!d.ledOn;
        hot = on;
        txt = on ? '正向导通 · 发光'
          : (d.ledVOpen > c.props.Vf ? '有正向电压但回路没闭合 · 不发光' : '反向截止 · 不发光');
      } else if (c.type === 'bell') {
        const on = Math.abs(d.I) > 5e-3;
        const vol = Math.round(bellVolume(Math.abs(d.I)) * 100);
        hot = on;
        txt = on ? '响铃中 · 音量 ' + vol + '%' : '不响(电流太小)';
      } else if (c.type === 'fuse') {
        hot = !!c.props.broken;
        txt = c.props.broken ? '已熔断(电流超过 ' + c.props.Imax + ' A)' : '完好';
      }
      rows.push({ name: labelOf(c), I: Math.abs(d.I), U: Math.abs(d.U), P: Math.abs(d.P), txt: txt, hot: hot });
    });
    // 实验数据表(v2.0):像实验记录那样列出每件元件的读数,方便多组对比找规律
    let readHtml = '';
    if (!rows.length) readHtml = '<div class="empty">画布上还没有元件</div>';
    else readHtml = '<table class="dtable"><thead><tr><th>元件</th><th>I/A</th><th>U/V</th><th>P/W</th><th>状态</th></tr></thead><tbody>' +
      rows.map(r => '<tr><td class="dname">' + r.name + '</td><td>' + fmt(r.I, 3) + '</td><td>' + fmt(r.U, 3) +
        '</td><td>' + fmt(r.P, 3) + '</td><td class="' + (r.hot ? 'dhot' : '') + '">' + r.txt + '</td></tr>').join('') +
      '</tbody></table>';

    // 同时有电流表与电压表时,给出"实测 R = U / I"(伏安法实验的结论行)
    {
      const ams = state.components.filter(c => c.type === 'ammeter');
      const vms = state.components.filter(c => c.type === 'voltmeter');
      if (ams.length && vms.length) {
        const ia = Math.abs((s.info.get(ams[0].id) || {}).I || 0);
        const uv = Math.abs((s.info.get(vms[0].id) || {}).U || 0);
        readHtml += '<div class="row"><span class="name">实测 R = U / I</span><span class="val' +
          (ia > 1e-4 ? ' hot' : '') + '">' + (ia > 1e-4 ? fmt(uv / ia, 2) + ' Ω' : '无电流,无法测量') + '</div>';
      }
    }

    // 导体对比表:多个导体时按电流大小排序,直观体现"导电性能"
    const conductors = state.components.filter(c => c.type === 'conductor');
    if (conductors.length >= 2) {
      const list = conductors.map(c => {
        const d = s.info.get(c.id) || { I: 0 };
        return { c: c, mat: materialOf(c), I: Math.abs(d.I), R: resistanceOf(c) };
      }).sort((a, b) => b.I - a.I);
      const maxI = Math.max.apply(null, list.map(x => x.I)) || 1;
      let cmp = '<div class="cmp"><div class="cmp-title">导体对比(按电流从大到小)</div>';
      list.forEach(x => {
        const pct = Math.max(3, Math.round(x.I / maxI * 100));
        cmp += '<div class="cmp-item">' +
          '<div class="cmp-line"><span class="cmp-name">' + x.mat.name + '</span>' +
          '<span class="cmp-meta">' + x.c.props.L + 'm · ' + x.c.props.S + 'mm² · R=' + fmtOhm(x.R) + '</span>' +
          '<span class="cmp-val">' + fmt(x.I, 3) + ' A</span></div>' +
          '<div class="cmp-track"><i style="width:' + pct + '%;background:' + x.mat.color + '"></i></div></div>';
      });
      cmp += '<div class="cmp-note">电阻越小 → 通过的电流越大 → 这种材料的导电性能越强</div></div>';
      // 只有导体、没有测量元件时,别让"还没有测量元件"和对比表挤在一起
      if (!rows.length) readHtml = '';
      readHtml += cmp;
    }
    elReadouts.innerHTML = readHtml;

    // 选中的是电铃时,实时刷新它的音量显示
    const sel = state.selected;
    if (sel && sel.kind === 'component') {
      const sc = compById(sel.id);
      const volEl = document.getElementById('fv_bellvol');
      if (sc && sc.type === 'bell' && volEl) {
        const dd = s.info.get(sc.id) || { I: 0 };
        volEl.textContent = Math.round(bellVolume(Math.abs(dd.I)) * 100) + '%';
      }
    }

    updateTips(s);
  }

  function updateTips(s) {
    let html = '';
    const bulbs = state.components.filter(c => c.type === 'bulb');
    const openSwitch = state.components.some(c => c.type === 'switch' && !c.props.closed);
    const burntFuse = state.components.some(c => c.type === 'fuse' && c.props.broken);
    const hasLed = state.components.some(c => c.type === 'led');
    const hasMotor = state.components.some(c => c.type === 'motor');
    const conductors = state.components.filter(c => c.type === 'conductor');
    if (s.sol.sources.length === 0) {
      html = '<div>当前画布上没有电源。请先添加<b>电池</b>,并用导线把它和用电器连成一个<b>闭合回路</b>。</div>';
    } else if (s.status === 'short') {
      html = '<div class="sh">⚠ 短路:导线的电阻几乎为零,电源两极被直接连通,电流过大(本例 ' +
        fmt(Math.abs(s.battI), 2) + ' A,实际会更大)。<br>短路会烧坏电源和导线,实验中<b>严禁</b>把电源两极直接用导线连接。' +
        '<br><span class="tip-dim">说明:本程序把导线和闭合的开关也当作很小的电阻,真实的短路电流往往比这里显示的更大——电池会剧烈发热、冒烟甚至爆裂。</span></div>' +
        (burntFuse ? '<div>顺带一提:保险丝已经因为这个大电流熔断,起到了保护作用。</div>' : '');
    } else if (s.status === 'open') {
      html = '<div>电路<b>断路</b>,没有电流。检查:① 开关是否闭合;② 导线是否连成一个完整回路;' +
        (openSwitch ? '(当前有开关处于断开状态,点一下开关即可闭合)' : '③ 是否有接线柱漏接。') + '</div>' +
        (burntFuse ? '<div class="sh">保险丝已熔断,电路被切断——这正是它对电路的保护作用。选中它点“更换保险丝”即可恢复。</div>' : '') +
        (hasLed ? '<div>如果电路里接的是发光二极管,还要注意<b>正负极不能接反</b>。</div>' : '');
    } else {
      const I = fmt(Math.abs(s.battI), 3);
      const U = fmt(Math.abs(s.battU), 3);
      const conn = analyzeConnection(s);
      const connText = {
        series: '<span class="bad">两灯为串联</span>:电流处处相等,总电压等于各部分电压之和,U = U₁ + U₂。',
        parallel: '<span class="bad">两灯为并联</span>:各支路两端电压相等,干路电流等于各支路电流之和,I = I₁ + I₂。',
        mixed: '<span class="bad">两灯既非纯串联也非纯并联</span>:这是混联电路,可以先算并联部分,再与串联部分相加。'
      }[conn] || '';
      const lossPct = (s.battE > 1e-6) ? Math.round(s.battIR / s.battE * 100) : 0;
      const lossTip = (s.battIR > 1e-6)
        ? '<div class="tip-warn">⚡ 内阻分掉了电动势的 <b>' + lossPct + '%</b>(E = ' + fmt(s.battE, 2) +
          ' V,U = ' + fmt(s.battU, 2) + ' V,I·r = ' + fmt(s.battIR, 2) +
          ' V)。内阻越大、电流越大,路端电压掉得越明显。</div>'
        : '';
      html = '<div>电路已接通:干路电流 <b>' + I + ' A</b>,电源两端电压 <b>' + U + ' V</b>。<br>' +
        (bulbs.length >= 2 ? connText : '') +
        '</div><ul>' +
        '<li>欧姆定律:I = U / R,电压是形成电流的原因。</li>' +
        (bulbs.length ? '<li>灯泡越亮,说明它消耗的电功率 P = UI = I²R 越大。</li>' : '') +
        (conductors.length >= 2 ? '<li><b>不同导体的导电性能不同</b>:材料不同,电阻率 ρ 不同,电阻也就不同。</li>' : '') +
        (conductors.length ? '<li>导体电阻由<b>材料、长度、横截面积</b>决定:同种材料越长电阻越大,横截面积越大电阻越小。</li>' : '') +
        (hasLed ? '<li>发光二极管<b>单向导电</b>:正向接才导通发光,反接时相当于断路。</li>' : '') +
        (hasMotor ? '<li>电动机把电能转化为机械能,电流越大转得越快。</li>' : '') +
        '<li>电压表要<b>并联</b>在被测元件两端,电流表要<b>串联</b>在电路中。</li>' +
        '</ul>' + lossTip;
    }
    // 超量程:既报错又给真值 —— 读数区已标红,这里给出换档建议(任何状态下都追加)
    const overTip = state.components
      .filter(c => (c.type === 'ammeter' || c.type === 'voltmeter') && meterOver(c, s.info.get(c.id)))
      .map(c => {
        const d = s.info.get(c.id) || { I: 0, U: 0 };
        const isA = c.type === 'ammeter';
        const v = Math.abs(isA ? d.I : d.U);
        return '<div class="sh">⚠ ' + labelOf(c) + '读数 <b>' + fmt(v, 3) + (isA ? ' A' : ' V') +
          '</b> 超出 ' + meterRange(c) + (isA ? ' A' : ' V') + ' 量程 —— 请改接 <b>' +
          (isA ? '0~3 A' : '0~15 V') + '</b> 量程(真值就是它,指针会打表)。</div>';
      }).join('');
    elTips.innerHTML = html + overTip;
  }

  /* 判断两个灯泡的连接方式:看它们两端接到哪些节点 */
  function analyzeConnection(s) {
    const bulbs = state.components.filter(c => c.type === 'bulb');
    if (bulbs.length < 2) return null;
    const nets = bulbs.map(b => [s.sol.netOf(key(b.id, 0)), s.sol.netOf(key(b.id, 1))]);
    // 【并联】所有灯泡的两个节点完全相同(接在同一对节点之间)
    const n0 = nets[0];
    const samePair = nets.every(n => (n[0] === n0[0] && n[1] === n0[1]) || (n[0] === n0[1] && n[1] === n0[0]));
    if (samePair) return 'parallel';
    // 【串联】把灯泡看成点、"共用节点"看成边:应当恰好是一条链
    //   · 任何节点最多被 2 个灯泡共用(否则是分支)
    //   · 共用关系把所有灯泡连成一整条(边数 = 灯泡数 - 1 且连通)
    // 旧写法用"两两相邻"判据,3 个以上灯泡时首尾不相邻就会误判成混联。
    const deg = {};
    nets.forEach(n => n.forEach(v => { deg[v] = (deg[v] || 0) + 1; }));
    if (Object.keys(deg).some(k => deg[k] > 2)) return 'mixed';
    const par = nets.map((_, i) => i);
    const find = i => (par[i] === i ? i : (par[i] = find(par[i])));
    let edges = 0;
    for (let i = 0; i < nets.length; i++) {
      for (let j = i + 1; j < nets.length; j++) {
        const a = nets[i], b = nets[j];
        if (a[0] === b[0] || a[0] === b[1] || a[1] === b[0] || a[1] === b[1]) {
          const ra = find(i), rb = find(j);
          if (ra !== rb) par[ra] = rb;
          edges++;
        }
      }
    }
    let roots = 0;
    for (let i = 0; i < nets.length; i++) if (find(i) === i) roots++;
    if (roots === 1 && edges === nets.length - 1) return 'series';
    return 'mixed';
  }

  let lastInspectedId = null;      // 上次"被滚动到可见区"的元件,避免重复滚动
  let wantInspectorScroll = false; // 只有"点选元件 / 学习点名"才置位,其余自动选中不滚动
  function renderInspector() {
    /* 手机版:选中元件时只在底部"参数"按钮上做个高亮提示,**不自动弹出抽屉**。
       (自动弹会在拖动元件、框选、撤销等操作时反复挡住画布,非常影响操作;
         想调参数时点一下底部的"参数"即可。) */
    if (layoutMode === 'mobile') {
      const mBtnIns = document.getElementById('mBtnInspector');
      if (mBtnIns) {
        const hasSel = !!(state.selected && state.selected.kind !== 'wire');
        setElClass(mBtnIns, 'ready', hasSel);
      }
      // 取消选择后,如果参数抽屉还开着就顺手收起
      if (!state.selected && sheetOpenKind === 'inspector') closeSheet();
    }
    updateActionBar();          // 选中元件时把手机版底部栏切成操作条
    const sel = state.selected;
    if (sel && sel.kind === 'multi') {
      const n = state.selectedIds.length;
      elInspector.innerHTML =
        '<div class="insp-title">已选中 ' + n + ' 个元件</div>' +
        '<div class="btnrow">' +
        '<button data-act="rotateSel">整组旋转 90°</button>' +
        '<button data-act="rotateSel180">整组翻转 180°</button>' +
        '</div>' +
        '<div class="btnrow">' +
        '<button data-act="selectAll">全选 (Ctrl+A)</button>' +
        '<button data-act="clearSel">取消选择</button>' +
        '</div>' +
        '<button class="danger" data-act="deleteSel">删除所选 ' + n + ' 个元件</button>' +
        '<div class="insp-note">拖动其中任意一个元件即可<b>整组一起移动</b>;<br>' +
        '按住 Shift 拖动鼠标可框选更多元件,按住 Shift 点击可单个加入/移出。<br>' +
        '按 <b>R</b> 整组旋转,按 <b>Delete</b> 一次删除。</div>';
      return;
    }
    if (!sel || sel.kind !== 'component') {
      elInspector.innerHTML = '<div class="insp-empty">点击画布上的元件可调参数;' +
        '在空白处拖动鼠标可<b>框选多个元件</b>批量拖动</div>';
      return;
    }
    const c = compById(sel.id);
    if (!c) { elInspector.innerHTML = ''; return; }
    let html = '<div class="insp-title">' + labelOf(c) + '(' + DEFS[c.type].label + ')</div>';
    // 操作按钮放最前面:右侧栏不做内部滚动,放底部会被挤出可视区看不见
    html += '<div class="btnrow">' +
      '<button data-act="rotate90">旋转 90°</button>' +
      '<button data-act="rotate180">' + ((c.type === 'battery' || c.type === 'led') ? '对调 +-' : '翻转 180°') + '</button>' +
      '<button class="danger" data-act="del">删除</button>' +
      '</div>';
    if (c.type === 'battery') {
      html += field('电压 E', 'V', 1.5, 6, 0.5, c.props.V, ' V') + field('内阻 r', 'r', 0.1, 2, 0.1, c.props.r, ' Ω') +
        '<div class="insp-note">当前极性:' +
        (normRot(c) === 180 || normRot(c) === 270 ? '<b>左为+、右为-</b>' : '<b>左为-、右为+</b>') +
        '(竖直放置时为上+下-或上-下+)。</div>' +
        '<details class="note"><summary>怎么改正负极方向?</summary>' +
        '<div class="insp-note">点「对调 +-」即可改变正负极方向(接线夹留在原处),点「旋转 90°」可把电池竖起来放。</div></details>';
    } else if (c.type === 'bulb') {
      if (c.props.burned) {
        html += '<button class="on" data-act="replaceBulb">更换灯泡(灯丝已烧断)</button>';
      } else if (c.props._hot > 0) {
        html += '<div class="insp-note" style="color:#c02a2a;font-weight:600">⚠ 正在过载:约 ' +
          Math.max(0, 1.6 - c.props._hot).toFixed(1) + ' 秒后灯丝烧断(降低电压可恢复)</div>';
      }
      html += '<div class="fields">' + field('灯丝电阻 R', 'R', 5, 30, 1, c.props.R, ' Ω') +
        field('额定功率', 'rated', 0.3, 3, 0.1, c.props.rated || 1.0, ' W') + '</div>' +
        '<details class="note"><summary>过载规则说明</summary><div class="insp-note">亮度按"实际功率 ÷ 额定功率"计算:' +
        '超过额定 <b>1.2 倍</b> 亮起 ⚠ 警告,超过 <b>1.5 倍</b> 且持续约 <b>1.6 秒</b> 灯丝就会烧断(及时降低电压可以救回)。</div></details>';
    } else if (c.type === 'resistor') {
      html += field('阻值 R', 'R', 5, 100, 5, c.props.R, ' Ω');
    } else if (c.type === 'rheostat') {
      html += field('接入阻值 R', 'R', 0, 50, 1, c.props.R, ' Ω') +
        '<div class="insp-note">拖动滑片改变接入电路的电阻,可用来控制电流大小(本程序简化为两端变阻器)。</div>';
    } else if (c.type === 'conductor') {
      const mat = materialOf(c);
      html += '<div style="color:#47597a;font-size:12.5px">选择材料:</div><div class="matgrid">';
      MATERIALS.forEach(m => {
        html += '<button data-act="setMat" data-mat="' + m.id + '"' +
          (m.id === mat.id ? ' class="on"' : '') + '>' + m.name + '</button>';
      });
      html += '</div>' +
        field('长度 L', 'L', 0.1, 2, 0.1, c.props.L, ' m') +
        field('横截面积 S', 'S', 0.01, 1, 0.01, c.props.S, ' mm²') +
        '<div class="insp-note">当前材料:<b>' + mat.name + '</b>(' + mat.kind + '),电阻率 ρ=' + mat.rho +
        ' Ω·mm²/m<br>R = ρL/S = <b><span id="fv_calc">' + fmtOhm(resistanceOf(c)) + '</span></b><br>' +
        '同种材料:越长电阻越大、越粗电阻越小;材料不同,导电性能不同。</div>';
    } else if (c.type === 'motor') {
      html += field('线圈电阻 R', 'R', 5, 50, 1, c.props.R, ' Ω') +
        '<div class="insp-note">电动机把电能转化为机械能,电流越大转子转得越快。</div>';
    } else if (c.type === 'led') {
      html += field('导通压降 Vf', 'Vf', 1.5, 2.5, 0.1, c.props.Vf, ' V') +
        field('内阻 R', 'R', 10, 100, 5, c.props.R, ' Ω') +
        '<div class="insp-note">具有<b>单向导电性</b>:右端(+)接正极才导通发光。实际使用必须串联限流电阻。</div>';
    } else if (c.type === 'bell') {
      const db = (state.solved && state.solved.info) ? state.solved.info.get(c.id) : null;
      const vol0 = db ? Math.round(bellVolume(Math.abs(db.I)) * 100) + '%' : '—';
      html += field('线圈电阻 R', 'R', 5, 50, 1, c.props.R, ' Ω') +
        '<div class="insp-note">有电流通过时铃锤振动发声。<b>电流越大,声音越响、敲击越快</b>' +
        '(本程序:0.05 A 起响,0.25 A 及以上为满音量)。<br>串联一个滑动变阻器,改变阻值就能听到音量变化。<br>' +
        '当前音量:<b><span id="fv_bellvol">' + vol0 + '</span></b></div>';
    } else if (c.type === 'fuse') {
      html += field('额定电流 Imax', 'Imax', 0.1, 3, 0.1, c.props.Imax, ' A') +
        '<div class="insp-note">电流超过额定值会熔断,从而切断电路起保护作用。</div>';
      if (c.props.broken) html += '<button class="on" data-act="replaceFuse">更换保险丝</button>';
    } else if (c.type === 'switch') {
      html += '<button class="' + (c.props.closed ? 'on' : '') + '" data-act="toggleSwitch">' +
        (c.props.closed ? '开关已闭合(点击断开)' : '开关已断开(点击闭合)') + '</button>';
    } else if (c.type === 'ammeter') {
      const range = meterRange(c);
      const dm = (state.solved && state.solved.info) ? state.solved.info.get(c.id) : null;
      const ua = dm ? Math.abs(dm.U) : 0;
      html += '<div style="color:#47597a;font-size:12.5px">量程(改接正接线柱,两档互斥):</div><div class="btnrow">' +
        meterRanges(c).map(v => '<button data-act="setMeterRange" data-val="' + v + '"' +
          (range === v ? ' class="on"' : '') + '>0~' + v + ' A</button>').join('') + '</div>' +
        '<button class="' + (c.props.ideal ? 'on' : '') + '" data-act="toggleIdealMeter">' +
        (c.props.ideal ? '理想电表(内阻≈0)· 点击改回实际' : '实际电表(内阻 0.02 Ω)· 点击改理想') + '</button>' +
        '<div class="insp-note">应<b>串联</b>接入。当前电流表两端电压 <b>' + fmt(ua, 3) +
        ' V</b>;理想表内阻为 0,分压可忽略(常规读数显示 0.000 V)。</div>';
    } else if (c.type === 'voltmeter') {
      const range = meterRange(c);
      const dm = (state.solved && state.solved.info) ? state.solved.info.get(c.id) : null;
      const iv = dm ? Math.abs(dm.I) : 0;
      const ivTxt = iv < 0.001 ? (iv * 1e6).toFixed(1) + ' µA' : fmt(iv, 3) + ' A';
      html += '<div style="color:#47597a;font-size:12.5px">量程(改接正接线柱,两档互斥):</div><div class="btnrow">' +
        meterRanges(c).map(v => '<button data-act="setMeterRange" data-val="' + v + '"' +
          (range === v ? ' class="on"' : '') + '>0~' + v + ' V</button>').join('') + '</div>' +
        '<button class="' + (c.props.ideal ? 'on' : '') + '" data-act="toggleIdealMeter">' +
        (c.props.ideal ? '理想电表(内阻≈∞)· 点击改回实际' : '实际电表(内阻 1 MΩ)· 点击改理想') + '</button>' +
        '<div class="insp-note">应<b>并联</b>在被测元件两端。流过电压表的电流 <b>' + ivTxt +
        '</b>;理想表内阻无穷大,分流可忽略。</div>';
    } else {
      html += '<div class="insp-note">接线点只起导线交汇作用,四个方向内部导通。</div>';
    }
    if (c.type === 'battery' || c.type === 'led') {
      html += '<div class="insp-note">点「对调 +-」相当于把元件掉个头:<b>接线夹留在原处</b>,元件内部正负极反过来,' +
        '所以电池电流方向会跟着反向' + (c.type === 'led' ? ',发光二极管会变成反接而不亮' : '') + '。' +
        '(若想保持正负极不变、只把元件挪个方向,请把导线接到另一侧的接线端。)</div>';
    }
    elInspector.innerHTML = html;
    if (learnOn) learnHighlight();       // 面板重绘后把"要拖的滑块"高亮补回来
    // 右侧栏较长时,参数卡片可能被挤到屏幕外(滑块够不着)。
    // 选中对象变化时把卡片滚进视口——学习"点名"元件时也走这条路。
    const selIdNow = (state.selected && state.selected.kind === 'component') ? state.selected.id : null;
    if (wantInspectorScroll && selIdNow) {
      wantInspectorScroll = false;
      lastInspectedId = selIdNow;
      try {
        const card = document.getElementById('inspectorCard');
        if (card && card.scrollIntoView) {
          card.scrollIntoView({ block: 'nearest', behavior: 'auto' });   // 即时滚动,低配/无头环境也可靠
          // 兜底:个别布局下 scrollIntoView 不动,就直接算一次滚动量
          if (card.getBoundingClientRect && window.scrollBy) {
            const rect = card.getBoundingClientRect();
            const vh = window.innerHeight || 800;
            if (rect.bottom > vh) window.scrollBy(0, rect.bottom - vh + 24);
            else if (rect.top < 0) window.scrollBy(0, rect.top - 24);
          }
        }
      } catch (e) { }
    } else if (!selIdNow) {
      lastInspectedId = null;
      wantInspectorScroll = false;
    }
  }
  function field(text, prop, min, max, step, val, unit) {
    return '<div class="field" data-field="' + prop + '"><label>' + text + '<span id="fv_' + prop + '">' + val + unit + '</span></label>' +
      '<input type="range" data-prop="' + prop + '" min="' + min + '" max="' + max + '" step="' + step + '" value="' + val + '"></div>';
  }

  /* ---------- 交互 ---------- */
  // 是否触摸/手机操作:手指比鼠标粗,判定范围要按"屏幕像素"放大
  function isTouchLike() {
    if (layoutMode === 'mobile') return true;
    try { return !!(window.matchMedia && window.matchMedia('(pointer:coarse)').matches); } catch (e) { return false; }
  }
  function toLocal(ev) {
    const r = canvas.getBoundingClientRect();
    return screenToWorld(ev.clientX - r.left, ev.clientY - r.top);
  }
  // 把"屏幕像素"换算成世界单位下的命中半径(缩小画面时自动放大,手指也点得中)
  function hitRadiusScreen(px) { return Math.max(6, px / Math.max(0.05, view.scale)); }
  /* 接线柱判定半径(屏幕像素)——长按、松手、点击、悬停统一用它,避免两套数值手感割裂 */
  function termSlackPx() { return isTouchLike() ? 48 : 22; }
  // 找最近的接线柱:判定范围按屏幕像素给(手指按下去容易命中),并取"最近的那个"
  function hitTerminal(p, slackPx) {
    const touch = isTouchLike();
    const px = slackPx || termSlackPx();
    const rad = hitRadiusScreen(px);
    let best = null, bestD = Infinity;
    for (let i = state.components.length - 1; i >= 0; i--) {
      const c = state.components[i];
      const ts = DEFS[c.type].terminals;
      for (let t = 0; t < ts.length; t++) {
        const pos = termPos(c, t);
        const d = Math.hypot(p.x - pos.x, p.y - pos.y);
        // 接线点本体会被元件本体挡住,单独给一个略小的范围
        // 接线点:中心留给「拖动本体」,只有外圈当作接线柱(否则触屏上拖不动)
        let lim = rad;
        if (c.type === 'junction') {
          const inner = hitRadiusScreen(touch ? 15 : 9);
          if (d < inner) continue;
          lim = hitRadiusScreen(touch ? 48 : 26);   // 外圈:接线柱命中范围(中心留给拖动本体)
        }
        if (d < lim && d < bestD) { bestD = d; best = { cid: c.id, ti: t, pos: pos }; }
      }
    }
    return best;
  }
  /* 长按起手专用:接线点中心的小圈也算接线柱(点击/拖动/悬停仍走 hitTerminal) */
  function hitTerminalAny(p) {
    const touch = isTouchLike();
    const rad = hitRadiusScreen(termSlackPx());
    let best = null, bestD = Infinity;
    for (let i = state.components.length - 1; i >= 0; i--) {
      const c = state.components[i];
      const ts = DEFS[c.type].terminals;
      for (let t = 0; t < ts.length; t++) {
        const pos = termPos(c, t);
        const d = Math.hypot(p.x - pos.x, p.y - pos.y);
        let lim = rad;
        if (c.type === 'junction') lim = hitRadiusScreen(touch ? 48 : 26);
        if (d < lim && d < bestD) { bestD = d; best = { cid: c.id, ti: t, pos: pos }; }
      }
    }
    return best;
  }
  function hitComponent(p) {
    const pad = hitRadiusScreen(isTouchLike() ? 18 : 4);   // 手指点得中,鼠标保持精确
    for (let i = state.components.length - 1; i >= 0; i--) {
      const c = state.components[i], b = bounds(c);
      const m = pad;                                  // 本体都留外扩,接线点也更容易按住
      if (p.x >= b.x - m && p.x <= b.x + b.w + m && p.y >= b.y - m && p.y <= b.y + b.h + m) return c;
    }
    return null;
  }
  // 带容差的导线命中(拖线时容差放宽,方便"吸附"到导线上)
  function hitWireTol(p, tol) {
    for (let i = state.wires.length - 1; i >= 0; i--) {
      const w = state.wires[i];
      const ca = compById(w.a.cid), cb = compById(w.b.cid);
      if (!ca || !cb) continue;
      const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
      if (dist2Seg(p.x, p.y, pa.x, pa.y, pb.x, pb.y) < (tol || 8)) return i;
    }
    return -1;
  }
  // 点 p 在导线 wi 上的最近点(用于决定接线点落在哪里)
  function projOnWire(wi, p) {
    const w = state.wires[wi];
    if (!w) return null;
    const ca = compById(w.a.cid), cb = compById(w.b.cid);
    if (!ca || !cb) return null;
    const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
    const vx = pb.x - pa.x, vy = pb.y - pa.y;
    const len2 = vx * vx + vy * vy;
    let t = len2 > 1e-9 ? ((p.x - pa.x) * vx + (p.y - pa.y) * vy) / len2 : 0;
    t = Math.max(0.12, Math.min(0.88, t));         // 不要贴到端点(端点已有接线柱)
    return { x: pa.x + vx * t, y: pa.y + vy * t };
  }
  // 在导线 wi 的 (x,y) 处插入一个接线点,并把 from 端点接到它上面
  function insertJunctionOnWire(wi, x, y, from) {
    const w = state.wires[wi];
    if (!w) return false;
    pushUndo('在导线上接分支');
    const jx = Math.round(x / 10) * 10, jy = Math.round(y / 10) * 10;
    const j = makeComp('junction', jx, jy);
    state.components.push(j);
    state.wires.splice(wi, 1);
    state.wires.push({ a: { cid: w.a.cid, ti: w.a.ti }, b: { cid: j.id, ti: 0 } });
    state.wires.push({ a: { cid: j.id, ti: 0 }, b: { cid: w.b.cid, ti: w.b.ti } });
    if (!(from.cid === j.id && from.ti === 0)) {
      state.wires.push({ a: { cid: from.cid, ti: from.ti }, b: { cid: j.id, ti: 0 } });
    }
    state.dirty = true;
    Sound.click(0.6);
    showToast('已在导线上加入接线点,并连好分支');
    return true;
  }

  /* ---------- 长按接线:直接拖 = 移动元件;按住不动 = 进入接线状态 ---------- */
  const TERM_HOLD_MS = 380;      // 长按时长(毫秒)
  const HUD_SHOW_AT = 0.5;       // 按住进度超过 50%(约 190ms)才显示进度条 —— 轻点绝不出现在屏幕上
  const TERM_HOLD_PX_SCREEN = 14; // 按住期间允许的抖动(屏幕像素)
  function clearTermPress() {
    if (state.termPress && state.termPress.timer) { try { clearTimeout(state.termPress.timer); } catch (e) { } }
    state.termPress = null;
  }
  // 尝试进入接线状态(幂等;定时器与帧循环共用)
  function tryEnterWireMode(holder) {
    if (!holder || state.termPress !== holder) return false;
    if (holder.moved) return false;                          // 按住期间移动过 → 按拖动元件处理
    if (!state.drag || state.drag.mode !== 'component') return false;
    const from = holder.from;
    clearTermPress();
    state.tapTerm = null;
    state.hoverTerm = { cid: from.cid, ti: from.ti, pos: { x: holder.sx, y: holder.sy } };
    state.wireMode = { from: from };        // 接线模式:松手也保持,接着点另一个接线柱就能连
    state.dirty = true;
    Sound.click(0.5);
    showToast('接线模式:点另一个接线柱就能连上(按 Esc 或点空白退出)');
    return true;
  }
  /* 点一下接线柱 → 进入"待连接":再点另一个接线柱就连上(v2.0 恢复点击连线,不再需要长按) */
  function beginPendingTerm(t) {
    if (!t) return false;
    state.pendingTerm = { cid: t.cid, ti: t.ti };
    state.termPress = null;
    state.tapTerm = null;
    state.dirty = true;
    Sound.click(0.45);
    const c0 = compById(t.cid);
    const nm = c0 ? tagOf(c0).trim() : '';
    showToast('已选中 ' + nm + ' 的接线柱:再点另一个接线柱就连上(点空白或 Esc 取消)');
    renderInspector();
    return true;
  }
  function armTermPress(t, p) { }

  function hitWire(p) {
    for (let i = state.wires.length - 1; i >= 0; i--) {
      const w = state.wires[i];
      const ca = compById(w.a.cid), cb = compById(w.b.cid);
      if (!ca || !cb) continue;
      const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
      if (dist2Seg(p.x, p.y, pa.x, pa.y, pb.x, pb.y) < 8) return i;
    }
    return -1;
  }

  /* ---------- 触摸手势:双指缩放 ---------- */
  const activePointers = new Map();
  let pinchState = null;
  function pinchInfo() {
    const pts = Array.from(activePointers.values());
    if (pts.length !== 2) return null;
    const dx = pts[0].x - pts[1].x, dy = pts[0].y - pts[1].y;
    return { dist: Math.max(1, Math.hypot(dx, dy)), cx: (pts[0].x + pts[1].x) / 2, cy: (pts[0].y + pts[1].y) / 2 };
  }

  canvas.addEventListener('pointerdown', ev => {
    const p = toLocal(ev);
    state.mouse = p; mouseStale = false;
    if (ev.pointerType) state.lastPointerType = ev.pointerType;   // 记住最近一次按下的指针类型
    /* 接线模式下(已松手):这一次点击就是"指定另一端" */
    if (state.wireMode && ev.button !== 2) {
      const wm = state.wireMode;
      const tt = hitTerminal(p, termSlackPx());
      if (tt) {
        if (!(tt.cid === wm.from.cid && tt.ti === wm.from.ti)) {
          addWire(wm.from.cid, wm.from.ti, tt.cid, tt.ti);
          Sound.click(0.6);
        } else {
          Sound.click(0.3);                     // 点自己 = 取消
        }
        state.wireMode = null;
        state.dirty = true;
        renderInspector();
        return;
      }
      const wi = hitWireTol(p, hitRadiusScreen(isTouchLike() ? 30 : 14));
      if (wi >= 0) {                            // 点在导线上 → 在那条导线上插入接线点并连通
        const pr = projOnWire(wi, p);
        if (pr) insertJunctionOnWire(wi, pr.x, pr.y, wm.from);
        state.wireMode = null;
        state.dirty = true;
        renderInspector();
        return;
      }
      // 点空白:退出接线模式,并继续按普通点击处理(可以顺便选中别的元件)
      state.wireMode = null;
      state.dirty = true;
    }
    canvas.setPointerCapture(ev.pointerId);
    activePointers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });
    // 第二根手指落下 → 进入双指缩放,取消正在进行的拖动/连线
    if (activePointers.size === 2) {
      const info = pinchInfo();
      if (info) {
        pinchState = { dist: info.dist, zoom: view.zoom, cx: info.cx, cy: info.cy };
        state.drag = null;
        state.hoverTerm = null;
        state.selected = null;
        renderInspector();
        return;
      }
    }
    if (ev.button === 2) return;                     // 右键在 contextmenu 处理
    const nt0 = hitNote(p);
    if (nt0) {
      // Alt + 点击:锁定/解锁该注解。锁定后它只作显示,点击会"穿透"到下面的元件
      if (ev.altKey) {
        pushUndo('锁定注解');
        nt0.locked = !nt0.locked;
        state.dirty = true;
        showToast(nt0.locked ? '注解已锁定:点击穿透,不再挡住下面的元件(Alt+点击可解锁)'
          : '注解已解锁:可以拖动、可以右键删除');
        return;
      }
      if (hitNoteGrip(nt0, p)) {                    // 拖右下角 = 调整注解框大小
        pushUndo('调整注解大小');
        state.noteResize = { id: nt0.id, startX: p.x, w0: nt0.w || 280 };
        return;
      }
      pushUndo('移动注解'); state.noteDrag = { id: nt0.id, dx: p.x - nt0.x, dy: p.y - nt0.y, moved: false }; return;
    }
    if (state.annotate && !hitComponent(p) && hitWire(p) < 0) {
      let txt = '';
      try { txt = (typeof prompt === 'function') ? (prompt('输入注解内容(可多行)', '') || '') : ''; } catch (e) { txt = ''; }
      if (txt.trim()) addNote(p.x, p.y, txt.trim());
      return;
    }
    const body = hitComponent(p);
    // 已经有"待连接"的接线柱时,这一下点击用来指定另一端
    if (state.pendingTerm) {
      let t2 = hitTerminal(p);
      // 接线点:它的接线柱就在圆心(中心被"拖动本体"占用了),这里要能直接补上
      if (!t2 && body && body.type === 'junction') {
        const bp = termPos(body, 0);
        t2 = { cid: body.id, ti: 0, pos: bp };
      }
      if (t2) {
        if (t2.cid === state.pendingTerm.cid && t2.ti === state.pendingTerm.ti) {
          clearPendingTerm();                  // 点自己 = 取消
        } else {
          addWire(state.pendingTerm.cid, state.pendingTerm.ti, t2.cid, t2.ti);
          clearPendingTerm();
          Sound.click(0.6);
        }
      } else {
        // 点在导线上 → 就地插一个接线点把分支接上(和"先选中端点再点线"一致)
        const wi2 = hitWireTol(p, hitRadiusScreen(isTouchLike() ? 30 : 14));
        if (wi2 >= 0) {
          const pr = projOnWire(wi2, p);
          if (pr) {
            insertJunctionOnWire(wi2, pr.x, pr.y, state.pendingTerm);
            clearPendingTerm();
            Sound.click(0.6);
            renderInspector();
            return;
          }
        }
        clearPendingTerm();                    // 点空白 = 取消
      }
      renderInspector();
      return;
    }
    /* 连线 / 拖动 的判定:
       · 已经有"待连接"端点时,这一下点击就是指定另一端 → 直接连上;
       · 否则一律按"拖元件"处理,同时记住按下的位置有没有端点。
         松手时若**没有移动过**,才算"点了一下端点" → 进入待连接(点击连线);
         只要移动过,就是拖动元件,不会误连。
       (这样既保留了"点端点连线",又不会像"端点无条件优先"那样让元件拖不动。) */
    {
      // 接线点的中心小圈也算端点(拖动仍然是移动本体)
      const tArm = hitTerminalAny(p);
      const t = hitTerminal(p);
      if (t && state.pendingTerm && (state.pendingTerm.cid !== t.cid || state.pendingTerm.ti !== t.ti)) {
        addWire(state.pendingTerm.cid, state.pendingTerm.ti, t.cid, t.ti);
        clearPendingTerm();
        Sound.click(0.6);
        renderInspector();
        return;
      }
      /* 接线交互(v2.0 起"点一下就连"):
         · 轻点接线柱 = 选中这一端(待连接),再点另一个接线柱就接好;
         · 拖动(接线柱或本体)= 移动元件,不接线;
         · 按住不动不再需要等计时 —— 松手即判定,点得快也一样能连。 */
      state.tapTerm = t || tArm || null;
    }
    const c = body;
    if (c) {
      const shift = !!ev.shiftKey;
      // 类似文件管理器的多选:点未选中的元件 = 只选它;Shift 点击 = 加入/移出选择
      if (!isSelected(c.id)) {
        state.selectedIds = shift ? state.selectedIds.concat([c.id]) : [c.id];
        state.selected = { kind: 'component', id: c.id };
        wantInspectorScroll = true;          // 用户主动点选 → 把参数卡片带进视野
      } else if (shift) {
        state.selectedIds = state.selectedIds.filter(id => id !== c.id);
        state.selected = selSummary();
      }
      // 拖动整组:记录组内每个元件的起始位置
      const ids = state.selectedIds.length ? state.selectedIds : [c.id];
      state.drag = {
        mode: 'component', cid: c.id, moved: false, before: captureSnapshot(), sx: p.x, sy: p.y, shift: shift,
        anchor: { x: c.x, y: c.y }, dx: p.x - c.x, dy: p.y - c.y,
        tapTerm: state.tapTerm,
        group: ids.map(id => { const cc = compById(id); return { id: id, x: cc.x, y: cc.y }; })
      };
      renderInspector();
      return;
    }
    const wi = hitWire(p);
    if (wi >= 0) { state.selected = { kind: 'wire', index: wi }; state.selectedIds = []; renderInspector(); return; }
    // 空白处:拖动 = 框选多个元件(像用光标框选文件);
    // 中键拖动、按住 Ctrl/⌘ 或空格拖动 = 平移画面;轻点 = 取消选择
    if (ev.button === 1 || ev.ctrlKey || ev.metaKey || state.spaceDown) {
      // 中键/空格拖动 = 平移画面。必须阻止浏览器默认行为(否则中键会触发"自动滚动",
      // 整个页面跟着一起滑,和画面平移打架),并禁掉由中键拖动带出的选择。
      if (ev.button === 1) {
        ev.preventDefault();
        try { if (document.body && document.body.style) document.body.style.userSelect = 'none'; } catch (e) { }
      }
      state.drag = { mode: 'pan', cx: ev.clientX, cy: ev.clientY, tx: view.tx, ty: view.ty, moved: false };
    } else {
      state.drag = { mode: 'marquee', x0: p.x, y0: p.y, x1: p.x, y1: p.y, moved: false, add: !!ev.shiftKey, tapTerm: state.tapTerm };
      canvas.style.cursor = 'crosshair';
    }
    renderInspector();
  });

  // 中键的"自动滚动"由浏览器在 mousedown 时触发,光拦 pointerdown 不够稳:
  // 这里把 mousedown / auxclick 也一并拦掉,保证中键拖动只平移画面、页面纹丝不动。
  const blockMiddle = ev => { if (ev.button === 1) ev.preventDefault(); };
  canvas.addEventListener('mousedown', blockMiddle);
  canvas.addEventListener('auxclick', blockMiddle);
  if (wrap && wrap.addEventListener) { wrap.addEventListener('mousedown', blockMiddle); wrap.addEventListener('auxclick', blockMiddle); }

  // 双击缩放:只在手机端、且双击的是"空白处"时才生效。
  // (电脑版取消:连点两下开关之类的操作会被误判成双击,很烦;
  //   手机端也避开元件,免得连点开关时突然放大。)
  canvas.addEventListener('dblclick', ev => {
    if (layoutMode !== 'mobile') return;
    if (state.drag) return;
    const p = toLocal(ev);
    if (hitComponent(p)) return;            // 点在元件上(比如连点开关)不缩放
    if (hitTerminal(p)) return;
    if (hitNote(p)) return;
    const r = canvas.getBoundingClientRect();
    setZoom(Math.min(10, view.zoom * 1.25), ev.clientX - r.left, ev.clientY - r.top);
    state.dirty = true;
  });

  canvas.addEventListener('pointermove', ev => {
    state.mouse = toLocal(ev);
    if (activePointers.has(ev.pointerId)) activePointers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });
    // 双指:捏合缩放 + 拖动平移
    if (pinchState && activePointers.size === 2) {
      const info = pinchInfo();
      if (info) {
        if (pinchState.dist > 0 && Math.abs(info.dist - pinchState.dist) > 1.5) {
          setZoom(pinchState.zoom * (info.dist / pinchState.dist), info.cx, info.cy);
        }
        if (pinchState.cx !== undefined) {
          view.tx += (info.cx - pinchState.cx);
          view.ty += (info.cy - pinchState.cy);
        }
        pinchState.dist = info.dist;
        pinchState.cx = info.cx; pinchState.cy = info.cy;
        pinchState.zoom = view.zoom;
        return;
      }
    }
    const p = toLocal(ev);
    state.mouse = p;
    clearTermPress();
    const d = state.drag;
    if (!d) { state.hoverTerm = hitTerminal(p); return; }
    if (d.mode === 'component') {
      if (Math.hypot(p.x - d.sx, p.y - d.sy) > 3) {
        d.moved = true;
        state.tapTerm = null;              // 有移动就不算"点端点"
        // 一开始拖动就退出接线模式:拖动 = 拖动,接线只靠"长按 + 点击"
        if (state.wireMode) { state.wireMode = null; state.dirty = true; }
      }
      if (d.moved) state.dirty = true;      // 实时重算:拖动时电流箭头跟着变(视觉冲击更强)
      // 拖动过程中严格跟随光标(不做网格吸附,否则放大后会"跟不上手");
      // 整组按同一原始位移移动,保持相对位置。吸附在松手时统一进行。
      const LIM = 100000;
      let dx = p.x - d.sx, dy = p.y - d.sy;
      let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
      d.group.forEach(g => {
        minX = Math.min(minX, g.x); maxX = Math.max(maxX, g.x);
        minY = Math.min(minY, g.y); maxY = Math.max(maxY, g.y);
      });
      dx = Math.max(-LIM - minX, Math.min(LIM - maxX, dx));
      dy = Math.max(-LIM - minY, Math.min(LIM - maxY, dy));
      d.group.forEach(g => { const cc = compById(g.id); if (cc) { cc.x = g.x + dx; cc.y = g.y + dy; } });
    } else if (d.mode === 'wire') {
      if (Math.hypot(p.x - d.sx, p.y - d.sy) > hitRadiusScreen(4)) d.moved = true;
      d.x = p.x; d.y = p.y;
      state.hoverTerm = hitTerminal(p, termSlackPx());
      /* 靠近某条导线 → 记下"将要插入接线点"的位置(松手才真正放置)。
         命中端子时优先连端子,不做导线吸附。 */
      if (state.hoverTerm) {
        d.snap = null;
      } else {
        const wi = hitWireTol(p, hitRadiusScreen(isTouchLike() ? 22 : 14));
        const pr = wi >= 0 ? projOnWire(wi, p) : null;
        d.snap = pr ? { wi: wi, x: pr.x, y: pr.y } : null;
      }
      state.dirty = true;
    } else if (d.mode === 'marquee') {
      d.x1 = p.x; d.y1 = p.y;
      if (Math.hypot(d.x1 - d.x0, d.y1 - d.y0) > 3) d.moved = true;
    } else if (d.mode === 'pan') {
      const dx = ev.clientX - d.cx, dy = ev.clientY - d.cy;
      if (Math.abs(dx) > 3 || Math.abs(dy) > 3) d.moved = true;
      view.tx = d.tx + dx;
      view.ty = d.ty + dy;
    }
  });

  canvas.addEventListener('pointerup', ev => {
    activePointers.delete(ev.pointerId);
    if (activePointers.size < 2) pinchState = null;
    if (ev.button === 1) { try { if (document.body && document.body.style) document.body.style.userSelect = ''; } catch (e) { } }   // 中键平移结束,恢复文本选择
    // 触摸抬起后指针就不在画布上了:标记为"失效",避免虚线预览指向空处
    if (!ev.pointerType || ev.pointerType !== 'mouse') mouseStale = true;
    state.noteDrag = null;
    state.noteResize = null;
    const d = state.drag;
    state.drag = null;
    if (!d) { state.tapTerm = null; return; }
    if (d.mode === 'wire') {
      // 兼容:更早版本可能残留这个模式;现在拖动一律不接线
      state.dirty = true;
    } else if (d.mode === 'component') {
      /* 轻点接线柱 = 进入待连接(点一下就连上;v2.0 恢复,不再需要长按):
         松手时若没移动过、且按下的正是接线柱,就把它设为"待连接"一端;
         接着点另一个接线柱即 addWire 连上。拖动过(moved)则仍是移动元件。 */
      if (!d.moved && d.tapTerm) { beginPendingTerm(d.tapTerm); return; }
      state.tapTerm = null;
      if (state.wireMode) { return; }           // 刚进入接线模式这一下,不触发元件的点击动作
      if (d.moved) state.learnMoved = true;
      if (d.moved && d.before) pushUndoSnapshot('移动元件', d.before);
      if (d.moved) {
        // 松手时才吸附到网格:拖动过程严格跟手,落点整齐、方便对接导线
        const step = currentGridStep();
        const anc = compById(d.cid);
        if (anc && d.group.length) {
          const sdx = Math.round(anc.x / step) * step - anc.x;
          const sdy = Math.round(anc.y / step) * step - anc.y;
          if (Math.abs(sdx) > 1e-6 || Math.abs(sdy) > 1e-6) {
            d.group.forEach(g => { const cc = compById(g.id); if (cc) { cc.x += sdx; cc.y += sdy; } });
          }
        }
      } else {
        const c = compById(d.cid);
        if (c && c.type === 'switch') {
          pushUndo('切换开关');
          c.props.closed = !c.props.closed;
          state.dirty = true;
          Sound.click(c.props.closed ? 1 : 0.8);
        }
        // 多选中轻点其中一个 → 收敛为只选它(和文件管理器一致);Shift 点击用于增删,不收敛
        if (!d.shift && state.selectedIds.length > 1) { state.selectedIds = [d.cid]; state.selected = { kind: 'component', id: d.cid }; }
      }
      renderInspector();
    } else if (d.mode === 'marquee') {
      canvas.style.cursor = 'default';
      if (!d.moved && d.tapTerm) { beginPendingTerm(d.tapTerm); return; }   // 点在元件本体外的接线柱也算"点接线柱"
      if (!d.moved) {
        if (!d.add) { state.selectedIds = []; state.selected = null; }
      } else {
        const x0 = Math.min(d.x0, d.x1), x1 = Math.max(d.x0, d.x1);
        const y0 = Math.min(d.y0, d.y1), y1 = Math.max(d.y0, d.y1);
        const hits = state.components.filter(c => {
          const b = bounds(c);
          return !(b.x > x1 || b.x + b.w < x0 || b.y > y1 || b.y + b.h < y0);
        }).map(c => c.id);
        let next = d.add ? state.selectedIds.concat(hits.filter(id => state.selectedIds.indexOf(id) < 0)) : hits;
        applySelection(next);
        Sound.click(0.35);
      }
      renderInspector();
    } else if (d.mode === 'pan') {
      canvas.style.cursor = 'default';
    }
  });

  canvas.addEventListener('contextmenu', ev => {
    ev.preventDefault();
    /* 关键:触摸设备"长按"也会触发浏览器的 contextmenu(约 0.5 秒),
       而这里是"右键删除元件/导线"——于是长按接线时元件直接被删掉。
       三重保险:① 触摸布局/粗指针 ② 最近一次按下的指针类型是触摸 ③ 长按进度条正在走
       —— 这几种情况一律忽略,绝不删除、也不打断长按。 */
    if (isTouchLike() || state.lastPointerType === 'touch' || state.termPress) { return; }
    const ntHit = hitNote(toLocal(ev));
    if (ntHit) { removeNote(ntHit.id); return; }
    if (state.wireMode) { state.wireMode = null; state.dirty = true; showToast('已退出接线模式'); return; }
    if (state.pendingTerm) { clearPendingTerm(); return; }
    const p = toLocal(ev);
    const c = hitComponent(p);
    if (c) { deleteComponent(c.id); return; }
    const wi = hitWire(p);
    if (wi >= 0) { pushUndo('删除导线'); state.wires.splice(wi, 1); state.selected = null; state.dirty = true; renderInspector(); }
  });
  // 触摸被系统打断(来电、多任务切换)时复位手势状态
  canvas.addEventListener('pointercancel', ev => {
    activePointers.delete(ev.pointerId);
    if (activePointers.size < 2) pinchState = null;
    state.drag = null;
    state.tapTerm = null;
    clearTermPress();                 // 系统打断(来电/多任务)→ 长按状态一并清掉
    mouseStale = true;
  });
  // 指针离开画布(鼠标移出 / 触摸结束)→ 虚线预览不再跟随
  canvas.addEventListener('pointerleave', () => { mouseStale = true; clearTermPress(); });

  window.addEventListener('keydown', ev => {
    if (ev.target && ev.target.tagName === 'INPUT') return;   // 正在调参数时不响应快捷键
    // 空格:按住时拖动 = 平移画面
    if (ev.key === ' ' || ev.code === 'Space') { state.spaceDown = true; }
    const mod = ev.ctrlKey || ev.metaKey;
    // Ctrl/⌘ + Z:撤销(加 Shift 为重做);Ctrl/⌘ + Y:重做
    if (mod && (ev.key === 'z' || ev.key === 'Z')) {
      ev.preventDefault();
      if (ev.shiftKey) doRedo(); else doUndo();
      return;
    }
    if (mod && (ev.key === 'y' || ev.key === 'Y')) { ev.preventDefault(); doRedo(); return; }
    // Ctrl/⌘ + A:全选
    if (mod && (ev.key === 'a' || ev.key === 'A')) {
      selectAllComponents(); ev.preventDefault(); return;
    }
    if (mod) return;                       // 其余快捷键不响应带修饰键的组合(避免 Ctrl+R 触发旋转)
    // Esc:先关图鉴,再取消选择
    if (ev.key === 'Escape') {
      if (libOverlay && libOverlay.hidden === false) { closeLibrary(); return; }
      if (aboutOverlay && aboutOverlay.hidden === false) { closeAbout(); return; }
      if (aboutOverlay && aboutOverlay.hidden === false) { closeAbout(); return; }
      if (state.pendingTerm) { clearPendingTerm(); renderInspector(); return; }
      clearSelection(); renderInspector(); return;
    }
    // R 键旋转选中的元件(支持多选,整组一起转)
    if ((ev.key === 'r' || ev.key === 'R') && state.selectedIds.length) {
      rotateSelection(90); ev.preventDefault(); return;
    }
    if (ev.key !== 'Delete' && ev.key !== 'Backspace') return;
    const s = state.selected;
    if (!s) return;
    if (state.selectedIds.length > 1) { deleteSelection(); return; }
    if (s.kind === 'component') deleteComponent(s.id);
    else if (s.kind === 'multi') deleteSelection();
    else if (s.kind === 'wire') { state.wires.splice(s.index, 1); state.selected = null; state.dirty = true; }
    renderInspector();
  });
  window.addEventListener('keyup', ev => {
    if (ev.key === ' ' || ev.code === 'Space') state.spaceDown = false;
  });

  function deleteComponent(cid) {
    if (!compById(cid)) return;
    state.learnDeleted = true;
    pushUndo('删除元件');
    state.components = state.components.filter(c => c.id !== cid);
    state.wires = state.wires.filter(w => w.a.cid !== cid && w.b.cid !== cid);
    clearSelection();
    state.dirty = true;
    renderInspector();
    if (typeof refreshPalette === 'function') refreshPalette();
  }
  // 批量删除所选元件(连同它们的导线)
  function deleteSelection() {
    const ids = state.selectedIds.slice();
    if (!ids.length) return;
    pushUndo('删除所选 ' + ids.length + ' 个元件');
    state.components = state.components.filter(c => ids.indexOf(c.id) < 0);
    state.wires = state.wires.filter(w => ids.indexOf(w.a.cid) < 0 && ids.indexOf(w.b.cid) < 0);
    clearSelection();
    state.dirty = true;
    Sound.click(0.6);
    renderInspector();
    if (typeof refreshPalette === 'function') refreshPalette();
  }
  /* ---------- 元件掉头与正负极 ----------
     真实实验里把电池"掉个头",接线夹是留在原处的,于是元件内部正负极相对电路反了过来,
     电流方向也跟着反向。本程序里导线记录的是"接在第几个接线端",如果只转元件,
     导线会跟着一起转,电流方向就永远不变。所以这里在元件掉头时把两个接线端上的导线对调,
     效果与真实实验一致:接线夹不动、元件极性反过来。 */
  function syncFlipWires(c) {
    const d = DEFS[c.type];
    if (!d || !d.terminals || d.terminals.length !== 2) return false;   // 只处理"两头元件"
    const want = Math.floor(normRot(c) / 180) % 2 === 1;                 // 朝向 180°/270° = 已掉头
    const was = !!c.flipped;
    if (want === was) return false;
    c.flipped = want;
    state.wires.forEach(w => {
      if (w.a.cid === c.id) w.a.ti = 1 - w.a.ti;
      if (w.b.cid === c.id) w.b.ti = 1 - w.b.ti;
    });
    state.dirty = true;
    return true;
  }

/* ---------- 撤销 / 重做 ----------
     每次会改变电路的操作之前,先把"整份电路快照"(元件 + 导线 + 编号 + 选中状态)存起来;
     撤销就是回到上一步之前的状态,重做再把它放回去。
     同一类连续操作(例如按住滑块调电阻)只记一步,避免一次拖动产生几十条历史。 */
  const undoStack = [], redoStack = [];
  const UNDO_LIMIT = 120;
  let lastCoalesceKey = null, lastCoalesceTime = 0;
  let historySuppressed = 0;              // >0 时暂不记录(批量构建电路时用)
  function withoutHistory(fn) {
    historySuppressed++;
    try { return fn(); } finally { historySuppressed--; }
  }

  function captureSnapshot() {
    return {
      components: JSON.parse(JSON.stringify(state.components)),
      wires: JSON.parse(JSON.stringify(state.wires)),
      idSeq: state.idSeq,
      selected: state.selected ? JSON.parse(JSON.stringify(state.selected)) : null,
      selectedIds: state.selectedIds.slice(),
      notes: JSON.parse(JSON.stringify(state.notes || []))
    };
  }
  function updateHistoryButtons() {
    const u = document.getElementById('btnUndo'), r = document.getElementById('btnRedo');
    if (u) {
      u.disabled = undoStack.length === 0;
      u.title = undoStack.length ? ('撤销:' + undoStack[undoStack.length - 1].label + '(Ctrl+Z)') : '没有可撤销的操作';
    }
    if (r) {
      r.disabled = redoStack.length === 0;
      r.title = redoStack.length ? ('重做:' + redoStack[redoStack.length - 1].label + '(Ctrl+Y)') : '没有可重做的操作';
    }
  }
  function pushUndoSnapshot(label, snap) {
    undoStack.push({ label: label, snap: snap });
    if (undoStack.length > UNDO_LIMIT) undoStack.shift();
    redoStack.length = 0;                 // 产生新分支后,原来的"重做"作废
    lastCoalesceKey = null;
    updateHistoryButtons();
  }
  function pushUndo(label, coalesceKey) {
    if (historySuppressed) return;
    const now = Date.now();
    if (coalesceKey && coalesceKey === lastCoalesceKey && now - lastCoalesceTime < 900) {
      lastCoalesceTime = now;             // 同一类连续操作(如拖滑块)并入上一步
      return;
    }
    pushUndoSnapshot(label, captureSnapshot());
    lastCoalesceKey = coalesceKey || null;   // 注意:必须在压栈之后设置(压栈会清空它)
    lastCoalesceTime = now;
  }
  function restoreSnapshot(sn) {
    state.components = JSON.parse(JSON.stringify(sn.components));
    state.wires = JSON.parse(JSON.stringify(sn.wires));
    // 灯泡的"过载倒计时"是运行中的瞬时状态,不该跟着快照回来(否则撤销一下就会立刻烧断)
    state.components.forEach(c => { if (c.props) c.props._hot = 0; });
    state.idSeq = sn.idSeq;
    state.selected = sn.selected ? JSON.parse(JSON.stringify(sn.selected)) : null;
    state.selectedIds = (sn.selectedIds || []).slice();
    state.notes = sn.notes ? JSON.parse(JSON.stringify(sn.notes)) : (state.notes || []);
    state.noteDrag = null;
    state.drag = null;
    state.hoverTerm = null;
    state.dirty = true;
    state.solved = null;                  // 强制重新求解
    ensureSolved();
    renderInspector();
    updateHistoryButtons();
  }
  function doUndo() {
    state.learnUndone = true;
    if (!undoStack.length) return false;
    const e = undoStack.pop();
    redoStack.push({ label: e.label, snap: captureSnapshot() });
    restoreSnapshot(e.snap);
    Sound.tick(0, { play: 'click' });
    Sound.click(0.32);
    if (typeof refreshPalette === 'function') refreshPalette();
    return true;
  }
  function doRedo() {
    if (!redoStack.length) return false;
    const e = redoStack.pop();
    undoStack.push({ label: e.label, snap: captureSnapshot() });
    restoreSnapshot(e.snap);
    Sound.click(0.45);
    if (typeof refreshPalette === 'function') refreshPalette();
    return true;
  }
  function historyInfo() {
    return {
      canUndo: undoStack.length > 0, canRedo: redoStack.length > 0,
      undoLabel: undoStack.length ? undoStack[undoStack.length - 1].label : '',
      redoLabel: redoStack.length ? redoStack[redoStack.length - 1].label : '',
      undoCount: undoStack.length, redoCount: redoStack.length
    };
  }

  /* ================= 实验文件:保存 / 打开(JSON) =================
     格式:{ app, format, savedAt, components, wires, notes, idSeq, view }
     保存 = 序列化快照(与撤销系统同构);打开 = 校验后走 restoreSnapshot
     (自动清灯泡过载计时、强制重求解、刷新面板)。校验不过绝不覆盖当前电路。 */
  const EXP_FORMAT = 1;
  function exportExperimentJSON() {
    const snap = captureSnapshot();
    return JSON.stringify({
      app: 'circuit-lab',
      format: EXP_FORMAT,
      savedAt: new Date().toISOString(),
      components: snap.components,
      wires: snap.wires,
      notes: snap.notes,
      idSeq: snap.idSeq,
      view: { scale: view.scale, baseScale: view.baseScale, zoom: view.zoom, tx: view.tx, ty: view.ty }
    }, null, 2);
  }
  function importExperimentJSON(text) {
    let d = null;
    try { d = JSON.parse(text); } catch (e) {
      return { ok: false, error: '文件不是有效的 JSON(可能没下载完,或被改坏了)' };
    }
    if (!d || typeof d !== 'object' || d.app !== 'circuit-lab') {
      return { ok: false, error: '这不是本程序的实验文件' };
    }
    if (typeof d.format !== 'number' || d.format > EXP_FORMAT) {
      return { ok: false, error: '实验文件版本太新(format=' + d.format + '),请用新版程序打开' };
    }
    if (!Array.isArray(d.components) || !Array.isArray(d.wires)) {
      return { ok: false, error: '文件缺少元件或导线数据' };
    }
    const idMap = new Map();
    for (const c of d.components) {
      if (!c || !DEFS[c.type] || !isFinite(c.x) || !isFinite(c.y)) {
        return { ok: false, error: '文件里的元件数据损坏' };
      }
      if (!c.props || typeof c.props !== 'object') c.props = {};
      idMap.set(c.id, c);
    }
    for (const w of d.wires) {
      if (!w || !w.a || !w.b) return { ok: false, error: '文件里的导线数据损坏' };
      const ca = idMap.get(w.a.cid), cb = idMap.get(w.b.cid);
      if (!ca || !cb) return { ok: false, error: '导线引用了文件里不存在的元件' };
      const okT = (cc, ti) => typeof ti === 'number' && ti >= 0 && ti < DEFS[cc.type].terminals.length;
      if (!okT(ca, w.a.ti) || !okT(cb, w.b.ti)) return { ok: false, error: '导线接到了不存在的端子上' };
    }
    const notes = Array.isArray(d.notes)
      ? d.notes.filter(n => n && isFinite(n.x) && isFinite(n.y)) : [];
    // —— 全部通过才动状态:先压一步撤销(打开也可以撤销),再整体替换 ——
    pushUndo('打开实验');
    const maxNum = d.components.reduce(function (m, c) {
      return Math.max(m, parseInt(String(c.id).slice(1), 10) || 0);
    }, 0);
    restoreSnapshot({
      components: d.components,
      wires: d.wires,
      idSeq: Math.max(d.idSeq | 0, maxNum, d.components.length),
      selected: null, selectedIds: [],
      notes: notes
    });
    state.wireMode = null; state.pendingTerm = null;
    state.annotate = false; state.learnPick = null; state.tapTerm = null;
    if (d.view && isFinite(d.view.tx) && isFinite(d.view.ty)) {
      view.scale = d.view.scale || view.scale;
      view.baseScale = d.view.baseScale || view.baseScale;
      view.zoom = d.view.zoom || view.zoom;
      view.tx = d.view.tx; view.ty = d.view.ty;
    }
    return { ok: true, comps: d.components.length, wires: d.wires.length, notes: notes.length };
  }
  function saveExperimentFile() {
    try {
      const json = exportExperimentJSON();
      const d = new Date(), pad = n => (n < 10 ? '0' : '') + n;
      const name = '电路实验_' + d.getFullYear() + pad(d.getMonth() + 1) + pad(d.getDate()) +
        '_' + pad(d.getHours()) + pad(d.getMinutes()) + '.json';
      const blob = new Blob([json], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url; a.download = name;
      if (a.style) a.style.display = 'none';
      document.body.appendChild(a); a.click(); document.body.removeChild(a);
      setTimeout(function () { try { URL.revokeObjectURL(url); } catch (e) { } }, 4000);
      showToast('实验已保存:' + name + '(' + state.components.length + ' 个元件)');
      return { ok: true, name: name, bytes: json.length };
    } catch (e) {
      showToast('保存失败:' + (e && e.message ? e.message : '未知错误'));
      return { ok: false, error: String((e && e.message) || e) };
    }
  }
  let fileInputEl = null;
  function openExperimentFile() {
    try {
      if (!fileInputEl) {
        fileInputEl = document.createElement('input');
        fileInputEl.type = 'file';
        fileInputEl.accept = '.json,application/json';
        fileInputEl.style.display = 'none';
        fileInputEl.addEventListener('change', function () {
          const f = fileInputEl.files && fileInputEl.files[0];
          if (!f) return;
          const reader = new FileReader();
          reader.onload = function () {
            const r = importExperimentJSON(String(reader.result));
            if (r.ok) showToast('已打开实验:' + r.comps + ' 个元件、' + r.wires + ' 条导线');
            else showToast('打开失败:' + r.error);
            fileInputEl.value = '';
          };
          reader.onerror = function () { showToast('打开失败:读取文件出错'); fileInputEl.value = ''; };
          reader.readAsText(f);
        });
        document.body.appendChild(fileInputEl);
      }
      fileInputEl.click();
      return { ok: true };
    } catch (e) {
      showToast('打开失败:' + (e && e.message ? e.message : '未知错误'));
      return { ok: false, error: String((e && e.message) || e) };
    }
  }
  /* 导出主画布为高清 PNG:同步块内临时放大背板 → 画一帧 → 取图 → 还原。
     JS 单线程,浏览器来不及画中间态 → 无闪烁;导出期间 exportMode 跳过界面元素。 */
  function exportCanvasPNG() {
    const ts = (last != null) ? last : 0;
    const oldW = canvas.width || 1000, oldH = canvas.height || 700, oldDpr = view.dpr;
    let url = null, outW = oldW, outH = oldH;
    try {
      const S = Math.max(1, Math.min(4, Math.round(2400 / Math.max(1, oldW))));
      if (S > 1) {
        canvas.width = Math.round(oldW * S);
        canvas.height = Math.round(oldH * S);
        view.dpr = oldDpr * S;
      }
      exportMode = true;
      try { frameLogic(ts); } finally { exportMode = false; }
      url = canvas.toDataURL('image/png');
      outW = canvas.width; outH = canvas.height;
      const a = document.createElement('a');
      a.href = url; a.download = '实物接线图.png';
      if (a.style) a.style.display = 'none';
      document.body.appendChild(a); a.click(); document.body.removeChild(a);
      showToast('图片已导出(' + outW + '×' + outH + ')');
      return { ok: true, w: outW, h: outH };
    } catch (e) {
      showToast('导出失败:' + (e && e.message ? e.message : '未知错误'));
      return { ok: false, error: String((e && e.message) || e) };
    } finally {
      canvas.width = oldW; canvas.height = oldH; view.dpr = oldDpr;   // 无论成败都还原
      try { frameLogic(ts); } catch (e2) { }
    }
  }
  (function bindFileButtons() {
    const sv = document.getElementById('btnSaveExp');
    if (sv) sv.addEventListener('click', function () { saveExperimentFile(); Sound.click(0.4); });
    const op = document.getElementById('btnOpenExp');
    if (op) op.addEventListener('click', function () { openExperimentFile(); Sound.click(0.4); });
    const ex = document.getElementById('btnExportImg');
    if (ex) ex.addEventListener('click', function () { exportCanvasPNG(); Sound.click(0.4); });
  })();

  // 批量旋转所选元件
  function rotateSelection(delta) {
    const list = selectedComponents();
    if (!list.length) return;
    pushUndo(delta === 180 ? '翻转所选元件' : '旋转所选元件');
    list.forEach(c => { c.rot = normDeg(normRot(c) + delta); syncFlipWires(c); });
    state.dirty = true;
    Sound.click(0.45);
    renderInspector();
  }
  // 复制所选元件(参数一起复制),贴在原处右下方,方便连续摆放
  function duplicateSelection() {
    const all = selectedComponents();
    if (!all.length) return;
    // 器材篮子:复制同样受"本关给定数量"限制(删除会自动腾出名额)
    const list = []; const used = {};
    all.forEach(function (c) {
      const gi = levelGearItem(c.type);
      if (gi && !gi.free) {
        const placed = state.components.filter(x => x.type === c.type).length + (used[c.type] || 0);
        if (placed >= gi.n) {
          showToast('本关「' + ((DEFS[c.type] && DEFS[c.type].label) || '元件') + '」已用完,无法复制');
          return;
        }
        used[c.type] = (used[c.type] || 0) + 1;
      }
      list.push(c);
    });
    if (!list.length) return;
    const one = list.length === 1;
    pushUndo(one ? '复制元件' : ('复制所选 ' + list.length + ' 个元件'));
    const news = list.map(function (c) {
      const n = makeComp(c.type, c.x + 44, c.y + 44);
      n.rot = c.rot || 0;
      n.props = JSON.parse(JSON.stringify(c.props || {}));
      n.props._hot = 0;              // 副本从"没过载"开始,不会一出现就烧断
      return n;
    });
    state.components = state.components.concat(news);
    state.selectedIds = news.map(function (c) { return c.id; });
    state.selected = one ? { kind: 'component', id: news[0].id } : selSummary();
    state.dirty = true;
    Sound.place();
    state.flash = { id: news[news.length - 1].id, t: 0 };
    showToast(one ? ('已复制:' + ((DEFS[news[0].type] && DEFS[news[0].type].label) || '元件'))
      : ('已复制 ' + news.length + ' 个元件'));
    ensureVisible(news[news.length - 1]);
    renderInspector();
  }
  // 旋转元件(顺时针 90°/180°):电池转 180° 就是正负极对调,转 90° 可以竖着放
  function rotateComponent(c, delta) {
    if (!c) return;
    state.learnRotated = true;
    pushUndo(delta === 180 ? ((c.type === 'battery' || c.type === 'led') ? '对调正负极' : '翻转元件') : '旋转元件');
    c.rot = normDeg(normRot(c) + delta);
    syncFlipWires(c);
    state.dirty = true;
    Sound.click(0.45);
    renderInspector();
  }

  /* ---------- 手机版底部"选中操作条":选中元件后整条切换 ---------- */
  // 惰性查 DOM(renderInspector 在启动早期就会被调用,用缓存的 const 会踩暂时性死区)
  function updateActionBar() {
    const bar = document.getElementById('mbar');
    if (!bar) return;
    const kind = state.selected && state.selected.kind;
    const isWire = !!(state.selected && kind === 'wire');
    const on = !!(layoutMode === 'mobile' && (isWire ||
      (state.selectedIds.length && (kind === 'component' || kind === 'multi'))));
    setElClass(bar, 'acting', on);
    setElClass(bar, 'wiremode', on && isWire);      // 导线模式:只留"删除导线"和"完成"
    if (!on) return;
    if (isWire) {
      const delLblW = document.getElementById('mActDelLbl');
      if (delLblW) delLblW.textContent = '删除导线';
      return;
    }
    const n = state.selectedIds.length;
    const c = n === 1 ? compById(state.selectedIds[0]) : null;
    const canFlip = !!(c && (c.type === 'battery' || c.type === 'led'));
    const rotLbl = document.getElementById('mActRotLbl');
    const flipLbl = document.getElementById('mActFlipLbl');
    const delLbl = document.getElementById('mActDelLbl');
    const flipBtn = document.getElementById('mActFlip');
    if (rotLbl) rotLbl.textContent = n > 1 ? '整组旋转' : '旋转';
    if (flipLbl) flipLbl.textContent = canFlip ? '对调+-' : '翻转';
    if (delLbl) delLbl.textContent = n > 1 ? ('删' + n + '个') : '删除';
    if (flipBtn) flipBtn.title = canFlip
      ? '对调正负极(接线夹留在原处,电流方向随之反向)' : '翻转 180°';
  }
  {
    const bind = (id, fn) => { const b = document.getElementById(id); if (b) b.addEventListener('click', fn); };
    // 「参数」必须留在操作条里:选中元件后最常做的就是调参数
    bind('mActParams', function () {
      if (sheetOpenKind === 'inspector') { closeSheet(); return; }
      openSheet('inspector');
      Sound.click(0.4);
    });
    bind('mActDone', function () { clearSelection(); renderInspector(); });
    bind('mActRot', function () { rotateSelection(90); });
    bind('mActFlip', function () {
      const ids = state.selectedIds;
      if (ids.length === 1) {
        const c = compById(ids[0]);
        if (c) { rotateComponent(c, 180); return; }
      }
      rotateSelection(180);
    });
    bind('mActCopy', duplicateSelection);
    bind('mActDel', function () {
      // 选中的是导线(手机端没有右键/Delete 键,靠这颗按钮删)
      if (state.selected && state.selected.kind === 'wire') {
        pushUndo('删除导线');
        state.wires.splice(state.selected.index, 1);
        state.selected = null; state.dirty = true; renderInspector();
        showToast('已删除这条导线');
        return;
      }
      if (state.selectedIds.length > 1) { deleteSelection(); return; }
      const c = compById(state.selectedIds[0]);
      if (c) deleteComponent(c.id);
    });
  }

  /* 电脑版底部操作条:删除选中的元件(与右键、Delete 键等价) */
  /* 学习条与手机抽屉互斥:抽屉开着时把学习条藏起来,避免压住"添加元件"面板 */
  function syncLearnBarForSheet(kindArg) {
    const ov = document.getElementById('learnOverlay');
    if (!ov) return;
    const sheetOn = (kindArg !== undefined) ? !!kindArg : !!sheetOpenKind;
    setElClass(ov, 'hide-for-sheet', layoutMode === 'mobile' && sheetOn);
  }

  /* ---------- 操作学习:独立画布 + 注解指引 + 按钮高亮 ---------- */
  const LEARN_STEPS = [
    { t: '欢迎来到简易电路实验展示',
      note: '这里是操作学习。接下来我会用画布上的说明框一步步教你,\n需要点的按钮会闪烁高亮。大约 3 分钟走完全部操作。',
      target: '#learnNext',
      d: '准备好了就点下面高亮的「开始学习」。进入后会给你一块全新的画布,你原来的电路会被安全保存,退出时自动恢复。' },
    { t: '第 1 步:添加元件(开关、电池、小灯泡)',
      note: '① 添加元件\n点右侧「添加元件」面板,依次放入:\n① 开关 ② 电池 ③ 小灯泡',
      noteMobile: '① 添加元件\n点底部「+元件」打开元件抽屉\n依次放入:① 开关 ② 电池 ③ 小灯泡',
      target: ['#paletteQuick',
        '#paletteQuick [data-type="switch"]', '#paletteQuick [data-type="battery"]', '#paletteQuick [data-type="bulb"]'],
      targetMobile: '#mBtnPalette',          // 手机端:点底部「+元件」打开抽屉
      d: '三个元件都放好后会自动进入下一步——后面几步要用它们组成完整电路。',
      check: s => ['switch', 'battery', 'bulb'].every(t => s.components.some(c => c.type === t)) },
    { t: '第 2 步:移动元件',
      note: '② 移动元件\n按住元件本体拖动它,松手会自动吸附到网格线',
      target: '#wrap',
      d: '接线点(小圆点)也是拖它的中心来移动。',
      check: s => s.learnMoved },
    { t: '第 3 步:连接导线(最常用)',
      note: '③ 连接导线\n点一下蓝色小圆点(接线柱)\n再点另一个小圆点就连上',
      target: '#wrap',
      d: '按住不动约半秒,起头出现呼吸光环就进入接线状态;松手后点另一端即可连上(点导线会自动插接线点)。把电池、开关、灯泡依次连成一个回路。',
      check: s => s.wires.length > 0 },
    { t: '第 4 步:载入一个演示电路',
      note: '④ 演示电路\n点「演示电路 / 📚演示」展开菜单,选「基本电路」\n(后面几步在完整电路上练习更方便)',
      target: ['#btnPresets', '#presetList [data-preset="basic"]'],
      targetMobile: ['#mBtnPresets', '#presetList [data-preset="basic"]'],
      d: '菜单里的「基本电路」也会一起高亮,直接点它即可。演示电路都带讲解注解。',
      check: s => s.learnPresetLoaded },
    { t: '第 5 步:闭合开关看电流',
      note: '⑤ 开关与电流\n点一下画布上高亮的开关让它闭合\n接通后会出现橙色箭头 = 电流方向',
      target: '#wrap',
      pick: 'switch',
      d: '电流越大箭头跑得越快;再点一下开关就断开。',
      check: s => s.components.some(c => c.type === 'switch' && c.props && c.props.closed) },
    { t: '第 6 步:调整参数',
      note: '⑥ 调参数\n画布上高亮的就是电池\n点「⚙参数」,把电压滑块拖到 6 V(到了会自动下一步)',
      noteMobile: '⑥ 调参数\n画布上高亮的就是电池\n点操作条里的「⚙参数」,把电压滑块拖到 6 V(到了会自动下一步)',
      target: '#inspectorCard',
      pick: 'battery',
      pickProp: 'V',          // 还要把"电压 E"这个滑块整行高亮出来
      targetMobile: ['#mActParams', '#mBtnInspector'],
      d: '电压、内阻、灯泡额定值、导体材料与粗细都可以调。',
      hold: 3,        // 调到 6V 后再停留约 1.2 秒,别让参数窗口突然消失
      check: s => {
        const b = s.components.filter(c => c.type === 'battery')[0];
        return !!b && Math.abs((b.props.V || 0) - 6) < 0.25;   // 必须真的调到 6 V
      } },
    { t: '第 7 步:旋转与对调正负极',
      note: '⑦ 旋转 / 对调+-\n画布上高亮的是电池,点「对调 +-」(或按 R 键)\n电流箭头会立刻反向',
      noteMobile: '⑦ 旋转 / 对调+-\n画布上高亮的是电池\n点下方操作条里高亮的「对调 +-」',
      target: ['#wrap', '#inspectorCard [data-act="rotate180"]'],
      targetMobile: '#mActFlip',
      pick: 'battery',
      d: '接线夹留在原处,只把元件内部正负极反过来。',
      check: s => s.learnRotated },
    { t: '第 8 步:删除元件',
      note: '⑧ 删除元件\n选中高亮的元件,点下方操作条里的红色「删除」\n(电脑端也可以右键元件直接删、或按 Delete 键)',
      target: '#btnDelSel',
      targetMobile: '#mActDel',
      pick: 'switch',
      d: '删掉的元件连同它的导线一起删除,撤销可以找回。',
      check: s => s.learnDeleted },
    { t: '第 9 步:框选多个元件',
      hold: 3,        // 框选完成后停留久一点,能看清选中了哪些
      note: '⑨ 框选\n在画布空白处按住拖动,像框选文件一样选中多个元件\n然后可以整组移动、整组旋转、一次删除',
      target: '#wrap',
      d: 'Ctrl+A 全选,Shift 点击可以单个加入/移出。',
      check: s => s.selectedIds.length > 1 },
    { t: '第 9.5 步:画面控制(缩放 / 平移 / 缩略图)',
      note: '⑩ 画面控制\nCtrl+滚轮 或「- 缩小 / + 放大」缩放\nCtrl/⌘+拖动、中键拖动、空格+拖动 平移画面\n右下角缩略图可以点着跳转、拖左上角手柄改大小\n!!此处需要手动点击下一步',
      noteMobile: '⑩ 画面控制\n双指捏合缩放、双指拖动平移画面\n点下方「⤢适应」一键把整个电路缩放居中\n!!此处需要手动点击下一步',
      target: '#btnZoomIn',
      targetMobile: '#mBtnFit',
      d: '手机端用双指捏合缩放、双指拖动平移;「⤢适应窗口」一键把整个电路缩放居中。',
      check: null },      // 不自动跳步:这一步由用户手动点"下一步"
    { t: '第 10 步:撤销与重做',
      note: '⑩ 撤销\n按 Ctrl+Z 或点下方「撤销」,把刚才的操作退回去',
      target: ['#btnUndo', '#btnRedo'],
      d: '最多可回退 120 步;Ctrl+Y 是重做。',
      check: s => s.learnUndone },
    { t: '第 11 步:加一条注解',
      desktopOnly: true,          // 注解只在电脑端有,手机端直接跳过这一步
      note: '⑪ 注解功能\n点下方「📝注解」进入注解模式,再点画布空白处\n就能加一个半透明说明框(白字)',
      noteMobile: '⑪ 注解功能(电脑端)\n在电脑端点「📝注解」就能在画布上加说明框\n(这是给老师讲重难点用的)',
      target: '#btnAnnotate',
      targetMobile: '',
      d: '注解可以拖动位置、右键删除,讲重难点时非常有用。',
      check: s => (s.notes || []).filter(n => n.id !== 'learn-note').length > 0 },
    { t: '第 12 步:元件图鉴与帮助',
      note: '⑫ 图鉴与帮助\n「📖元件图鉴」:每种元件的电路符号、实物图、常见规格\n「❓帮助」:完整说明书与常见问题',
      target: ['#btnLib', '#btnAbout', '#libClose'],
      targetMobile: '#btnLib',
      tip: '点击此处返回操作界面',
      tipSel: '#libClose',
      hold: 0,        // 用户要求:返回操作界面后直接下一步
      d: '这两个是课后自学的好帮手。看完点右上角「×」返回,会自动进入下一步。',
      check: s => s.learnLibDone },
    { t: '全部完成,开始探索吧!',
      target: '#learnNext',
      note: '🎉 操作学习完成\n你已经掌握了全部操作。点「完成」退出,\n原来的电路会自动恢复。',
      d: '14 个演示电路、13 种元件、注解与图鉴,随时可用。',
      check: null }
  ];
  let learnIdx = 0, learnOn = false, learnSaved = null, learnHold = 0, learnSettle = 0;   // learnHold:刚点过上一步的一小段时间内不自动前进
  const learnOverlay = document.getElementById('learnOverlay');
  const learnBody = document.getElementById('learnBody');
  const learnBar = document.getElementById('learnBar');

  /* 注解放哪:在画布的四个角里挑一个"压住元件最少"的位置,
     避免说明框挡住这一步要操作的东西(比如要点的开关)。 */
  function learnNotePlace() {
    const v = visibleWorld();
    const W = 380, H = 110;                      // 说明框的大致尺寸(世界单位)
    const boxes = state.components.map(c => bounds(c));
    const pad = 28;
    // 底部实际被"底部栏 + 元件栏 + 提示条"挡住的屏幕高度(--mstack,单位 px),换算成世界单位
    let stackPx = 104;
    try {
      const v0 = getComputedStyle(document.documentElement).getPropertyValue('--mstack');
      const parsed = parseFloat(v0);
      if (isFinite(parsed) && parsed > 0) stackPx = parsed;
    } catch (e) { }
    const lift = stackPx / Math.max(0.05, view.scale) + 10;
    const cands = [
      { x: v.x0 + pad, y: v.y0 + pad },                          // 左上(默认优先)
      { x: v.x1 - W - pad, y: v.y0 + pad },                      // 右上
      { x: v.x0 + pad, y: v.y1 - H - lift },                     // 左下(避开底部栏+元件栏+提示条)
      { x: v.x1 - W - pad, y: v.y1 - H - lift }                  // 右下(同上,并避开缩略图)
    ];
    const overlap = p => boxes.reduce(function (s, b) {
      const ox = Math.max(0, Math.min(p.x + W, b.x + b.w) - Math.max(p.x, b.x));
      const oy = Math.max(0, Math.min(p.y + H, b.y + b.h) - Math.max(p.y, b.y));
      return s + ox * oy;
    }, 0);
    let best = cands[0], bestScore = Infinity;
    cands.forEach(function (c) {
      const sc = overlap(c);
      if (sc < bestScore - 0.5) { bestScore = sc; best = c; }     // 严格更小才换,保证优先左上
    });
    return best;
  }
  // 本步要操作的元件:自动选中它,并在画布上一直高亮(配合"点这里调参数/点这里开关")
  function learnPickComponent(st) {
    const want = st && st.pick;
    if (!want || !learnOn) { state.learnPick = null; return; }
    const c = state.components.filter(function (x) { return x.type === want; })[0];
    if (!c) { state.learnPick = null; return; }
    state.learnPick = c.id;
    state.selected = { kind: 'component', id: c.id };
    wantInspectorScroll = true;              // 学习点名 → 这一步要调参数,带进视野
    state.selectedIds = [c.id];
    state.flash = { id: c.id, t: 0 };
    state.dirty = true;
    renderInspector();
  }
  function learnSetNote() {
    const st = LEARN_STEPS[learnIdx];
    // 每进入一步都把这些"做过了"的标记清零:只反映"本步之内做过没有",
    // 否则上一步/上一次学习留下的旧标记会让这一步一到就自己跳过去。
    state.learnMoved = state.learnPresetLoaded = state.learnPropTouched = false;
    state.learnRotated = state.learnDeleted = state.learnUndone = false;
    state.learnLibDone = false;
    learnPickComponent(st);
    const pos = learnNotePlace();
    const noteText = (layoutMode === 'mobile' && st.noteMobile) ? st.noteMobile : st.note;
    state.notes = noteText
      ? [{ id: 'learn-note', x: pos.x, y: pos.y, w: 380, text: noteText }]
      : [];
    state.dirty = true;
  }
  // 提示气泡:跟着某一步指定的元素走(例如图鉴右上角的关闭键)
  function learnTipTo(st) {
    let tipEl = document.getElementById('learnTip');
    if (!tipEl) {
      tipEl = document.createElement('div');
      tipEl.id = 'learnTip';
      document.body.appendChild(tipEl);
    }
    const text = st && st.tip;
    if (!text || !learnOn || !st.tipSel) { setElClass(tipEl, 'on', false); return; }
    let el = null;
    try { el = document.querySelector(st.tipSel); } catch (e) { el = null; }
    if (!el) { setElClass(tipEl, 'on', false); return; }
    const cs = window.getComputedStyle ? window.getComputedStyle(el) : null;
    const r = el.getBoundingClientRect();
    // 目标不可见(比如图鉴还没打开)就先不显示
    if (!r || r.width < 2 || r.height < 2 || (cs && (cs.display === 'none' || cs.visibility === 'hidden'))) {
      setElClass(tipEl, 'on', false);
      return;
    }
    tipEl.textContent = text;
    setElClass(tipEl, 'on', true);
    const tw = tipEl.offsetWidth || 180, th = tipEl.offsetHeight || 34;
    let left = r.left - tw - 12;                 // 默认放在目标左侧
    if (left < 8) left = Math.max(8, r.right + 12);   // 左边放不下就放右侧
    const top = Math.min(Math.max(8, r.top + r.height / 2 - th / 2), (window.innerHeight || 800) - th - 8);
    tipEl.style.left = left + 'px';
    tipEl.style.top = top + 'px';
  }
  function learnHighlight() {
    document.querySelectorAll('.learn-hl').forEach(el => setElClass(el, 'learn-hl', false));
    if (!document.querySelector) return;
    // target 可以是选择器,也可以是选择器数组(例如"演示电路"按钮 + 菜单里的「基本电路」)
    const st = LEARN_STEPS[learnIdx] || {};
    // 手机端可以用 targetMobile 指定专门的高亮对象;显式给空串表示"手机端不高亮"
    const hasMobileTarget = Object.prototype.hasOwnProperty.call(st, 'targetMobile');
    const sel = (layoutMode === 'mobile' && hasMobileTarget) ? st.targetMobile : st.target;
    if (!sel) return;
    const list = Array.isArray(sel) ? sel : [sel];
    // 手机端:如果这一步要点的按钮在"底部功能栏"里(#mBtn*),而当前正选中元件
    // (此时底部栏被操作条替换、功能按钮被藏起来),就先取消选中,让按钮露出来。
    if (layoutMode === 'mobile' && state.selectedIds.length &&
        list.some(function (one) { return typeof one === 'string' && one.indexOf('#mBtn') === 0; }) &&
        !list.some(function (one) { return typeof one === 'string' && one.indexOf('#mAct') === 0; })) {
      clearSelection();
      renderInspector();
    }
    list.forEach(function (one) {
      let el = null;
      try { el = document.querySelector(one); } catch (e) { el = null; }
      if (el) setElClass(el, 'learn-hl', true);
    });
    learnTipTo(st);
    // 需要拖动的那个参数滑块也高亮(面板每次重绘后都会重新调用本函数,所以不会丢)
    if (st.pickProp) {
      let row = null;
      try { row = document.querySelector('#inspector [data-field="' + st.pickProp + '"]'); } catch (e) { row = null; }
      if (row) setElClass(row, 'learn-hl', true);
    }
  }
  // 手机端没有注解按钮,标了 desktopOnly 的步骤直接跳过
  function learnSkipped(st) { return !!(st && st.desktopOnly && layoutMode === 'mobile'); }
  function learnStepList() { return LEARN_STEPS.filter(function (st) { return !learnSkipped(st); }); }
  function learnNextIdx(from) {
    let i = from + 1;
    while (i < LEARN_STEPS.length && learnSkipped(LEARN_STEPS[i])) i++;
    return i;
  }
  function learnPrevIdx(from) {
    let i = from - 1;
    while (i > 0 && learnSkipped(LEARN_STEPS[i])) i--;
    return i;
  }
  function renderLearn() {
    const s = LEARN_STEPS[learnIdx] || LEARN_STEPS[0];
    const visList = learnStepList();
    const pos = Math.max(1, visList.indexOf(s) + 1);
    if (learnBody) {
      learnBody.innerHTML = '<div class="learn-step">第 ' + pos + ' / ' + visList.length + ' 步</div>' +
        '<h3>' + s.t + '</h3><p>' + s.d + '</p>';
    }
    if (learnOverlay) setElClass(learnOverlay, 'docked', learnOn);
    if (learnBar) {
      learnBar.innerHTML = '<span class="learn-dots">' +
        LEARN_STEPS.map(function (st, i) {
          if (learnSkipped(st)) return '';
          return '<i class="' + (i === learnIdx ? 'on' : '') + '"></i>';
        }).join('') + '</span>';
    }
    const prev = document.getElementById('learnPrev');
    const next = document.getElementById('learnNext');
    if (prev) {
      prev.disabled = learnIdx <= 0;
      prev.textContent = (layoutMode === 'mobile') ? '上一步' : '← 上一步';
    }
    if (next) {
      // 手机端用短文案,避免按钮挤出行外
      const mobile = (layoutMode === 'mobile');
      const lastVisible = learnNextIdx(learnIdx) >= LEARN_STEPS.length;
      next.textContent = (learnIdx === 0 && !learnOn) ? (mobile ? '开始学习' : '开始学习 →')
        : (lastVisible ? (mobile ? '完成' : '完成 ✓')
          : (mobile ? '下一步' : '下一步 →'));
    }
    if (learnOn && learnSkipped(LEARN_STEPS[learnIdx])) {   // 当前端看不到这一步 → 自动挪到下一个可见步
      const nx2 = learnNextIdx(learnIdx);
      learnIdx = (nx2 < LEARN_STEPS.length) ? nx2 : learnPrevIdx(learnIdx);
    }
    if (learnOn) { learnSetNote(); learnHighlight(); }
    syncLearnBarForSheet();
  }
  function learnEnter() {
    if (learnOn) return;
    learnOn = true;
    state.learnOn = true;      // 同步到 state,供 resize 判断
    learnSaved = {
      snap: captureSnapshot(),
      undo: undoStack.slice(), redo: redoStack.slice(),
      view: { tx: view.tx, ty: view.ty, zoom: view.zoom, scale: view.scale }
    };
    // 全新画布
    withoutHistory(() => {
      state.components = []; state.wires = []; state.notes = [];
      state.selected = null; state.selectedIds = []; state.drag = null;
      state.learnMoved = state.learnPresetLoaded = state.learnPropTouched = false;
      state.learnRotated = state.learnDeleted = state.learnUndone = false;
      state.learnLibDone = false;
      state.idSeq = state.idSeq;    // 保持 id 单调,避免与已有元件冲突
    });
    undoStack.length = 0; redoStack.length = 0;
    updateHistoryButtons();
    state.dirty = true;
    // 空画布用固定 100%,否则 fitView 会放大到极限、画布上的注解字会巨大
    view.zoom = 1;
    applyZoom();
    view.tx = (canvas.clientWidth || 800) / 2 - 300 * view.scale;
    view.ty = (canvas.clientHeight || 480) / 2 - 300 * view.scale;
  }
  function learnExit() {
    if (!learnOn) { if (learnOverlay) learnOverlay.hidden = true; setBodyFlag('lib-open', false); return; }
    learnOn = false;
    state.learnOn = false;
    state.learnPick = null;
    document.querySelectorAll('.learn-hl').forEach(el => setElClass(el, 'learn-hl', false));
    const tipElOff = document.getElementById('learnTip');
    if (tipElOff) setElClass(tipElOff, 'on', false);
    if (learnSaved) {
      withoutHistory(() => restoreSnapshot(learnSaved.snap));
      undoStack.length = 0; redoStack.length = 0;
      learnSaved.undo.forEach(x => undoStack.push(x));
      learnSaved.redo.forEach(x => redoStack.push(x));
      view.tx = learnSaved.view.tx; view.ty = learnSaved.view.ty;
      view.zoom = learnSaved.view.zoom; view.scale = learnSaved.view.scale;
      learnSaved = null;
    }
    updateHistoryButtons();
    state.dirty = true;
    renderInspector();
    if (learnOverlay) { learnOverlay.hidden = true; setElClass(learnOverlay, 'docked', false); }
    setBodyFlag('lib-open', false);
  }
  function learnAdvance() {
    // 第 1 屏是"确认进入":在这里才真正进入学习并停靠到画布左下角
    if (learnIdx === 0 && !learnOn) {
      learnEnter();
      setElClass(learnOverlay, 'docked', true);
      learnIdx = 1;
      renderLearn();
      showToast('已进入操作学习:原来的电路会在退出时自动恢复');
      Sound.click(0.5);
      return;
    }
    const nx = learnNextIdx(learnIdx);
    if (nx >= LEARN_STEPS.length) { learnExit(); showToast('操作学习完成,原电路已恢复'); return; }
    learnIdx = nx;
    learnSettle = 0;                    // 换步重置"停留"计数
    // 换步时收起手机端抽屉,保证每一步都能看清画布
    if (layoutMode === 'mobile' && sheetOpenKind) closeSheet();
    renderLearn();
    Sound.click(0.5);
  }
  // 做到就自动下一步(每 400ms 检查一次)
  function learnTick() {
    if (!learnOn) return;
    if (learnHold > 0) { learnHold--; return; }        // 刚退回上一步,先别自动前进
    const s = LEARN_STEPS[learnIdx];
    if (!(s && typeof s.check === 'function' && s.check(state))) { learnSettle = 0; return; }
    // 做到了也别立刻跳走:按该步的 hold 再停留几拍,参数窗口才有时间看清
    const need = (typeof s.hold === 'number') ? s.hold : 2;   // 默认停留 2 拍(约 0.8 秒)看清结果
    if (learnSettle < need) { learnSettle++; return; }
    learnAdvance();
  }
  // 后退一步:同时把刚才的动作静默撤销,并把"做过了"的标记清掉,避免立刻又被推回来
  function learnBack() {
    if (learnIdx <= 0) return;
    learnIdx = learnPrevIdx(learnIdx);
    learnSettle = 0;
    if (learnIdx <= 0) return;
    learnHold = 6;                                   // 约 2.4 秒内不自动前进
    state.learnMoved = state.learnPresetLoaded = state.learnPropTouched = false;
    state.learnRotated = state.learnDeleted = state.learnUndone = false;
    try { doUndo(); } catch (e) { }
    renderLearn();
    Sound.click(0.35);
  }
  {
    const bl = document.getElementById('btnLearn');
    if (bl) bl.addEventListener('click', function () {
      learnIdx = 0;                        // 先只弹出确认窗口,用户点「开始学习」才真正进入
      if (learnOverlay) { learnOverlay.hidden = false; setBodyFlag('lib-open', true); }
      setElClass(learnOverlay, 'docked', false);
      renderLearn();
      Sound.click(0.5);
    });
    const bc = document.getElementById('learnClose');
    if (bc) bc.addEventListener('click', learnExit);
    const bp = document.getElementById('learnPrev');
    if (bp) bp.addEventListener('click', learnBack);
    const bn = document.getElementById('learnNext');
    if (bn) bn.addEventListener('click', learnAdvance);
  }

  /* 注解模式开关 */
  const btnAnnotateEl = document.getElementById('btnAnnotate');
  if (btnAnnotateEl) {
    btnAnnotateEl.addEventListener('click', function () {
      state.annotate = !state.annotate;
      setElClass(btnAnnotateEl, 'on', state.annotate);
      showToast(state.annotate ? '注解模式:点画布空白处添加说明框(右键说明框可删除)' : '已退出注解模式');
    });
  }
  const btnDelSelEl = document.getElementById('btnDelSel');
  if (btnDelSelEl) {
    btnDelSelEl.addEventListener('click', function () {
      if (state.selectedIds.length > 1) { deleteSelection(); return; }
      if (state.selectedIds.length === 1) { deleteComponent(state.selectedIds[0]); return; }
      if (state.selected && state.selected.kind === 'wire') {
        pushUndo('删除导线');
        state.wires.splice(state.selected.index, 1);
        state.selected = null; state.dirty = true; renderInspector(); return;
      }
      showToast('先点一下要删除的元件(也可以右键元件直接删)');
    });
  }
  const btnUndoEl = document.getElementById('btnUndo');
  if (btnUndoEl) btnUndoEl.addEventListener('click', () => doUndo());
  const btnRedoEl = document.getElementById('btnRedo');
  if (btnRedoEl) btnRedoEl.addEventListener('click', () => doRedo());
  updateHistoryButtons();
  document.getElementById('btnClear').addEventListener('click', () => {
    pushUndo('清空画布');
    state.components = []; state.wires = []; state.selected = null; state.drag = null;
    state.notes = [];
    state.dirty = true; renderInspector();
  });
  document.getElementById('btnZoomIn').addEventListener('click', () => setZoom(view.zoom * 1.25));
  document.getElementById('btnZoomOut').addEventListener('click', () => setZoom(view.zoom / 1.25));
  document.getElementById('btnZoomFit').addEventListener('click', () => {
    fitView();
  });
  // 音效开关
  const btnSound = document.getElementById('btnSound');
  function updateSoundBtn() {
    // 窄屏只显示图标,宽屏显示完整文字(由 CSS 决定显示哪一个)
    btnSound.innerHTML = '<span class="icg">' + (Sound.isEnabled() ? '🔊' : '🔇') + '</span>' +
      '<span class="lbl" id="lblSound">音效' + (Sound.isEnabled() ? '开' : '关') + '</span>';
    btnSound.className = Sound.isEnabled() ? 'on' : '';
  }
  btnSound.addEventListener('click', () => {
    Sound.resume();
    Sound.setEnabled(!Sound.isEnabled());
    updateSoundBtn();
    if (Sound.isEnabled()) Sound.click(0.6);
  });
  updateSoundBtn();
  // ---------- 暗色 / 亮色主题 ----------
  const btnTheme = document.getElementById('btnTheme');
  function applyTheme(name) {
    view.theme = name;
    const isDark = (name === 'dark');
    setBodyFlag('dark', isDark);        // 只增删 dark,不影响 mobile 等其他标记
    Object.assign(COL, THEMES[isDark ? 'dark' : 'light']);
    if (btnTheme) {
      btnTheme.innerHTML = '<span class="icg">' + (isDark ? '☀️' : '🌙') + '</span>' +
      '<span class="lbl" id="lblTheme">' + (isDark ? '亮色' : '暗色') + '</span>';
    }
    const meta = document.querySelector ? document.querySelector('meta[name="theme-color"]') : null;
    if (meta) meta.setAttribute('content', isDark ? '#0e1726' : '#12305a');
    try {
      if (window.localStorage) window.localStorage.setItem('circuitLab.theme', name);
    } catch (e) { }
  }
  function readSavedTheme() {
    try { return window.localStorage ? window.localStorage.getItem('circuitLab.theme') : null; } catch (e) { return null; }
  }
  if (btnTheme) {
    btnTheme.addEventListener('click', () => {
      applyTheme(view.theme === 'dark' ? 'light' : 'dark');
      Sound.click(0.5);
    });
  }
  // 优先用上次保存的选择;第一次访问则跟随系统设置
  const savedTheme = readSavedTheme();
  let prefersDark = false;
  try { prefersDark = !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); } catch (e) { }
  applyTheme(savedTheme === 'dark' || savedTheme === 'light' ? savedTheme : (prefersDark ? 'dark' : 'light'));

  // 浏览器要求先有用户操作才允许播放声音
  canvas.addEventListener('pointerdown', () => Sound.resume());
  window.addEventListener('pointerdown', () => Sound.resume(), { once: true });
  // 操作说明:宽屏(两栏布局)默认展开,窄屏/手机默认收起,把"添加元件"顶到最前面
  const hintCard = document.getElementById('hintCard');
  if (hintCard) {
    hintCard.open = (window.innerWidth || 1000) >= 1080 || layoutMode === 'mobile';   // 手机版默认展开,方便看操作提示
    try {
      const saved = window.localStorage && window.localStorage.getItem('circuitLab.hintOpen');
      if (saved === '1') hintCard.open = true;
      else if (saved === '0') hintCard.open = false;
      hintCard.addEventListener('toggle', () => {
        try { window.localStorage.setItem('circuitLab.hintOpen', hintCard.open ? '1' : '0'); } catch (e) { }
      });
    } catch (e) { }
  }
  document.querySelectorAll('[data-preset]').forEach(btn => {
    btn.addEventListener('click', () => {
      loadPreset(btn.dataset.preset);
      // 手机端:选完演示电路就把抽屉收起来,否则它会一直盖在画布上
      if (layoutMode === 'mobile' && sheetOpenKind) closeSheet();
    });
  });

  // 手机端学习条里的元件栏:与右侧「添加元件」用同一套动作
  // 关卡模式下这里是"器材篮子":只显示本关给定的器材(带数量),用完提示
  const paletteQuick = document.getElementById('paletteQuick');
  function buildPalette() {
    if (!paletteQuick) return;
    try { paletteQuick.innerHTML = ''; } catch (e) { }        // 清空旧按钮(真实 DOM)
    let guard = 500;                                          // 兜底移除 + 护栏:任何环境都不会死循环
    while (paletteQuick.children && paletteQuick.children.length && guard-- > 0) {
      paletteQuick.removeChild(paletteQuick.children[0]);
    }
    const lv = state.level ? examLevelById(state.level.id) : null;
    const items = [];
    if (lv) {
      (lv.level.gear || []).forEach(gi => items.push({ type: gi.type, n: gi.n, free: !!gi.free }));
      // 接线点只在关卡显式声明(gear 里有 junction:free)时才出现,避免凭空冒出学生看不懂的"接线点"
    } else {
      PALETTE.forEach(item => items.push({ type: item.type }));
    }
    // 显示"剩余数":拿走一个就减 1;全部拿完(free 除外)置灰
    items.forEach(it => {
      const item = PALETTE.find(x => x.type === it.type);
      if (!item) return;
      const placed = it.free ? 0 : state.components.filter(c => c.type === it.type).length;
      const remain = it.free ? null : (it.n - placed);
      const empty = !it.free && remain <= 0;
      const b = document.createElement('button');
      b.dataset.type = it.type;
      if (empty) b.disabled = true;
      b.innerHTML = '<span class="glyph">' + item.glyph + '</span>' + item.name +
        (it.free ? '<small>不限量</small>' : (it.n > 1 ? '<small class="rem">剩 ' + remain + '</small>' : (remain >= 0 ? '<small class="rem">剩 ' + remain + '</small>' : '')));
      b.addEventListener('click', () => {
        const n = state.components.length;
        addComp(it.type, 260 + (n % 4) * 140, 180 + Math.floor(n / 4) * 110);
      });
      paletteQuick.appendChild(b);
    });
  }
  // 刷新器材栏的灰态/剩余数(不改结构,避免重建)—— 添加/删除/撤销后调用
  function refreshPalette() {
    const lv = state.level ? examLevelById(state.level.id) : null;
    if (!paletteQuick || !lv) return;
    const btns = paletteQuick.children;
    for (let i = 0; i < btns.length; i++) {
      const b = btns[i];
      const t = b.dataset.type;
      const gi = (lv.level.gear || []).find(g => g.type === t);
      if (!gi || gi.free) continue;
      const placed = state.components.filter(c => c.type === t).length;
      const remain = gi.n - placed;
      const rem = b.querySelector('.rem');
      if (rem) rem.textContent = '剩 ' + Math.max(remain, 0);
      b.disabled = remain <= 0;
    }
  }
  buildPalette();

  elInspector.addEventListener('input', ev => {
    state.learnPropTouched = true;
    const inp = ev.target;
    if (inp.tagName !== 'INPUT') return;
    const c = compById(state.selected && state.selected.id);
    if (!c) return;
    const prop = inp.dataset.prop;
    const propNames = { V: '电压', Vf: '导通压降', r: '内阻', R: '阻值', Imax: '额定电流', L: '长度', S: '横截面积' };
    pushUndo('调整' + (propNames[prop] || '参数'), 'prop:' + c.id + ':' + prop);
    c.props[prop] = Number(inp.value);
    const units = { V: ' V', Vf: ' V', r: ' Ω', R: ' Ω', Imax: ' A', L: ' m', S: ' mm²' };
    const unit = units[prop] || '';
    const lab = document.getElementById('fv_' + prop);
    if (lab) lab.textContent = inp.value + unit;
    state.dirty = true;
    // 拖动长度/粗细时原地更新算得的电阻,避免重建面板打断拖动
    if (prop === 'L' || prop === 'S') {
      const calc = document.getElementById('fv_calc');
      if (calc) calc.textContent = fmtOhm(resistanceOf(c));
    }
  });
  elInspector.addEventListener('click', ev => {
    const act = ev.target.dataset && ev.target.dataset.act;
    if (!act) return;
    // 批量操作:不依赖单个选中元件
    if (act === 'rotateSel') { rotateSelection(90); return; }
    if (act === 'rotateSel180') { rotateSelection(180); return; }
    if (act === 'deleteSel') { deleteSelection(); return; }
    if (act === 'selectAll') { selectAllComponents(); return; }
    if (act === 'clearSel') { clearSelection(); renderInspector(); return; }
    const c = compById(state.selected && state.selected.id);
    if (!c) return;
    if (act === 'toggleSwitch') {
      pushUndo('切换开关');
      c.props.closed = !c.props.closed;
      state.dirty = true;
      Sound.click(c.props.closed ? 1 : 0.8);
      renderInspector();
    }
    if (act === 'setMat') {
      pushUndo('更换导体材料');
      c.props.material = ev.target.dataset.mat;
      state.dirty = true;
      Sound.click(0.5);
      renderInspector();
    }
    if (act === 'setMeterRange') {
      const v = parseFloat(ev.target.dataset.val);
      if ((c.type === 'ammeter' || c.type === 'voltmeter') && isFinite(v) && v !== meterRange(c)) {
        pushUndo('改接量程');                    // 两档互斥:改一个,另一个自动"灭"
        c.props.range = v;
        state.dirty = true;
        Sound.click(0.5);
        renderInspector();
      }
      return;
    }
    if (act === 'toggleIdealMeter') {
      if (c.type !== 'ammeter' && c.type !== 'voltmeter') return;
      pushUndo(c.props.ideal ? '改回实际电表' : '改为理想电表');
      c.props.ideal = !c.props.ideal;
      state.dirty = true;
      Sound.click(0.5);
      renderInspector();
      return;
    }
    if (act === 'rotate90') rotateComponent(c, 90);
    if (act === 'rotate180') rotateComponent(c, 180);
    if (act === 'replaceFuse') { pushUndo('更换保险丝'); c.props.broken = false; state.dirty = true; renderInspector(); }
    if (act === 'replaceBulb') {
      pushUndo('更换灯泡');
      c.props.burned = false;
      c.props._hot = 0;                      // 倒计时也清零
      state.dirty = true; renderInspector(); showToast('已换上新的灯泡');
    }
    if (act === 'del') deleteComponent(c.id);
  });

  /* ---------- 无限画布:视口变换(世界坐标 → 屏幕坐标) ----------
     screen = world * scale + (tx, ty)   —— 画布本身不再有边界,
     元件可以放在任意位置,靠平移 + 缩放调整显示范围。 */
  function worldToScreen(wx, wy) { return { x: wx * view.scale + view.tx, y: wy * view.scale + view.ty }; }
  function screenToWorld(sx, sy) { return { x: (sx - view.tx) / view.scale, y: (sy - view.ty) / view.scale }; }
  function applyZoom() {
    const dpr = window.devicePixelRatio || 1;
    view.scale = view.baseScale * view.zoom;         // CSS 像素 / 世界单位
    view.dpr = dpr;
    const cssW = Math.max(240, wrap.clientWidth || 800);
    const cssH = Math.max(180, wrap.clientHeight || 480);
    canvas.style.display = 'block';                  // 脚本就绪后才显示画布
    canvas.style.width = cssW + 'px';
    canvas.style.height = cssH + 'px';
    canvas.width = Math.max(1, Math.round(cssW * dpr));
    canvas.height = Math.max(1, Math.round(cssH * dpr));
    if (elZoomLabel) elZoomLabel.textContent = Math.round(view.zoom * 100) + '%';
  }
  // 画布可见的世界矩形
  function visibleWorld() {
    const w = canvas.clientWidth || wrap.clientWidth || 800;
    const h = canvas.clientHeight || wrap.clientHeight || 480;
    const a = screenToWorld(0, 0), b = screenToWorld(w, h);
    return { x0: a.x, y0: a.y, x1: b.x, y1: b.y, w: b.x - a.x, h: b.y - a.y };
  }
  // 所有元件(含导线端点)的世界包围盒
  function contentBounds() {
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    state.components.forEach(c => {
      const b = bounds(c);
      x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y);
      x1 = Math.max(x1, b.x + b.w); y1 = Math.max(y1, b.y + b.h);
    });
    state.wires.forEach(w => {
      const ca = compById(w.a.cid), cb = compById(w.b.cid);
      if (!ca || !cb) return;
      const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
      x0 = Math.min(x0, pa.x, pb.x); y0 = Math.min(y0, pa.y, pb.y);
      x1 = Math.max(x1, pa.x, pb.x); y1 = Math.max(y1, pa.y, pb.y);
    });
    if (!isFinite(x0)) return { x: 0, y: 0, w: 600, h: 400 };
    return { x: x0, y: y0, w: Math.max(60, x1 - x0), h: Math.max(60, y1 - y0) };
  }
  // 把整个电路缩放并居中显示("适应窗口")
  function fitView(pad) {
    pad = pad === undefined ? 36 : pad;
    const b = contentBounds();
    const cssW = canvas.clientWidth || wrap.clientWidth || 800;
    const cssH = canvas.clientHeight || wrap.clientHeight || 480;
    const s = Math.min((cssW - pad * 2) / b.w, (cssH - pad * 2) / b.h);
    view.baseScale = Math.max(0.02, Math.min(4, s));
    view.zoom = 1;
    view.scale = view.baseScale;
    view.tx = (cssW - b.w * view.scale) / 2 - b.x * view.scale;
    view.ty = (cssH - b.h * view.scale) / 2 - b.y * view.scale;
    applyZoom();
  }
  function resize() {
    // 缩略图:画布尺寸变了以后把它夹回可视范围内(拖动过才有 pos)
    try { if (mmBox && typeof mmApplyPos === 'function') mmApplyPos(); } catch (e) { }
    // 手机版:让画布吃掉"底部操作栏之上"的所有剩余高度
    if (layoutMode === 'mobile' && wrap) {
      const top = wrap.getBoundingClientRect().top;
      const bar = (mbarEl && mbarEl.offsetHeight) ? mbarEl.offsetHeight : 58;
      const hintEl = document.getElementById('mHint');
      const palH = 0;      // 手机端底部常驻元件栏已移除(会挡手),此项恒为 0
      const hintOn = !!(hintEl && hintEl.className.indexOf('off') < 0);
      const hintH = hintOn ? (hintEl.offsetHeight || 26) : 0;
      if (hintEl) { hintEl.style.bottom = (bar + palH) + 'px'; hintEl.style.display = hintOn ? 'flex' : 'none'; }
      // 学习条要停在"整个底部栈"之上:把它需要的留白写进 CSS 变量(提示条收起来时会自动落下)
      try {
        if (document.documentElement && document.documentElement.style) {
          document.documentElement.style.setProperty('--mstack', (bar + palH + hintH + 10) + 'px');
        }
      } catch (e) { }
      const h = Math.max(240, (window.innerHeight || 700) - top - bar - palH - hintH - 14);
      wrap.style.height = h + 'px';
    } else if (wrap) {
      // 电脑版:画布铺满窗口剩余高度——不留大片空白,也不产生整页滚动条。
      // 做法:先估一个高度,再按"整页实际高度与窗口之差"迭代贴合;
      // 右侧栏限高到与画布同高(内容超出则内部滚动),这样页面高度只由画布决定。
      const innerH = window.innerHeight || 700;
      const absTop = wrap.getBoundingClientRect().top + (window.scrollY || window.pageYOffset || 0);
      // 画布底边贴到窗口底部上方 18px:把下方的空白全部利用起来
      // 底部操作条占了画布下方一块,画布高度要把它扣掉
      const bottomBar = document.querySelector ? document.querySelector('.group-bottom') : null;
      const barH = (bottomBar && bottomBar.offsetHeight) ? bottomBar.offsetHeight + 20 : 0;
      const h = Math.max(300, innerH - absTop - 18 - barH);
      wrap.style.height = h + 'px';
    }
    applyZoom();
    // 未手动缩放时始终适应窗口;但学习模式用的是空画布,fitView 会放大到极限,所以跳过
    if (!state.learnOn && Math.abs(view.zoom - 1) < 1e-6) fitView();
  }
  // 以某个屏幕点为焦点缩放(不传则以画布中心为焦点)
  function setZoom(z, cx, cy) {
    z = Math.max(0.1, Math.min(10, z));
    const r = canvas.getBoundingClientRect();
    const px = (cx === undefined) ? r.width / 2 : (cx - r.left);
    const py = (cy === undefined) ? r.height / 2 : (cy - r.top);
    const before = screenToWorld(px, py);            // 光标下的世界点
    view.zoom = z;
    view.scale = view.baseScale * view.zoom;
    const after = worldToScreen(before.x, before.y);
    view.tx += px - after.x;                         // 让该世界点保持在光标下
    view.ty += py - after.y;
    applyZoom();
  }
  // 平移(屏幕像素增量)
  function panBy(dxPx, dyPx) { view.tx += dxPx; view.ty += dyPx; }
  window.addEventListener('resize', () => {
    // 只在"识别结果真的变了"时才重新应用布局:
    // 手机上地址栏伸缩会频繁触发 resize,若无条件重设会把打开的抽屉收起来
    if (!readLayoutMode()) {
      const m = detectLayoutMode();
      if (m !== layoutMode) applyLayoutMode(m, false);
    }
    resize();
  });
  if (window.addEventListener && window.visualViewport) {
    window.visualViewport.addEventListener('resize', resize);
  }
  window.addEventListener('orientationchange', () => { setTimeout(resize, 260); });
  // 首次渲染后再校正一次(部分手机浏览器初次布局尺寸不准)
  setTimeout(resize, 300);
  canvas.addEventListener('wheel', ev => {
    if (!ev.ctrlKey && !ev.metaKey) return;                 // Ctrl/⌘ + 滚轮 = 缩放,否则正常翻页
    ev.preventDefault();
    setZoom(view.zoom * Math.exp(-ev.deltaY * 0.0022), ev.clientX, ev.clientY);
  }, { passive: false });
  canvas.addEventListener('pointermove', ev => {
    state.mouse = toLocal(ev);
    mouseStale = false;
    // 按住接线柱后明显移动 → 取消长按(按"拖动元件"处理)
    if (state.termPress) {
      const tol = TERM_HOLD_PX_SCREEN / Math.max(0.2, view.scale);
      if (Math.hypot(state.mouse.x - state.termPress.sx, state.mouse.y - state.termPress.sy) > tol) {
        state.termPress.moved = true;               // 先记下"移动过",再取消长按
        clearTermPress();
      }
    }
    /* 接线模式下实时计算"即将插入接线点"的位置(松手/点击才真正放置),
       由渲染负责画半透明呼吸小点。放在 pointermove 里算,和点击流程用同一套函数。 */
    if (state.wireMode) {
      const htNow = hitTerminal(state.mouse, termSlackPx());
      if (htNow) {
        state.wireHover = null;
      } else {
        const wi = hitWireTol(state.mouse, hitRadiusScreen(isTouchLike() ? 30 : 14));
        const pr = wi >= 0 ? projOnWire(wi, state.mouse) : null;
        state.wireHover = pr ? { wi: wi, x: pr.x, y: pr.y } : null;
      }
    } else {
      state.wireHover = null;
    }
    if (state.noteResize) {
      const nr = state.noteResize;
      const ntR = (state.notes || []).filter(x => x.id === nr.id)[0];
      if (ntR) {
        const q = toLocal(ev);
        ntR.w = Math.max(150, Math.min(900, Math.round((nr.w0 + (q.x - nr.startX)) / 10) * 10));
        state.dirty = true;
      }
    }
    if (state.noteDrag) {
      const nt = (state.notes || []).filter(x => x.id === state.noteDrag.id)[0];
      if (nt) {
        const q = toLocal(ev);
        nt.x = Math.round((q.x - state.noteDrag.dx) / 10) * 10;
        nt.y = Math.round((q.y - state.noteDrag.dy) / 10) * 10;
        state.noteDrag.moved = true;
        state.dirty = true;
      }
    }                     // 指针还活着:两段式连线的虚线预览可以跟着走
    if (state.drag && state.drag.mode === 'pan' && state.drag.moved) canvas.style.cursor = 'grabbing';
    else if (!state.drag) {
      const pm = toLocal(ev);
      const hn = hitNote(pm);
      canvas.style.cursor = (hn && hitNoteGrip(hn, pm)) ? 'nwse-resize'
        : (hitComponent(pm) ? 'move' : 'default');
    }
  });

  function line(x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); }

  // 当前可见网格的世界步长:画网格与"松手吸附"都用它,吸附永远对齐看得见的格子
  function currentGridStep() {
    let step = 20;
    while (step * view.scale < 9) step *= 5;
    while (step * view.scale > 90) step /= 5;
    return step;
  }
  // 无限网格:只画可见范围内的线,密度随缩放自适应
  function drawGrid() {
    const v = visibleWorld();
    ctx.fillStyle = COL.canvasBg;
    ctx.fillRect(v.x0, v.y0, v.w, v.h);
    const step = currentGridStep();
    const x0 = Math.floor(v.x0 / step) * step, x1 = v.x1;
    const y0 = Math.floor(v.y0 / step) * step, y1 = v.y1;
    ctx.lineWidth = 1 / view.scale;
    for (let x = x0; x <= x1; x += step) {
      ctx.strokeStyle = (Math.abs(x % (step * 5)) < 1e-6) ? COL.gridBold : COL.grid;
      line(x, v.y0, x, v.y1);
    }
    for (let y = y0; y <= y1; y += step) {
      ctx.strokeStyle = (Math.abs(y % (step * 5)) < 1e-6) ? COL.gridBold : COL.grid;
      line(v.x0, y, v.x1, y);
    }
  }

  function drawWires(s) {
    state.wires.forEach(w => {
      const ca = compById(w.a.cid), cb = compById(w.b.cid);
      if (!ca || !cb) return;
      const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
      const selected = state.selected && state.selected.kind === 'wire' && state.wires[state.selected.index] === w;
      ctx.lineCap = 'round';
      ctx.strokeStyle = selected ? '#ff9d2e' : COL.wire;
      ctx.lineWidth = selected ? 6 : 4;
      line(pa.x, pa.y, pb.x, pb.y);
    });
  }

  function drawCurrentDots(s) {
    if (!s || !s.flows) return;
    const speedBase = 34, perAmp = 200;
    // 箭头大小按屏幕像素换算,保证任何缩放下都看得清方向
    const size = Math.max(6, Math.min(60, 13 / view.scale));
    const gap = size * 2.7;
    state.wires.forEach((w, i) => {
      const f = s.flows[i] || 0;
      if (Math.abs(f) < 2e-4) return;
      const ca = compById(w.a.cid), cb = compById(w.b.cid);
      if (!ca || !cb) return;
      const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
      const dx = pb.x - pa.x, dy = pb.y - pa.y;
      const len = Math.hypot(dx, dy);
      if (len < 12) return;
      const ux = dx / len, uy = dy / len;
      const dir = f > 0 ? 1 : -1;                       // 电流沿 a→b 为正
      const dxu = ux * dir, dyu = uy * dir;             // 电流方向的单位向量(箭头就指这边)
      const nx = -dyu, ny = dxu;                        // 法线(箭头宽度方向)
      const speed = speedBase + Math.min(240, Math.abs(f) * perAmp);
      // 弱电流淡入:电流越小箭头越透明,避免"跨过某个阈值突然冒出来"
      const flowAlpha = Math.max(0, Math.min(1, Math.abs(f) / 5e-4));
      const margin = size * 1.15;
      const usable = len - margin * 2;
      if (usable < gap * 0.3) return;
      // 关键:一律从"电流上游端"往下游铺箭头,行进量随时间增大,
      // 这样箭头移动方向永远与箭头所指方向一致(否则就会出现"箭头倒着走")。
      const travel = ((s._t || 0) * speed) % gap;
      const shaft = size * 0.75, headLen = size * 0.95, halfW = size * 0.5;
      ctx.save();
      ctx.globalAlpha = flowAlpha;
      if (flowAlpha < 0.02) { ctx.restore(); return; }     // 几乎没电流就不画箭头
      ctx.lineCap = 'round';
      for (let d = travel; d <= usable; d += gap) {
        const t = dir > 0 ? (margin + d) : (len - margin - d);
        const x = pa.x + ux * t, y = pa.y + uy * t;
        const tipX = x + dxu * headLen, tipY = y + dyu * headLen;
        const tailX = x - dxu * shaft, tailY = y - dyu * shaft;
        const bx = tipX - dxu * headLen, by = tipY - dyu * headLen;   // 箭头底边中点
        ctx.beginPath();
        ctx.moveTo(tailX, tailY);
        ctx.lineTo(bx, by);
        ctx.strokeStyle = COL.current;
        ctx.lineWidth = Math.max(1.2, size * 0.22);
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(tipX, tipY);
        ctx.lineTo(bx + nx * halfW, by + ny * halfW);
        ctx.lineTo(bx - nx * halfW, by - ny * halfW);
        ctx.lineTo(tipX, tipY);
        ctx.fillStyle = COL.current;
        ctx.fill();
        ctx.strokeStyle = 'rgba(255,255,255,.55)';
        ctx.lineWidth = Math.max(0.8, size * 0.1);
        ctx.stroke();
      }
      ctx.restore();
    });
  }

  const FONT = '"Microsoft YaHei","PingFang SC",system-ui,sans-serif';
  function label(text, x, y, color, size, weight) {
    ctx.save();
    // 元件被旋转时,文字跟着走到新位置但保持正立(方便阅读)
    if (view.rot) { ctx.translate(x, y); ctx.rotate(-view.rot); ctx.translate(-x, -y); }
    ctx.fillStyle = color || COL.label;
    ctx.font = (weight || '500') + ' ' + (size || 12) + 'px ' + FONT;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(text, x, y);
    ctx.restore();
  }

  function drawComponent(c, s) {
    const x = c.x, y = c.y, info = s ? (s.info.get(c.id) || { I: 0, U: 0, P: 0 }) : { I: 0, U: 0, P: 0 };
    const rotRad = normRot(c) * Math.PI / 180;
    if (rotRad) { ctx.save(); ctx.translate(x, y); ctx.rotate(rotRad); ctx.translate(-x, -y); }
    view.rot = rotRad;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    const wire = COL.wire;
    if (c.type === 'battery') {
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 48, y, x - 14, y); line(x + 6, y, x + 48, y);
      ctx.strokeStyle = COL.comp;
      ctx.lineWidth = 8; line(x - 14, y - 12, x - 14, y + 12);      // 负极:短粗线
      ctx.lineWidth = 4; line(x + 6, y - 22, x + 6, y + 22);        // 正极:长细线
      label('-', x - 27, y - 20, COL.textFaint, 14, '700');
      label('+', x + 27, y - 20, COL.danger, 14, '700');
      label(tagOf(c) + '电池 ' + c.props.V + ' V', x, y + 34, COL.label, 12);
    } else if (c.type === 'switch') {
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 48, y, x - 18, y); line(x + 18, y, x + 48, y);
      ctx.fillStyle = COL.comp;
      ctx.beginPath(); ctx.arc(x - 18, y, 4.5, 0, Math.PI * 2); ctx.fill();
      ctx.beginPath(); ctx.arc(x + 18, y, 4.5, 0, Math.PI * 2); ctx.fill();
      ctx.strokeStyle = c.props.closed ? COL.ok : COL.danger;
      ctx.lineWidth = 5;
      if (c.props.closed) line(x - 18, y, x + 18, y);
      else line(x - 18, y, x + 13, y - 24);
      label(tagOf(c) + (c.props.closed ? '开关:闭合' : '开关:断开'), x, y + 32, c.props.closed ? COL.ok : COL.danger, 12, '600');
    } else if (c.type === 'bulb') {
      const burned = !!c.props.burned;
      const ratio = Math.max(0, info.P / (c.props.rated || 0.75));
      const glow = burned ? 0 : Math.min(1, ratio);
      // 过载角标:>1.2 倍显示 ⚠;进入"寿命倒计时"后转红并显示剩余秒数
      const hot = c.props._hot || 0;
      if (!burned && (ratio > 1.2 || hot > 0)) {
        ctx.save();
        ctx.translate(x + 30, y - 30);
        ctx.beginPath();
        ctx.moveTo(0, -11); ctx.lineTo(11, 9); ctx.lineTo(-11, 9); ctx.closePath();
        const dying = hot > 0;
        ctx.fillStyle = (ratio > 1.5 || dying) ? 'rgba(228,64,64,0.96)' : 'rgba(255,157,46,0.96)';
        ctx.fill();
        ctx.fillStyle = '#fff';
        ctx.font = '700 15px "Microsoft YaHei", sans-serif';
        ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
        ctx.fillText('!', 0, 3);
        ctx.restore();
        if (dying) {                                   // 倒计时:还剩多少秒烧断
          const left = Math.max(0, 1.6 - hot);
          label('⚠ ' + left.toFixed(1) + ' 秒后烧断', x, y - 46, COL.danger, 12, '700');
        }
      }
      if (glow > 0.02) {
        const g = ctx.createRadialGradient(x, y, 6, x, y, 52);
        g.addColorStop(0, 'rgba(255,220,120,' + (0.85 * Math.min(1, glow)) + ')');
        g.addColorStop(0.45, 'rgba(255,196,60,' + (0.35 * glow) + ')');
        g.addColorStop(1, 'rgba(255,190,60,0)');
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(x, y, 52, 0, Math.PI * 2); ctx.fill();
      }
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 38, y, x - 22, y); line(x + 22, y, x + 38, y);
      ctx.strokeStyle = COL.comp; ctx.lineWidth = 4;
      ctx.beginPath(); ctx.arc(x, y, 22, 0, Math.PI * 2); ctx.stroke();
      const d = 22 * Math.SQRT1_2;
      line(x - d, y - d, x + d, y + d); line(x - d, y + d, x + d, y - d);
      ctx.fillStyle = 'rgba(255,214,102,' + glow + ')';
      ctx.beginPath(); ctx.arc(x, y, 20, 0, Math.PI * 2); ctx.fill();
      label(tagOf(c) + '小灯泡 R=' + c.props.R + 'Ω', x, y + 46, COL.label, 12);
    } else if (c.type === 'resistor') {
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 48, y, x - 28, y); line(x + 28, y, x + 48, y);
      ctx.strokeStyle = COL.comp; ctx.lineWidth = 4;
      ctx.beginPath(); ctx.rect(x - 28, y - 12, 56, 24); ctx.stroke();
      ctx.fillStyle = COL.fill; ctx.fill();
      label(tagOf(c) + 'R=' + c.props.R + 'Ω', x, y + 30, COL.label, 12);
    } else if (c.type === 'rheostat') {
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 56, y, x - 34, y); line(x + 34, y, x + 56, y);
      ctx.strokeStyle = COL.comp; ctx.lineWidth = 4;
      ctx.beginPath(); ctx.rect(x - 34, y - 12, 68, 24); ctx.stroke();
      ctx.fillStyle = COL.fill; ctx.fill();
      // 滑片箭头
      const on = Math.abs(info.I) > 1e-4;
      ctx.strokeStyle = on ? COL.warn : COL.textFaint;
      ctx.lineWidth = 3.5;
      const ax = x + 4;
      line(ax + 14, y - 34, ax, y - 14);
      ctx.beginPath();
      ctx.moveTo(ax - 6, y - 19); ctx.lineTo(ax + 6, y - 19); ctx.lineTo(ax, y - 11);
      ctx.closePath(); ctx.fillStyle = on ? COL.warn : COL.textFaint; ctx.fill();
      label(tagOf(c) + '滑动变阻器 ' + c.props.R + 'Ω', x, y + 32, COL.label, 12);
    } else if (c.type === 'conductor') {
      const mat = materialOf(c);
      const Rc = resistanceOf(c);
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 58, y, x - 46, y); line(x + 46, y, x + 58, y);
      // 材料色带(颜色代表这种材料)
      ctx.fillStyle = mat.color;
      ctx.globalAlpha = 0.28;
      ctx.beginPath(); ctx.rect(x - 46, y - 15, 92, 30); ctx.fill();
      ctx.globalAlpha = 1;
      ctx.strokeStyle = COL.comp; ctx.lineWidth = 3.5;
      ctx.beginPath(); ctx.rect(x - 46, y - 15, 92, 30); ctx.stroke();
      // 导体内部不再画流动标记:导线上的橙色箭头已经画到导体两端,
      // 这里留给"材料名 / R 值"文字,避免叠字看不清。
      label(mat.name, x, y - 3, COL.text, 13, '700');
      label('R=' + fmtOhm(Rc), x, y + 10, '#465a7a', 11.5, '600');
      label('L=' + c.props.L + 'm  S=' + c.props.S + 'mm²', x, y + 30, COL.label, 11.5);
    } else if (c.type === 'fuse') {
      const burnt = !!c.props.broken;
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 48, y, x - 34, y); line(x + 34, y, x + 48, y);
      ctx.strokeStyle = burnt ? COL.danger : COL.comp; ctx.lineWidth = 3.5;
      ctx.beginPath(); ctx.rect(x - 34, y - 11, 68, 22); ctx.stroke();
      ctx.fillStyle = burnt ? COL.fillWarm : COL.fillWarm; ctx.fill();
      ctx.strokeStyle = burnt ? COL.danger : COL.warn;
      ctx.lineWidth = 3;
      if (burnt) { line(x - 22, y - 6, x - 8, y + 6); line(x + 8, y - 6, x + 22, y + 6); }
      else { line(x - 24, y, x + 24, y); }
      label(burnt ? tagOf(c) + '已熔断(需更换)' : tagOf(c) + '保险丝 ' + c.props.Imax + 'A',
        x, y + 30, burnt ? COL.danger : COL.label, 12, burnt ? '700' : '500');
    } else if (c.type === 'led') {
      const on = !!info.ledOn;
      // 亮度随电流变化:电流越大越亮(0.02 A 视为满亮度)
      const k = on ? Math.max(0.18, Math.min(1, Math.abs(info.I) / 0.02)) : 0;
      if (on) {
        const g = ctx.createRadialGradient(x, y, 4, x, y, 46);
        g.addColorStop(0, 'rgba(255,110,110,' + (0.75 * k).toFixed(3) + ')');
        g.addColorStop(0.5, 'rgba(255,80,80,' + (0.28 * k).toFixed(3) + ')');
        g.addColorStop(1, 'rgba(255,80,80,0)');
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(x, y, 46, 0, Math.PI * 2); ctx.fill();
      }
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 46, y, x - 16, y); line(x + 16, y, x + 46, y);   // 0号接线柱在左(阴极),1号在右(阳极)
      ctx.strokeStyle = COL.comp; ctx.lineWidth = 4;
      ctx.beginPath();                                          // 三角形指向阴极(左)
      ctx.moveTo(x + 16, y - 16); ctx.lineTo(x + 16, y + 16); ctx.lineTo(x - 16, y);
      ctx.closePath(); ctx.stroke();
      if (on) { ctx.fillStyle = 'rgba(255,120,120,' + (0.85 * k).toFixed(3) + ')'; ctx.fill(); }
      line(x - 16, y - 16, x - 16, y + 16);                     // 阴极横线
      ctx.strokeStyle = on ? COL.danger : COL.soft; ctx.lineWidth = 3;
      line(x + 6, y - 26, x + 18, y - 38); line(x - 8, y - 26, x + 4, y - 38);   // 发光箭头
      // 三种情况分开说清楚:导通发光 / 有电压但回路没闭合 / 反接截止
      const ledTxt = on ? '正向导通 · 发光'
        : ((info.ledVOpen || 0) > c.props.Vf ? '未闭合:不发光' : '反向截止 · 不发光');
      label(tagOf(c) + ledTxt, x, y + 34, on ? COL.danger : COL.label, 12, on ? '700' : '500');
      label('+', x + 30, y - 18, COL.danger, 13, '700');
      label('-', x - 30, y - 18, COL.textFaint, 13, '700');
    } else if (c.type === 'motor') {
      const speed = Math.min(1, Math.abs(info.I) / 0.5);
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 44, y, x - 26, y); line(x + 26, y, x + 44, y);
      ctx.strokeStyle = COL.comp; ctx.lineWidth = 4;
      ctx.beginPath(); ctx.arc(x, y, 26, 0, Math.PI * 2); ctx.stroke();
      ctx.fillStyle = COL.white; ctx.beginPath(); ctx.arc(x, y, 24, 0, Math.PI * 2); ctx.fill();
      // 转子:电流越大转得越快
      const spin = (s && s._t ? s._t : 0) * (1 + speed * 26);
      ctx.strokeStyle = speed > 0.01 ? COL.ok : COL.soft;
      ctx.lineWidth = 3.5;
      for (let k = 0; k < 3; k++) {
        const a = spin + k * Math.PI * 2 / 3;
        line(x + Math.cos(a) * 6, y + Math.sin(a) * 6, x + Math.cos(a) * 17, y + Math.sin(a) * 17);
      }
      label('M', x, y - 12, COL.ok, 15, '700');
      label(tagOf(c) + (speed > 0.01 ? '转动中 ' + Math.round(speed * 100) + '%' : '未转动'), x, y + 42,
        speed > 0.01 ? COL.ok : COL.label, 12, speed > 0.01 ? '700' : '500');
    } else if (c.type === 'bell') {
      const vol = bellVolume(Math.abs(info.I));
      const ring = vol > 0;
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 44, y, x - 24, y); line(x + 24, y, x + 44, y);
      ctx.strokeStyle = COL.comp; ctx.lineWidth = 4;
      ctx.beginPath();
      ctx.moveTo(x - 20, y + 12);
      ctx.lineTo(x - 20, y - 2);
      ctx.arc(x, y - 2, 20, Math.PI, 0);      // 铃碗
      ctx.lineTo(x + 20, y + 12);
      ctx.closePath();
      ctx.fillStyle = ring ? COL.fillBell : COL.fill; ctx.fill(); ctx.stroke();
      // 铃锤:摆幅随音量变化
      const t = (s && s._t ? s._t : 0) * (10 + 10 * vol);
      const swing = ring ? Math.sin(t) * (0.18 + 0.42 * vol) : 0.18;
      ctx.strokeStyle = ring ? COL.warn : COL.soft;
      ctx.lineWidth = 3.5;
      ctx.save();
      ctx.translate(x, y + 12);
      ctx.rotate(swing);
      line(0, 0, 0, -20);
      ctx.beginPath(); ctx.arc(0, -22, 4.5, 0, Math.PI * 2);
      ctx.fillStyle = ring ? COL.warn : COL.soft; ctx.fill();
      ctx.restore();
      label(ring ? '叮——' : '不响', x, y + 42, ring ? COL.warn : COL.label,
        12 + 4 * vol, ring ? '700' : '500');
      if (ring) label('音量 ' + Math.round(vol * 100) + '%', x, y + 58, COL.label, 11.5);
    } else if (c.type === 'ammeter' || c.type === 'voltmeter') {
      const isA = c.type === 'ammeter';
      const over = meterOver(c, info);                 // 超量程:红环 + 红字(真值照常显示)
      ctx.strokeStyle = wire; ctx.lineWidth = 4;
      line(x - 38, y, x - 26, y); line(x + 26, y, x + 38, y);
      ctx.strokeStyle = over ? COL.danger : COL.comp; ctx.lineWidth = over ? 5 : 4;
      ctx.beginPath(); ctx.arc(x, y, 26, 0, Math.PI * 2); ctx.stroke();
      ctx.fillStyle = COL.white;
      ctx.beginPath(); ctx.arc(x, y, 24, 0, Math.PI * 2); ctx.fill();
      label(isA ? 'A' : 'V', x, y + 1, isA ? COL.ok : COL.term, 22, '700');
      // 表笔正负:端子 0 = +(红)、端子 1 = −(灰)。与电池的 −/+ 同一套画法。
      const rev = meterReversed(c, info);
      const plusCol = COL.danger;
      const minusCol = rev ? COL.danger : COL.textFaint;
      label('+', x + 34, y - 17, plusCol, 15, '700');
      label('-', x - 34, y - 17, minusCol, 15, '700');
      if (rev) {
        // 接反了:直接在表旁边写清楚,学生一眼知道是哪根表笔接反
        label('⚠ 表笔接反', x, y - 40, COL.danger, 12, '700');
      }
      const val = isA ? Math.abs(info.I) : Math.abs(info.U);
      label(tagOf(c) + fmt(val, 3) + (isA ? ' A' : ' V') + (over ? ' ⚠超量程' : ''),
        x, y + 46, over ? COL.danger : COL.text, 14, '700');
    } else if (c.type === 'junction') {
      ctx.fillStyle = COL.white;
      ctx.save();
      ctx.strokeStyle = COL.term; ctx.globalAlpha = 0.5; ctx.lineWidth = 1.6; ctx.setLineDash([3, 3]);
      ctx.beginPath(); ctx.arc(x, y, 13, 0, Math.PI * 2); ctx.stroke();
      ctx.restore();
      ctx.beginPath(); ctx.arc(x, y, 10, 0, Math.PI * 2); ctx.fill();   // 白色描边,便于看清可拖动的本体
      ctx.fillStyle = COL.comp;
      ctx.beginPath(); ctx.arc(x, y, 7.5, 0, Math.PI * 2); ctx.fill();
    }
    view.rot = 0;
    if (rotRad) ctx.restore();
  }

  function drawTerminals() {
    const pt = state.pendingTerm;
    // 长按进行中:进度环(0 → 一圈 = 进入接线状态)
    if (state.termPress) {
      const nowMs = (typeof performance !== 'undefined' ? performance.now() : Date.now());
      const prog = Math.max(0, Math.min(1, (nowMs - state.termPress.t0) / TERM_HOLD_MS));
      if (prog >= HUD_SHOW_AT) {
        ctx.save();
        ctx.beginPath();
        ctx.arc(state.termPress.sx, state.termPress.sy, 16, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(255,157,46,0.14)';
        ctx.fill();
        ctx.beginPath();
        ctx.arc(state.termPress.sx, state.termPress.sy, 16, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * prog);
        ctx.strokeStyle = COL.current;
        ctx.lineWidth = 3 / Math.max(0.3, view.scale);
        ctx.stroke();
        ctx.restore();
      }
    }
    state.components.forEach(c => {
      if (c.type === 'junction') return;        // 接线点本体就是一个点,不再画四个接线柱
      DEFS[c.type].terminals.forEach((_, i) => {
        const p = termPos(c, i);
        const hot = state.hoverTerm && state.hoverTerm.cid === c.id && state.hoverTerm.ti === i;
        const wf = (state.drag && state.drag.mode === 'wire') ? state.drag.from : null;
        const wmFrom = state.wireMode ? state.wireMode.from : null;
        const pend = (pt && pt.cid === c.id && pt.ti === i) ||
          (wf && wf.cid === c.id && wf.ti === i) ||
          (wmFrom && wmFrom.cid === c.id && wmFrom.ti === i);
        if (pend) {                                   // 待连接端子:一圈呼吸光环,提示"再点另一端"
          const pulse = 0.55 + 0.45 * Math.sin((state.solved && state.solved._t ? state.solved._t : 0) * 6);
          ctx.beginPath();
          ctx.arc(p.x, p.y, 13 + 3 * pulse, 0, Math.PI * 2);
          ctx.fillStyle = 'rgba(255,157,46,' + (0.18 + 0.18 * pulse).toFixed(3) + ')';
          ctx.fill();
          ctx.beginPath();
          ctx.arc(p.x, p.y, 13, 0, Math.PI * 2);
          ctx.strokeStyle = COL.current;
          ctx.lineWidth = 2 / Math.max(0.3, view.scale);
          ctx.stroke();
        }
        ctx.beginPath();
        ctx.arc(p.x, p.y, (hot || pend) ? 7 : 4.5, 0, Math.PI * 2);
        ctx.fillStyle = (hot || pend) ? COL.termHot : COL.white;
        ctx.fill();
        ctx.lineWidth = 2.5;
        ctx.strokeStyle = hot ? COL.warn : (pend ? COL.current : COL.term);
        ctx.stroke();
      });
    });
  }

  function drawSelection() {
    if (!state.selectedIds.length) return;
    ctx.save();
    ctx.setLineDash([7, 5]);
    ctx.strokeStyle = '#ff9d2e';
    ctx.lineWidth = 2;
    state.selectedIds.forEach(id => {
      const c = compById(id);
      if (!c) return;
      const b = bounds(c);
      ctx.beginPath();
      if (ctx.roundRect) ctx.roundRect(b.x - 8, b.y - 8, b.w + 16, b.h + 16, 10);
      else ctx.rect(b.x - 8, b.y - 8, b.w + 16, b.h + 16);
      ctx.stroke();
    });
    ctx.restore();
  }

  // 框选矩形(像用光标框选文件一样)
  function drawMarquee() {
    const d = state.drag;
    if (!d || d.mode !== 'marquee' || !d.moved) return;
    const x = Math.min(d.x0, d.x1), y = Math.min(d.y0, d.y1);
    const w = Math.abs(d.x1 - d.x0), h = Math.abs(d.y1 - d.y0);
    ctx.save();
    ctx.fillStyle = 'rgba(45,111,174,0.14)';
    ctx.beginPath(); ctx.rect(x, y, w, h); ctx.fill();
    ctx.setLineDash([6, 4]);
    ctx.strokeStyle = '#2d6fae';
    ctx.lineWidth = 1.6;
    ctx.beginPath(); ctx.rect(x, y, w, h); ctx.stroke();
    ctx.restore();
  }

  // 新添加的元件闪烁一圈,提示"就加在这里"
  function drawFlash() {
    // 操作学习:本步要操作的元件一直亮着(橙色圈,方便学生找到"要改哪个")
    const pickId = state.learnPick;
    if (pickId) {
      const pc = compById(pickId);
      if (pc) {
        const pb = bounds(pc);
        ctx.save();
        ctx.beginPath();
        ctx.arc(pb.x + pb.w / 2, pb.y + pb.h / 2, Math.max(pb.w, pb.h) / 2 + 16, 0, Math.PI * 2);
        ctx.strokeStyle = 'rgba(255,157,46,0.95)';
        ctx.lineWidth = 3.5 / Math.max(0.3, view.scale);
        ctx.stroke();
        ctx.restore();
      }
    }
    const f = state.flash;
    if (!f) return;
    const c = compById(f.id);
    if (!c) { state.flash = null; return; }
    if (f.t > 1.4) { state.flash = null; return; }
    const b = bounds(c);
    const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
    const k = Math.max(0, 1 - f.t / 1.4);
    const r = Math.max(b.w, b.h) / 2 + 14 + 26 * (1 - k);
    ctx.save();
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, Math.PI * 2);
    ctx.strokeStyle = 'rgba(255,157,46,' + (0.85 * k).toFixed(3) + ')';
    ctx.lineWidth = 3 / Math.max(0.3, view.scale);
    ctx.stroke();
    ctx.restore();
  }

  /* ---------- 画布注解(半透明底 + 白字) ---------- */
  const NOTE_FONT = 17;      // 注解字号(世界单位;画布缩放时同步放大缩小)
  const NOTE_LH = 23;        // 行高
  function noteBox(nt) {
    const w = nt.w || 280;
    const lines = String(nt.text || '').split('\n');
    const perRow = Math.max(6, Math.floor((w - 24) / NOTE_FONT));
    let rows = 0;
    lines.forEach(l => { rows += Math.max(1, Math.ceil(l.length / perRow)); });
    return { x: nt.x, y: nt.y, w: w, h: Math.max(44, rows * NOTE_LH + 18) };
  }
  function drawNotes() {
    (state.notes || []).forEach(nt => {
      const b = noteBox(nt);
      const active = state.noteDrag && state.noteDrag.id === nt.id;
      ctx.save();
      ctx.fillStyle = active ? 'rgba(20,45,80,0.80)' : 'rgba(18,40,72,0.62)';   // 半透明底
      ctx.strokeStyle = 'rgba(255,255,255,0.5)';
      ctx.lineWidth = 1.5 / Math.max(0.3, view.scale);
      if (nt.locked) {                                  // 锁定的注解画虚线,表示"只显示、可穿透"
        try { ctx.setLineDash([6 / Math.max(0.3, view.scale), 5 / Math.max(0.3, view.scale)]); } catch (e) { }
      }
      const r = 8;
      ctx.beginPath();
      ctx.moveTo(b.x + r, b.y);
      ctx.lineTo(b.x + b.w - r, b.y); ctx.quadraticCurveTo(b.x + b.w, b.y, b.x + b.w, b.y + r);
      ctx.lineTo(b.x + b.w, b.y + b.h - r); ctx.quadraticCurveTo(b.x + b.w, b.y + b.h, b.x + b.w - r, b.y + b.h);
      ctx.lineTo(b.x + r, b.y + b.h); ctx.quadraticCurveTo(b.x, b.y + b.h, b.x, b.y + b.h - r);
      ctx.lineTo(b.x, b.y + r); ctx.quadraticCurveTo(b.x, b.y, b.x + r, b.y);
      ctx.closePath(); ctx.fill(); ctx.stroke();
      try { ctx.setLineDash([]); } catch (e) { }
      if (nt.locked) {                                  // 右上角一个小锁(纯 Canvas 画,跨平台一致)
        const lx = b.x + b.w - 17, ly = b.y + 10, s = 1 / Math.max(0.3, view.scale);
        ctx.save();
        ctx.strokeStyle = 'rgba(255,157,46,0.95)';
        ctx.fillStyle = 'rgba(255,157,46,0.95)';
        ctx.lineWidth = 2 * s;
        ctx.beginPath();                                 // 锁梁
        ctx.arc(lx, ly, 4 * s, Math.PI, 0);
        ctx.stroke();
        ctx.beginPath();                                 // 锁身
        const bw = 11 * s, bh = 8 * s;
        ctx.rect(lx - bw / 2, ly, bw, bh);
        ctx.fill();
        ctx.restore();
      }
      if (!nt.locked) {                                 // 右下角缩放手柄(三条斜线)
        const g = 1 / Math.max(0.3, view.scale);
        ctx.save();
        ctx.strokeStyle = 'rgba(255,255,255,0.55)';
        ctx.lineWidth = 1.6 * g;
        for (let k = 0; k < 3; k++) {
          const off = (6 + k * 5) * g;
          ctx.beginPath();
          ctx.moveTo(b.x + b.w - off, b.y + b.h - 3 * g);
          ctx.lineTo(b.x + b.w - 3 * g, b.y + b.h - off);
          ctx.stroke();
        }
        ctx.restore();
      }
      ctx.textBaseline = 'top';
      ctx.font = '600 ' + NOTE_FONT + 'px "Microsoft YaHei", "PingFang SC", sans-serif';
      const perRow = Math.max(6, Math.floor((b.w - 24) / NOTE_FONT));
      let row = 0;
      String(nt.text || '').split('\n').forEach(raw => {
        // 以 !! 开头的行 = 重点提示:整行橙色高亮(标记本身不显示)
        const hot = raw.indexOf('!!') === 0;
        const ln = hot ? raw.slice(2) : raw;
        ctx.fillStyle = hot ? '#ff9d2e' : '#ffffff';
        for (let i = 0; i < ln.length || i === 0; i += perRow) {
          ctx.fillText(ln.slice(i, i + perRow), b.x + 12, b.y + 9 + row * NOTE_LH);
          row++;
          if (i + perRow >= ln.length) break;
        }
      });
      ctx.restore();
    });
  }
  // 注解右下角的缩放手柄(返回 true 表示点到了手柄)
  function hitNoteGrip(nt, p) {
    if (!nt || nt.locked) return false;
    const b = noteBox(nt);
    const pad = 16 / Math.max(0.3, view.scale);       // 手柄的点击范围(屏幕 16px)
    return p.x >= b.x + b.w - pad && p.x <= b.x + b.w + pad &&
           p.y >= b.y + b.h - pad && p.y <= b.y + b.h + pad;
  }
  function hitNote(p) {
    const list = state.notes || [];
    for (let i = list.length - 1; i >= 0; i--) {
      if (list[i].locked) continue;          // 锁定的注解"穿透":点击落到下面的元件上
      const b = noteBox(list[i]);
      if (p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h) return list[i];
    }
    return null;
  }
  function addNote(x, y, text) {
    pushUndo('添加注解');
    const nt = { id: 'n' + (++state.idSeq), x: Math.round(x / 10) * 10, y: Math.round(y / 10) * 10, w: 280, text: text };
    state.notes = (state.notes || []).concat([nt]);
    state.dirty = true;
    return nt;
  }
  function removeNote(id) {
    pushUndo('删除注解');
    state.notes = (state.notes || []).filter(x => x.id !== id);
    state.dirty = true;
  }

  /* 手机端长按 HUD:顶部一条进度条,手指挡住接线柱时也能看到"还要按多久" */
  function drawHoldHud() {
    if (!state.termPress) return;
    if (!(isTouchLike() || layoutMode === 'mobile')) return;
    const nowMs = (typeof performance !== 'undefined' ? performance.now() : Date.now());
    const progRaw = Math.max(0, Math.min(1, (nowMs - state.termPress.t0) / TERM_HOLD_MS));
    if (progRaw < HUD_SHOW_AT) { return; }                    // 轻点全程不显示(真实轻点常有 80~150ms)
    const fade = Math.min(1, (progRaw - HUD_SHOW_AT) / 0.20); // 淡入
    const prog = progRaw;
    const cw = canvas.clientWidth || 360;
    const w = Math.min(260, Math.max(180, cw - 80));
    const hgt = 46;
    const x = (cw - w) / 2, y = 14;
    ctx.save();
    ctx.setTransform(view.dpr, 0, 0, view.dpr, 0, 0);        // 切到屏幕坐标
    ctx.globalAlpha = fade;
    ctx.setLineDash([]);
    // 圆角底
    const r = 12;
    ctx.beginPath();
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + w - r, y); ctx.quadraticCurveTo(x + w, y, x + w, y + r);
    ctx.lineTo(x + w, y + hgt - r); ctx.quadraticCurveTo(x + w, y + hgt, x + w - r, y + hgt);
    ctx.lineTo(x + r, y + hgt); ctx.quadraticCurveTo(x, y + hgt, x, y + hgt - r);
    ctx.lineTo(x, y + r); ctx.quadraticCurveTo(x, y, x + r, y);
    ctx.closePath();
    ctx.fillStyle = 'rgba(10,22,38,0.90)';
    ctx.fill();
    ctx.strokeStyle = 'rgba(255,157,46,0.9)';
    ctx.lineWidth = 2;
    ctx.stroke();
    // 文字
    ctx.fillStyle = '#ffffff';
    ctx.font = '600 13px "Microsoft YaHei", "PingFang SC", sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('按住不放 → 接线模式', x + w / 2, y + 16);
    // 进度条
    const bx = x + 14, by = y + hgt - 15, bw = w - 28, bh = 6;
    ctx.fillStyle = 'rgba(255,255,255,0.18)';
    ctx.beginPath(); ctx.rect(bx, by, bw, bh); ctx.fill();
    ctx.fillStyle = '#ff9d2e';
    ctx.beginPath(); ctx.rect(bx, by, Math.max(1, bw * prog), bh); ctx.fill();
    ctx.textAlign = 'left';
    ctx.textBaseline = 'alphabetic';
    ctx.restore();
    // 恢复世界坐标变换,避免影响后续绘制
    ctx.setTransform(view.dpr * view.scale, 0, 0, view.dpr * view.scale, view.dpr * view.tx, view.dpr * view.ty);
  }

  function drawDragWire() {
    const d = state.drag;
    /* ① 接线模式下"起头接线柱"的呼吸光环:必须与鼠标状态无关!
       手机端松手后 mouseStale=true,如果把它放在下面的鼠标判断之后就会被整段跳过
       (表现就是"手机上看不到呼吸效果,电脑上能看到")。 */
    const srcNow = state.wireMode ? state.wireMode.from : ((d && d.mode === 'wire') ? d.from : null);
    if (srcNow) {
      const cSrc = compById(srcNow.cid);
      if (cSrc) {
        const p0 = termPos(cSrc, srcNow.ti);
        const ph0 = (performance.now() % 1400) / 1400;
        const pulse0 = 0.5 - 0.5 * Math.cos(ph0 * Math.PI * 2);
        ctx.save();
        ctx.setLineDash([]);
        ctx.globalAlpha = 0.18 + 0.30 * pulse0;
        ctx.fillStyle = COL.current;
        ctx.beginPath(); ctx.arc(p0.x, p0.y, 15 + 8 * pulse0, 0, Math.PI * 2); ctx.fill();
        ctx.globalAlpha = 0.55 + 0.35 * pulse0;
        ctx.strokeStyle = COL.current;
        ctx.lineWidth = 3;
        ctx.beginPath(); ctx.arc(p0.x, p0.y, 15, 0, Math.PI * 2); ctx.stroke();
        ctx.globalAlpha = 1;
        ctx.restore();
      }
    }
    let from = null, to = null;
    if (d && d.mode === 'wire') {
      const c = compById(d.from.cid);
      if (!c) return;
      from = termPos(c, d.from.ti); to = { x: d.x, y: d.y };
    } else if (state.wireMode) {
      if (mouseStale || !state.mouse) return;
      const c0 = compById(state.wireMode.from.cid);
      if (!c0) return;
      from = termPos(c0, state.wireMode.from.ti);
      to = state.mouse;
    } else if (state.pendingTerm) {
      // 两段式连线:只有"指针还在画布上"时才画跟随虚线。
      // 手指抬起后 state.mouse 仍是旧值,若还照着它画,就会出现一条指向空处的橙虚线。
      if (mouseStale || !state.mouse) return;
      const c = compById(state.pendingTerm.cid);
      if (!c) return;
      from = termPos(c, state.pendingTerm.ti);
      to = state.mouse;
    }
    if (!from || !to) return;
    /* 吸附点:接线模式下(鼠标靠近某条导线)实时算出来,画一个半透明"呼吸"接线点预览;
       旧拖动路径如果已经算过,就直接用它的。 */
    let snap = null;
    if (d && d.mode === 'wire' && d.moved && d.snap) snap = d.snap;
    else if (state.wireMode && state.wireHover) snap = { x: state.wireHover.x, y: state.wireHover.y };
    if (snap) { to = { x: snap.x, y: snap.y }; }
    ctx.save();
    ctx.setLineDash([8, 6]);
    ctx.strokeStyle = COL.current;
    ctx.lineWidth = 4;
    line(from.x, from.y, to.x, to.y);
    if (snap) {
      // 呼吸效果:半径与透明度随时间轻微起伏,表示"位置还没定下来"
      const ph = (performance.now() % 1600) / 1600;
      const pulse = 0.5 - 0.5 * Math.cos(ph * Math.PI * 2);        // 0..1
      const r = 10 + 5 * pulse;
      ctx.setLineDash([]);
      ctx.globalAlpha = 0.22 + 0.30 * pulse;
      ctx.fillStyle = COL.term;
      ctx.beginPath(); ctx.arc(snap.x, snap.y, r + 4, 0, Math.PI * 2); ctx.fill();
      ctx.globalAlpha = 0.45 + 0.4 * pulse;
      ctx.strokeStyle = COL.term; ctx.lineWidth = 2.5;
      ctx.beginPath(); ctx.arc(snap.x, snap.y, r, 0, Math.PI * 2); ctx.stroke();
      ctx.globalAlpha = 1;
      ctx.fillStyle = COL.white;
      ctx.beginPath(); ctx.arc(snap.x, snap.y, 3.5, 0, Math.PI * 2); ctx.fill();
    }
    // 吸附到的端子(如果有)画个圆,提示"松手就连这里"
    const ht = state.hoverTerm;
    if (ht) {
      const cc = compById(ht.cid);
      if (cc) {
        const q = termPos(cc, ht.ti);
        ctx.setLineDash([]);
        ctx.beginPath(); ctx.arc(q.x, q.y, 11, 0, Math.PI * 2);
        ctx.strokeStyle = COL.current; ctx.lineWidth = 3; ctx.stroke();
      }
    }
    ctx.restore();
  }

  /* ---------- 右下角缩略图(导航器) ----------
     把整个电路的元件用简化图形画出来,并显示当前视口范围;
     拖动左上角手柄可以调整大小,点击/拖动缩略图可以快速移动视野。 */
  const MINIMAP_COLOR = {
    battery: '#e05a3a', switch: '#2d6fae', bulb: '#e8a92e', resistor: '#6b7280',
    conductor: '#8a5a2b', rheostat: '#6b7280', ammeter: '#1d7f5f', voltmeter: '#2d6fae',
    motor: '#12734f', led: '#d3453a', bell: '#c9701a', fuse: '#b0392c', junction: '#93a3bd'
  };
  const mmCanvas = document.getElementById('mmCanvas');
  const mmCtx = (mmCanvas && mmCanvas.getContext) ? mmCanvas.getContext('2d') : null;
  const mmHandle = document.getElementById('mmHandle');
  const mmBox = document.getElementById('minimap');
  const btnMinimap = document.getElementById('btnMinimap');

  function mmSave() {
    try {
      if (window.localStorage) {
        window.localStorage.setItem('circuitLab.minimap', JSON.stringify(state.mm));
      }
    } catch (e) { }
  }
  function mmApplySize() {
    if (!mmBox) return;
    mmBox.style.width = state.mm.w + 'px';
    mmBox.style.height = state.mm.h + 'px';
    if (typeof mmApplyPos === 'function') mmApplyPos();
    if (btnMinimap) btnMinimap.className = state.mm.hidden ? '' : 'on';
  }
  /* 缩略图位置:默认贴在右下角;一旦拖动过,就用 left/top 记录(持久化) */
  const MM_EDGE = 12;      // 距画布边缘的默认内边距(吸附后也是这个值)
  const MM_SNAP = 26;      // 松手时离边缘多近就吸附
  function mmParentSize() {
    const host = (mmBox && mmBox.offsetParent) || (typeof wrap !== 'undefined' && wrap) || null;
    const r = host && host.getBoundingClientRect ? host.getBoundingClientRect() : { width: 1000, height: 620 };
    return { w: r.width || 1000, h: r.height || 620 };
  }
  function mmApplyPos() {
    if (!mmBox) return;
    if (!state.mm.pos) {                       // 没拖动过 → 保持 CSS 的右下角默认位置
      mmBox.style.left = ''; mmBox.style.top = '';
      mmBox.style.right = MM_EDGE + 'px'; mmBox.style.bottom = MM_EDGE + 'px';
      return;
    }
    const host = mmParentSize();
    const maxL = Math.max(4, host.w - state.mm.w - 4);
    const maxT = Math.max(4, host.h - state.mm.h - 4);
    const L = Math.max(4, Math.min(maxL, state.mm.pos.left));
    const T = Math.max(4, Math.min(maxT, state.mm.pos.top));
    state.mm.pos.left = L; state.mm.pos.top = T;
    mmBox.style.right = 'auto'; mmBox.style.bottom = 'auto';
    mmBox.style.left = L + 'px'; mmBox.style.top = T + 'px';
  }
  // 松手吸附:左右/上下各自独立判断,靠得近就贴边
  function mmSnap() {
    if (!state.mm.pos) return;
    const host = mmParentSize();
    const p = state.mm.pos;
    const right = host.w - (p.left + state.mm.w);
    const bottom = host.h - (p.top + state.mm.h);
    if (p.left <= MM_SNAP) p.left = MM_EDGE;
    else if (right <= MM_SNAP) p.left = Math.max(4, host.w - state.mm.w - MM_EDGE);
    if (p.top <= MM_SNAP) p.top = MM_EDGE;
    else if (bottom <= MM_SNAP) p.top = Math.max(4, host.h - state.mm.h - MM_EDGE);
    mmApplyPos();
  }
  function setMinimapHidden(hidden) {
    state.mm.hidden = !!hidden;
    if (mmBox) mmBox.style.display = state.mm.hidden ? 'none' : 'block';
    mmApplySize();
    mmSave();
  }
  function mmWorldMap() {
    const b = contentBounds();
    const pad = 8;
    const W = state.mm.w, H = state.mm.h;
    const sc = Math.max(0.001, Math.min((W - pad * 2) / b.w, (H - pad * 2) / b.h));
    return {
      s: sc,
      ox: (W - b.w * sc) / 2 - b.x * sc,
      oy: (H - b.h * sc) / 2 - b.y * sc,
      toX: function (wx) { return wx * sc + this.ox; },
      toY: function (wy) { return wy * sc + this.oy; }
    };
  }
  // 画缩略图:元件用简化的色块/圆点表示
  function drawMinimap() {
    if (!mmCtx || state.mm.hidden) return;
    const dpr = window.devicePixelRatio || 1;
    const W = state.mm.w, H = state.mm.h;
    if (mmCanvas.width !== Math.round(W * dpr) || mmCanvas.height !== Math.round(H * dpr)) {
      mmCanvas.width = Math.round(W * dpr);
      mmCanvas.height = Math.round(H * dpr);
    }
    const g = mmCtx;
    g.setTransform(dpr, 0, 0, dpr, 0, 0);
    g.clearRect(0, 0, W, H);
    g.fillStyle = COL.canvasBg;
    g.beginPath(); g.rect(0, 0, W, H); g.fill();
    const m = mmWorldMap();
    // 导线
    g.strokeStyle = COL.wire;
    g.lineWidth = 1;
    g.beginPath();
    state.wires.forEach(w => {
      const ca = compById(w.a.cid), cb = compById(w.b.cid);
      if (!ca || !cb) return;
      const pa = termPos(ca, w.a.ti), pb = termPos(cb, w.b.ti);
      g.moveTo(m.toX(pa.x), m.toY(pa.y));
      g.lineTo(m.toX(pb.x), m.toY(pb.y));
    });
    g.stroke();
    // 元件(简化:小色块 / 圆点)
    state.components.forEach(c => {
      const col = MINIMAP_COLOR[c.type] || '#7b8db0';
      const b = bounds(c);
      const x = m.toX(b.x), y = m.toY(b.y);
      const w = Math.max(2.5, b.w * m.s), h = Math.max(2.5, b.h * m.s);
      g.fillStyle = col;
      if (c.type === 'junction') {
        g.beginPath(); g.arc(x, y, 1.6, 0, Math.PI * 2); g.fill();
      } else if (c.type === 'bulb' || c.type === 'ammeter' || c.type === 'voltmeter' || c.type === 'motor' || c.type === 'bell') {
        g.beginPath(); g.arc(x + w / 2, y + h / 2, Math.max(2, Math.min(w, h) / 2), 0, Math.PI * 2); g.fill();
      } else {
        g.beginPath(); g.rect(x, y, w, h); g.fill();
      }
    });
    // 当前视口范围
    const v = visibleWorld();
    g.strokeStyle = '#ff9d2e';
    g.lineWidth = 1.5;
    g.beginPath();
    g.rect(m.toX(v.x0), m.toY(v.y0), v.w * m.s, v.h * m.s);
    g.stroke();
  }
  // 缩略图上的世界坐标 ↔ 屏幕坐标
  function mmToWorld(clientX, clientY) {
    const r = mmCanvas.getBoundingClientRect();
    const m = mmWorldMap();
    const W = state.mm.w, H = state.mm.h;
    const cssW = r.width || W, cssH = r.height || H;
    const mx = (clientX - r.left) * (W / cssW), my = (clientY - r.top) * (H / cssH);
    return { x: (mx - m.ox) / m.s, y: (my - m.oy) / m.s };
  }
  // 把主视图中心移到指定世界点
  function centerOn(wx, wy) {
    const cssW = canvas.clientWidth || wrap.clientWidth || 800;
    const cssH = canvas.clientHeight || wrap.clientHeight || 480;
    view.tx = cssW / 2 - wx * view.scale;
    view.ty = cssH / 2 - wy * view.scale;
  }
  if (mmCanvas) {
    let mmDrag = null;
    mmCanvas.addEventListener('pointerdown', ev => {
      ev.stopPropagation();
      try { mmCanvas.setPointerCapture && mmCanvas.setPointerCapture(ev.pointerId); } catch (e) { }
      mmDrag = { mode: 'nav' };
      const w = mmToWorld(ev.clientX, ev.clientY);
      centerOn(w.x, w.y);
    });
    mmCanvas.addEventListener('pointermove', ev => {
      if (!mmDrag || mmDrag.mode !== 'nav') return;
      const w = mmToWorld(ev.clientX, ev.clientY);
      centerOn(w.x, w.y);
    });
    const mmEnd = () => { mmDrag = null; };
    mmCanvas.addEventListener('pointerup', mmEnd);
    mmCanvas.addEventListener('pointercancel', mmEnd);
  }
  const mmBar = document.getElementById('mmBar');
  if (mmBar && mmBox) {
    let mv = null;
    mmBar.addEventListener('pointerdown', ev => {
      if (ev.stopPropagation) ev.stopPropagation();   // 不要触发下面的"跳转视野"
      const r = mmBox.getBoundingClientRect();
      const host = mmParentSize();
      const hostRect = (mmBox.offsetParent && mmBox.offsetParent.getBoundingClientRect)
        ? mmBox.offsetParent.getBoundingClientRect() : { left: 0, top: 0 };
      mv = {
        dx: ev.clientX - r.left, dy: ev.clientY - r.top,
        hostL: hostRect.left, hostT: hostRect.top, moved: false
      };
      try { mmBar.setPointerCapture && mmBar.setPointerCapture(ev.pointerId); } catch (e) { }
      setElClass(mmBox, 'mm-dragging', true);
    });
    mmBar.addEventListener('pointermove', ev => {
      if (!mv) return;
      const host = mmParentSize();
      let L = ev.clientX - mv.hostL - mv.dx;
      let T = ev.clientY - mv.hostT - mv.dy;
      if (!mv.moved && Math.hypot(ev.clientX - (mv.hostL + mv.dx), ev.clientY - (mv.hostT + mv.dy)) < 2) return;
      mv.moved = true;
      const maxL = Math.max(4, host.w - state.mm.w - 4);
      const maxT = Math.max(4, host.h - state.mm.h - 4);
      state.mm.pos = {
        left: Math.max(4, Math.min(maxL, L)),
        top: Math.max(4, Math.min(maxT, T))
      };
      mmApplyPos();
    });
    const mvEnd = () => {
      if (!mv) return;
      mv = null;
      setElClass(mmBox, 'mm-dragging', false);
      mmSnap();                                  // 松手吸附到最近的边
      mmSave();
    };
    mmBar.addEventListener('pointerup', mvEnd);
    mmBar.addEventListener('pointercancel', mvEnd);
  }

  if (mmHandle) {
    let rz = null;
    mmHandle.addEventListener('pointerdown', ev => {
      if (ev.stopPropagation) ev.stopPropagation();
      rz = { x: ev.clientX, y: ev.clientY, w: state.mm.w, h: state.mm.h };   // 先记录,别被后面的捕获异常打断
      try { mmHandle.setPointerCapture && mmHandle.setPointerCapture(ev.pointerId); } catch (e) { }
    });
    mmHandle.addEventListener('pointermove', ev => {
      if (!rz) return;
      // 手柄在右下角:往右/往下拖 = 变大
      state.mm.w = Math.max(96, Math.min(460, Math.round(rz.w + (ev.clientX - rz.x))));
      state.mm.h = Math.max(64, Math.min(320, Math.round(rz.h + (ev.clientY - rz.y))));
      mmApplySize();
    });
    const rzEnd = () => { if (rz) { rz = null; mmSave(); } };
    mmHandle.addEventListener('pointerup', rzEnd);
    mmHandle.addEventListener('pointercancel', rzEnd);
  }
  const mmClose = document.getElementById('mmClose');
  if (mmClose) mmClose.addEventListener('click', ev => { ev.stopPropagation(); setMinimapHidden(true); });

  /* ================= 元件图鉴 =================
     每种元件:电路符号 + 实物示意 + 原理说明 + 常见规格(多种参数的元件列出多个变体)。
     所有配图都是内联 SVG 矢量插画:任意缩放都清晰(真高清),不依赖网络,
     离线课堂也能正常显示,也不会出现图片挂掉的情况。 */
  function svgOpen(vb) { return '<svg class="lib-svg" viewBox="' + (vb || '0 0 220 150') + '" xmlns="http://www.w3.org/2000/svg">'; }

  // —— 电路符号(标准符号,用于"电路符号"一栏)
  const SYM = {
    battery: function () {
      // 单节电池符号:只有两块极板 —— 长细线是正极、短粗线是负极
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="88" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="132" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="88" y1="20" x2="88" y2="70" stroke="#1f3864" stroke-width="9"/>' +
        '<line x1="132" y1="10" x2="132" y2="80" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="70" y="18" font-size="15" font-weight="700" fill="#5b6b86">−</text>' +
        '<text x="140" y="18" font-size="15" font-weight="700" fill="#c02a2a">+</text>' +
        '<text x="110" y="88" text-anchor="middle" font-size="11" fill="#7b8db0">长线为正极(电流由此流出)</text>' +
        '</svg>';
    },
    switch: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="70" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="150" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<circle cx="70" cy="45" r="5" fill="#1f3864"/><circle cx="150" cy="45" r="5" fill="#1f3864"/>' +
        '<line x1="70" y1="45" x2="140" y2="16" stroke="#b0392c" stroke-width="5" stroke-linecap="round"/>' +
        '<text x="110" y="80" text-anchor="middle" font-size="11" fill="#7b8db0">断开状态:电路断开</text>' +
        '</svg>';
    },
    bulb: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="76" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="144" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<circle cx="110" cy="45" r="34" fill="none" stroke="#1f3864" stroke-width="4"/>' +
        '<line x1="86" y1="69" x2="134" y2="21" stroke="#1f3864" stroke-width="4"/>' +
        '<line x1="86" y1="21" x2="134" y2="69" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="110" y="88" text-anchor="middle" font-size="11" fill="#7b8db0">圆圈加叉=小灯泡</text>' +
        '</svg>';
    },
    resistor: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="66" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="154" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<rect x="66" y="26" width="88" height="38" fill="#eef4ff" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="110" y="88" text-anchor="middle" font-size="11" fill="#7b8db0">长方形=定值电阻</text>' +
        '</svg>';
    },
    rheostat: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="8" y1="45" x2="46" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="174" y1="45" x2="212" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<rect x="46" y="26" width="128" height="38" fill="#eef4ff" stroke="#1f3864" stroke-width="4"/>' +
        '<line x1="120" y1="8" x2="104" y2="24" stroke="#c9701a" stroke-width="4"/>' +
        '<polygon points="98,28 114,28 106,38" fill="#c9701a"/>' +
        '<text x="110" y="86" text-anchor="middle" font-size="11" fill="#7b8db0">箭头=滑片(阻值可调)</text>' +
        '</svg>';
    },
    ammeter: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="76" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="144" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<circle cx="110" cy="45" r="34" fill="#fff" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="110" y="56" text-anchor="middle" font-size="30" font-weight="700" fill="#1d7f5f">A</text>' +
        '<text x="110" y="88" text-anchor="middle" font-size="11" fill="#7b8db0">串联在电路中测电流</text>' +
        '</svg>';
    },
    voltmeter: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="76" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="144" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<circle cx="110" cy="45" r="34" fill="#fff" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="110" y="56" text-anchor="middle" font-size="30" font-weight="700" fill="#2d6fae">V</text>' +
        '<text x="110" y="88" text-anchor="middle" font-size="11" fill="#7b8db0">并联在被测元件两端</text>' +
        '</svg>';
    },
    motor: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="76" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="144" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<circle cx="110" cy="45" r="34" fill="#fff" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="110" y="57" text-anchor="middle" font-size="30" font-weight="700" fill="#1d7f5f">M</text>' +
        '<text x="110" y="88" text-anchor="middle" font-size="11" fill="#7b8db0">把电能转化为机械能</text>' +
        '</svg>';
    },
    led: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="88" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="132" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<polygon points="96,25 96,65 132,45" fill="none" stroke="#1f3864" stroke-width="4"/>' +
        '<line x1="132" y1="25" x2="132" y2="65" stroke="#1f3864" stroke-width="5"/>' +
        '<line x1="104" y1="18" x2="118" y2="6" stroke="#c02a2a" stroke-width="3"/>' +
        '<line x1="118" y1="24" x2="132" y2="12" stroke="#c02a2a" stroke-width="3"/>' +
        '<text x="110" y="86" text-anchor="middle" font-size="11" fill="#7b8db0">三角形指向阴极,单向导电</text>' +
        '</svg>';
    },
    bell: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="76" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="144" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<path d="M78 60 A32 32 0 0 1 142 60 Z" fill="none" stroke="#1f3864" stroke-width="4"/>' +
        '<line x1="76" y1="60" x2="144" y2="60" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="110" y="86" text-anchor="middle" font-size="11" fill="#7b8db0">通电后铃锤振动发声</text>' +
        '</svg>';
    },
    fuse: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="56" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="164" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<rect x="56" y="30" width="108" height="30" fill="#fffdf3" stroke="#1f3864" stroke-width="4"/>' +
        '<line x1="66" y1="45" x2="154" y2="45" stroke="#c9701a" stroke-width="3"/>' +
        '<text x="110" y="86" text-anchor="middle" font-size="11" fill="#7b8db0">电流过大时熔断,保护电路</text>' +
        '</svg>';
    },
    conductor: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="20" y1="45" x2="60" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="160" y1="45" x2="200" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<rect x="60" y="26" width="100" height="38" fill="#f6efe2" stroke="#1f3864" stroke-width="4"/>' +
        '<text x="110" y="50" text-anchor="middle" font-size="13" fill="#8a5a2b">待测导体</text>' +
        '<text x="110" y="86" text-anchor="middle" font-size="11" fill="#7b8db0">R = ρL/S(材料、长度、粗细)</text>' +
        '</svg>';
    },
    junction: function () {
      return svgOpen('0 0 220 90') +
        '<line x1="60" y1="45" x2="160" y2="45" stroke="#39558a" stroke-width="4"/>' +
        '<line x1="110" y1="45" x2="110" y2="80" stroke="#39558a" stroke-width="4"/>' +
        '<circle cx="110" cy="45" r="9" fill="#1f3864"/>' +
        '<text x="110" y="24" text-anchor="middle" font-size="11" fill="#7b8db0">导线交汇处相连</text>' +
        '</svg>';
    }
  };

  // —— 实物示意(矢量插画)
  const ART = {
    dryCell: function (cls, label) {
      // 竖直摆放的圆柱电池:正极凸起、筒体、底部金属环、负极平底
      // 全部以 x = 110 为轴线,保证正负极在同一条中线上
      return svgOpen('0 0 220 150') +
        '<defs><linearGradient id="cell1" x1="0" x2="1"><stop offset="0" stop-color="#e9eef6"/><stop offset=".38" stop-color="#ffffff"/><stop offset="1" stop-color="#c2ccdb"/></linearGradient></defs>' +
        '<rect x="100" y="14" width="20" height="12" rx="4" fill="#cfd7e2" stroke="#9aa7b5" stroke-width="2"/>' +
        '<rect x="78" y="26" width="64" height="96" rx="9" fill="url(#cell1)" stroke="#94a1b1" stroke-width="2"/>' +
        '<rect x="78" y="32" width="64" height="24" fill="' + cls + '" opacity=".92"/>' +
        '<rect x="78" y="104" width="64" height="12" fill="#8e99a8"/>' +
        '<rect x="88" y="122" width="44" height="9" rx="3" fill="#b6bfca" stroke="#9aa7b5" stroke-width="1.5"/>' +
        '<text x="110" y="86" text-anchor="middle" font-size="26" font-weight="700" fill="#37424f">' + label + '</text>' +
        '<text x="150" y="24" font-size="15" font-weight="700" fill="#c02a2a">+</text>' +
        '<text x="150" y="132" font-size="15" font-weight="700" fill="#2d6fae">-</text>' +
        '</svg>';
    },
    coinCell: function () {
      return svgOpen('0 0 220 150') +
        '<defs><radialGradient id="coin1" cx=".4" cy=".35"><stop offset="0" stop-color="#fdfefe"/><stop offset="1" stop-color="#b9c3cf"/></radialGradient></defs>' +
        '<ellipse cx="110" cy="76" rx="62" ry="52" fill="url(#coin1)" stroke="#98a4b2" stroke-width="2"/>' +
        '<ellipse cx="110" cy="70" rx="50" ry="42" fill="#dfe6ef" stroke="#aeb9c6" stroke-width="1.5"/>' +
        '<text x="110" y="66" text-anchor="middle" font-size="18" font-weight="700" fill="#3a4656">CR2032</text>' +
        '<text x="110" y="88" text-anchor="middle" font-size="14" fill="#5b6b86">3V</text>' +
        '<text x="110" y="140" text-anchor="middle" font-size="11" fill="#7b8db0">纽扣电池(常见于电子表、主板)</text>' +
        '</svg>';
    },
    nineVolt: function () {
      // 层叠电池:两个接线端都在筒体上沿(圆形是正极、方/六角形是负极)
      return svgOpen('0 0 220 150') +
        '<defs><linearGradient id="n9" x1="0" x2="1"><stop offset="0" stop-color="#e6ebf3"/><stop offset=".4" stop-color="#fff"/><stop offset="1" stop-color="#c4cedb"/></linearGradient></defs>' +
        '<circle cx="96" cy="26" r="8" fill="#cfd7e2" stroke="#9aa7b5" stroke-width="1.6"/>' +
        '<rect x="118" y="18" width="22" height="14" rx="4" fill="#cfd7e2" stroke="#9aa7b5" stroke-width="1.6"/>' +
        '<rect x="56" y="32" width="76" height="90" rx="8" fill="url(#n9)" stroke="#94a1b1" stroke-width="2"/>' +
        '<rect x="56" y="32" width="76" height="24" fill="#2f4f7a" opacity=".85"/>' +
        '<text x="94" y="88" text-anchor="middle" font-size="20" font-weight="700" fill="#37424f">9V</text>' +
        '<text x="110" y="140" text-anchor="middle" font-size="11" fill="#7b8db0">层叠电池(内部由 6 节小电池串联)</text>' +
        '</svg>';
    },
    bulb: function () {
      return svgOpen('0 0 220 150') +
        '<defs><radialGradient id="bulbg" cx=".4" cy=".32"><stop offset="0" stop-color="#ffffff" stop-opacity=".95"/><stop offset="1" stop-color="#cfe0f2" stop-opacity=".55"/></radialGradient></defs>' +
        '<path d="M78 96 L142 96 L138 118 L82 118 Z" fill="url(#bulbg)" stroke="#9fb2c9" stroke-width="2"/>' +
        '<circle cx="110" cy="66" r="42" fill="url(#bulbg)" stroke="#9fb2c9" stroke-width="2"/>' +
        '<path d="M96 92 L96 74 L104 66 L112 74 L120 66 L124 74" fill="none" stroke="#c9701a" stroke-width="2.5"/>' +
        '<rect x="82" y="116" width="56" height="8" rx="3" fill="#b9a887"/>' +
        '<rect x="82" y="126" width="56" height="8" rx="3" fill="#a8977316" stroke="#b9a887" stroke-width="1.5"/>' +
        '<rect x="88" y="136" width="44" height="9" rx="4" fill="#8e99a8"/>' +
        '<text x="110" y="24" text-anchor="middle" font-size="11" fill="#7b8db0">灯丝通电发热发光</text>' +
        '</svg>';
    },
    resistorAxial: function (bands, label) {
      var x = 62, out = svgOpen('0 0 220 150') +
        '<line x1="16" y1="75" x2="62" y2="75" stroke="#b9c3cf" stroke-width="4"/>' +
        '<line x1="158" y1="75" x2="204" y2="75" stroke="#b9c3cf" stroke-width="4"/>' +
        '<rect x="62" y="55" width="96" height="40" rx="12" fill="#e8d8b8" stroke="#c2ab84" stroke-width="2"/>';
      bands.forEach(function (c, i) {
        out += '<rect x="' + (78 + i * 20) + '" y="55" width="10" height="40" fill="' + c + '"/>';
      });
      out += '<text x="110" y="125" text-anchor="middle" font-size="13" font-weight="700" fill="#3a4656">' + label + '</text>' +
        '<text x="110" y="30" text-anchor="middle" font-size="11" fill="#7b8db0">色环表示阻值(碳膜电阻)</text></svg>';
      return out;
    },
    rheostat: function (label) {
      return svgOpen('0 0 220 150') +
        '<defs><linearGradient id="rheo1" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f3f6fa"/><stop offset="1" stop-color="#c8d2df"/></linearGradient></defs>' +
        '<rect x="42" y="72" width="136" height="42" rx="8" fill="url(#rheo1)" stroke="#9aa7b5" stroke-width="2"/>' +
        (function () { var s = ''; for (var i = 0; i < 13; i++) s += '<line x1="' + (50 + i * 10) + '" y1="72" x2="' + (50 + i * 10) + '" y2="114" stroke="#b58a4a" stroke-width="2.6"/>'; return s; })() +
        '<rect x="36" y="40" width="148" height="7" rx="3" fill="#8e99a8"/>' +
        '<rect x="96" y="34" width="26" height="42" rx="4" fill="#c9701a"/>' +
        '<line x1="109" y1="20" x2="109" y2="36" stroke="#8e99a8" stroke-width="5"/>' +
        '<circle cx="109" cy="18" r="7" fill="#e2b25e" stroke="#b58a4a" stroke-width="2"/>' +
        '<rect x="30" y="114" width="16" height="12" rx="3" fill="#8e99a8"/>' +
        '<rect x="174" y="114" width="16" height="12" rx="3" fill="#8e99a8"/>' +
        '<text x="110" y="142" text-anchor="middle" font-size="13" font-weight="700" fill="#3a4656">滑动变阻器 ' + label + '</text>' +
        '<text x="110" y="26" text-anchor="middle" font-size="11" fill="#7b8db0">移动滑片改变接入电阻</text>' +
        '</svg>';
    },
    meter: function (letter, color, ranges) {
      return svgOpen('0 0 220 150') +
        '<rect x="34" y="24" width="152" height="106" rx="10" fill="#f4f7fb" stroke="#9aa7b5" stroke-width="2"/>' +
        '<rect x="44" y="34" width="132" height="74" rx="6" fill="#ffffff" stroke="#c3cedb" stroke-width="1.5"/>' +
        '<path d="M64 96 A52 52 0 0 1 156 96" fill="none" stroke="#c3cedb" stroke-width="2"/>' +
        (function () { var s = ''; for (var i = 0; i <= 10; i++) { var a = Math.PI - i * Math.PI / 10; var x1 = 110 + Math.cos(a) * 46, y1 = 96 - Math.sin(a) * 46; var x2 = 110 + Math.cos(a) * 52, y2 = 96 - Math.sin(a) * 52; s += '<line x1="' + x1.toFixed(1) + '" y1="' + y1.toFixed(1) + '" x2="' + x2.toFixed(1) + '" y2="' + y2.toFixed(1) + '" stroke="#9aa7b5" stroke-width="1.5"/>'; } return s; })() +
        '<line x1="110" y1="96" x2="150" y2="60" stroke="' + color + '" stroke-width="3" stroke-linecap="round"/>' +
        '<circle cx="110" cy="96" r="5" fill="#5b6b86"/>' +
        '<text x="110" y="120" text-anchor="middle" font-size="20" font-weight="700" fill="' + color + '">' + letter + '</text>' +
        '<text x="110" y="145" text-anchor="middle" font-size="11" fill="#7b8db0">' + ranges + '</text>' +
        '</svg>';
    },
    motorArt: function () {
      return svgOpen('0 0 220 150') +
        '<defs><linearGradient id="mot1" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#eef2f8"/><stop offset="1" stop-color="#bcc7d5"/></linearGradient></defs>' +
        '<rect x="58" y="52" width="96" height="58" rx="12" fill="url(#mot1)" stroke="#94a1b1" stroke-width="2"/>' +
        '<ellipse cx="58" cy="81" rx="10" ry="29" fill="#d5dee9" stroke="#94a1b1" stroke-width="2"/>' +
        '<ellipse cx="154" cy="81" rx="10" ry="29" fill="#d5dee9" stroke="#94a1b1" stroke-width="2"/>' +
        '<rect x="158" y="74" width="34" height="13" rx="5" fill="#9aa7b5"/>' +
        '<circle cx="196" cy="80" r="7" fill="#7b8db0"/>' +
        '<path d="M74 110 L74 132 M146 110 L146 132" stroke="#c02a2a" stroke-width="3"/>' +
        '<path d="M86 52 L86 42 M134 52 L134 42" stroke="#2d6fae" stroke-width="3"/>' +
        '<text x="110" y="24" text-anchor="middle" font-size="11" fill="#7b8db0">通电后转轴转动,输出机械能</text>' +
        '<text x="110" y="146" text-anchor="middle" font-size="11" fill="#7b8db0">两根引线接电源</text>' +
        '</svg>';
    },
    ledArt: function (color) {
      return svgOpen('0 0 220 150') +
        '<defs><radialGradient id="led1" cx=".38" cy=".3"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="' + color + '"/></radialGradient></defs>' +
        '<path d="M74 92 A36 34 0 0 1 146 92 Z" fill="url(#led1)" stroke="#8e99a8" stroke-width="2"/>' +
        '<rect x="70" y="88" width="80" height="10" rx="4" fill="#c3cedb" stroke="#94a1b1" stroke-width="1.5"/>' +
        '<path d="M92 98 L88 132" stroke="#8e99a8" stroke-width="4"/>' +
        '<path d="M128 98 L132 120" stroke="#8e99a8" stroke-width="4"/>' +
        '<text x="110" y="26" text-anchor="middle" font-size="11" fill="#7b8db0">长脚接正极、短脚接负极</text>' +
        '<text x="110" y="147" text-anchor="middle" font-size="11" fill="#7b8db0">发光颜色由材料决定</text>' +
        '</svg>';
    },
    bellArt: function () {
      return svgOpen('0 0 220 150') +
        '<defs><linearGradient id="bell1" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffe9a8"/><stop offset="1" stop-color="#d9a53c"/></linearGradient></defs>' +
        '<path d="M62 96 A48 44 0 0 1 158 96 Z" fill="url(#bell1)" stroke="#b58a4a" stroke-width="2"/>' +
        '<rect x="54" y="94" width="112" height="10" rx="4" fill="#c8a05a" stroke="#b58a4a" stroke-width="1.5"/>' +
        '<circle cx="110" cy="100" r="9" fill="#8e99a8"/>' +
        '<line x1="110" y1="108" x2="110" y2="128" stroke="#8e99a8" stroke-width="5"/>' +
        '<rect x="42" y="126" width="16" height="12" rx="3" fill="#8e99a8"/>' +
        '<rect x="162" y="126" width="16" height="12" rx="3" fill="#8e99a8"/>' +
        '<text x="110" y="34" text-anchor="middle" font-size="11" fill="#7b8db0">电磁铁吸动锤子敲击铃碗</text>' +
        '</svg>';
    },
    fuseArt: function (amp) {
      return svgOpen('0 0 220 150') +
        '<rect x="44" y="62" width="132" height="34" rx="16" fill="#f2f7fb" fill-opacity=".9" stroke="#a8b6c6" stroke-width="2"/>' +
        '<rect x="34" y="58" width="20" height="42" rx="6" fill="#b9c3cf" stroke="#94a1b1" stroke-width="1.5"/>' +
        '<rect x="166" y="58" width="20" height="42" rx="6" fill="#b9c3cf" stroke="#94a1b1" stroke-width="1.5"/>' +
        '<line x1="54" y1="79" x2="166" y2="79" stroke="#c9701a" stroke-width="2.5"/>' +
        '<text x="110" y="126" text-anchor="middle" font-size="13" font-weight="700" fill="#3a4656">额定电流 ' + amp + '</text>' +
        '<text x="110" y="40" text-anchor="middle" font-size="11" fill="#7b8db0">玻璃管内是易熔的金属丝</text>' +
        '</svg>';
    },
    switchArt: function (kind) {
      if (kind === 'push') {
        return svgOpen('0 0 220 150') +
          '<rect x="46" y="86" width="128" height="26" rx="6" fill="#dde5ef" stroke="#94a1b1" stroke-width="2"/>' +
          '<rect x="94" y="42" width="32" height="30" rx="6" fill="#c02a2a" stroke="#8e2a2a" stroke-width="2"/>' +
          '<rect x="100" y="70" width="20" height="18" fill="#9aa7b5"/>' +
          '<circle cx="70" cy="99" r="6" fill="#8e99a8"/><circle cx="150" cy="99" r="6" fill="#8e99a8"/>' +
          '<text x="110" y="136" text-anchor="middle" font-size="11" fill="#7b8db0">按下接通、松手断开(按钮开关)</text>' +
          '</svg>';
      }
      return svgOpen('0 0 220 150') +
        '<rect x="34" y="92" width="152" height="22" rx="6" fill="#dde5ef" stroke="#94a1b1" stroke-width="2"/>' +
        '<circle cx="70" cy="92" r="9" fill="#b9c3cf" stroke="#8e99a8" stroke-width="2"/>' +
        '<circle cx="150" cy="92" r="9" fill="#b9c3cf" stroke="#8e99a8" stroke-width="2"/>' +
        '<line x1="70" y1="88" x2="146" y2="54" stroke="#c9701a" stroke-width="7" stroke-linecap="round"/>' +
        '<circle cx="70" cy="88" r="5" fill="#8e99a8"/>' +
        '<text x="110" y="136" text-anchor="middle" font-size="11" fill="#7b8db0">刀开关:合上刀闸电路接通</text>' +
        '</svg>';
    },
    conductorArt: function (kind) {
      var head = svgOpen('0 0 220 150');
      if (kind === 'copper') {
        return head +
          '<path d="M40 96 C70 40 150 40 180 96" fill="none" stroke="#c9702a" stroke-width="7" stroke-linecap="round"/>' +
          '<path d="M52 100 C80 52 140 52 168 100" fill="none" stroke="#e08b3a" stroke-width="5" stroke-linecap="round"/>' +
          '<text x="110" y="132" text-anchor="middle" font-size="12" font-weight="700" fill="#3a4656">铜丝(铜的导电性能仅次于银)</text>' +
          '</svg>';
      }
      if (kind === 'iron') {
        return head +
          '<path d="M96 34 L124 34 L118 118 L102 118 Z" fill="#98a3b2" stroke="#6b7280" stroke-width="2"/>' +
          '<ellipse cx="110" cy="34" rx="20" ry="7" fill="#c3cedb" stroke="#6b7280" stroke-width="2"/>' +
          '<path d="M110 118 L110 128" stroke="#6b7280" stroke-width="4"/>' +
          '<text x="110" y="146" text-anchor="middle" font-size="12" font-weight="700" fill="#3a4656">铁钉(铁的电阻约为铜的 6 倍)</text>' +
          '</svg>';
      }
      if (kind === 'graphite') {
        return head +
          '<rect x="46" y="60" width="128" height="18" rx="4" fill="#c9a06a" stroke="#a5804f" stroke-width="2"/>' +
          '<rect x="54" y="64" width="112" height="10" rx="3" fill="#3f3f46"/>' +
          '<rect x="36" y="58" width="12" height="22" rx="3" fill="#8e99a8"/>' +
          '<text x="110" y="120" text-anchor="middle" font-size="12" font-weight="700" fill="#3a4656">铅笔芯(石墨,电阻比金属大得多)</text>' +
          '</svg>';
      }
      if (kind === 'salt') {
        return head +
          '<path d="M62 44 L62 122 L158 122 L158 44" fill="#eaf3fd" fill-opacity=".8" stroke="#9aa7b5" stroke-width="3"/>' +
          '<path d="M64 74 L156 74 L156 120 L64 120 Z" fill="#7fb2e8" fill-opacity=".75"/>' +
          '<circle cx="88" cy="90" r="4" fill="#ffffff" fill-opacity=".7"/>' +
          '<circle cx="126" cy="104" r="5" fill="#ffffff" fill-opacity=".6"/>' +
          '<rect x="52" y="40" width="116" height="8" rx="4" fill="#c3cedb"/>' +
          '<text x="110" y="142" text-anchor="middle" font-size="12" font-weight="700" fill="#3a4656">盐水(酸碱盐溶液都能导电)</text>' +
          '</svg>';
      }
      return head +
        '<rect x="52" y="52" width="116" height="50" rx="8" fill="#f0e2c8" stroke="#b58a4a" stroke-width="2"/>' +
        '<text x="110" y="84" text-anchor="middle" font-size="14" font-weight="700" fill="#8a5a2b">镍铬合金丝</text>' +
        '<text x="110" y="126" text-anchor="middle" font-size="12" fill="#3a4656">电阻率大,常用于发热丝与实验电阻丝</text>' +
        '</svg>';
    },
    junctionArt: function () {
      return svgOpen('0 0 220 150') +
        '<rect x="88" y="34" width="44" height="56" rx="8" fill="#e2b25e" stroke="#b58a4a" stroke-width="2"/>' +
        '<rect x="96" y="24" width="28" height="14" rx="4" fill="#b9c3cf" stroke="#8e99a8" stroke-width="1.5"/>' +
        '<line x1="110" y1="90" x2="110" y2="128" stroke="#8e99a8" stroke-width="5"/>' +
        '<circle cx="110" cy="134" r="8" fill="#8e99a8"/>' +
        '<text x="110" y="24" text-anchor="middle" font-size="11" fill="#7b8db0">接线柱 / 接线夹</text>' +
        '<text x="110" y="148" text-anchor="middle" font-size="11" fill="#7b8db0">用来把多根导线可靠地连在一起</text>' +
        '</svg>';
    }
  };

  // —— 图鉴条目
  const LIBRARY = [
    {
      id: 'battery', name: '电池', cat: '电源', sym: SYM.battery(), art: ART.dryCell('#2f4f7a', '1.5V'),
      desc: '电池是把化学能转化为电能的装置,为电路提供电压(电压是形成电流的原因)。它有正极(+)和负极(-),电流从正极流出、经外电路回到负极。',
      params: [['电路符号', '长线=正极,短线=负极'], ['本程序可调电压', '1.5 V ~ 6 V'], ['本程序内阻 r', '0.1 Ω ~ 2 Ω(真实干电池约 0.3~1 Ω)']],
      variants: [
        { name: '1.5 V 干电池(AA/5 号)', spec: '电压 1.5 V', note: '最常用;两节串联得 3 V,正是本程序默认电源', art: ART.dryCell('#2f4f7a', '1.5V') },
        { name: '3 V 纽扣电池', spec: '电压 3 V', note: '体积小,用于电子表、计算器、主板', art: ART.coinCell() },
        { name: '9 V 层叠电池', spec: '电压 9 V', note: '内部是 6 节 1.5 V 小电池串联,常用于万用表、遥控器', art: ART.nineVolt() },
        { name: '电池组(2 节串联)', spec: '电压 3 V', note: '串联时电压相加;实验中常把两节电池装进电池盒', art: ART.dryCell('#22405f', '×2') }
      ],
      tips: ['串联电池组电压相加:2 节 1.5 V 串联=3 V', '电池内阻不能忽略:电流越大,路端电压越低', '不要把电池两极用导线直接连接(短路)']
    },
    {
      id: 'switch', name: '开关', cat: '控制元件', sym: SYM.switch(), art: ART.switchArt('knife'),
      desc: '开关用来控制电路的通断。闭合时电路接通、有电流;断开时电路成为断路、没有电流。它是“电路的阀门”。',
      params: [['状态', '断开 / 闭合'], ['作用', '控制电路通断,安全地启停用电器']],
      variants: [
        { name: '单刀单掷开关(刀开关)', spec: '通 / 断两态', note: '实验室最常用,闭合时刀闸落下接通电路', art: ART.switchArt('knife') },
        { name: '按钮开关', spec: '按下接通', note: '电铃、门铃常用;按下时接通,松手断开', art: ART.switchArt('push') }
      ],
      tips: ['开关要串联在电路中,且应接在火线一侧(家庭电路)', '闭合开关前先检查电路,避免短路']
    },
    {
      id: 'bulb', name: '小灯泡', cat: '用电器', sym: SYM.bulb(), art: ART.bulb(),
      desc: '灯泡把电能转化为光能和内能。电流通过灯丝时发热,温度升高到白炽状态就发光;功率越大越亮。',
      params: [['本程序可调电阻', '5 Ω ~ 30 Ω'], ['亮度依据', 'P = UI = I²R,相对额定功率换算']],
      variants: [
        { name: '2.5 V 0.3 A 小灯泡', spec: '额定功率 0.75 W', note: '实验室最常见,配两节干电池使用', art: ART.bulb() },
        { name: '3.8 V 0.3 A 小灯泡', spec: '额定功率 1.14 W', note: '手电筒灯泡,需要 3 节干电池', art: ART.bulb() },
        { name: '6 V 0.5 A 小灯泡', spec: '额定功率 3 W', note: '较亮,用于需要明显亮度对比的实验', art: ART.bulb() },
        { name: '高阻值小灯珠(10 Ω)', spec: 'R = 10 Ω', note: '本程序默认值,配 3 V 电源亮度约 80%', art: ART.bulb() }
      ],
      tips: ['实际灯丝电阻会随温度升高而变大', '电压过高会烧坏灯丝,实验中不要让灯泡两端电压超过额定值']
    },
    {
      id: 'resistor', name: '定值电阻', cat: '用电器', sym: SYM.resistor(), art: ART.resistorAxial(['#8b5a2b', '#000000', '#c02a2a', '#c9a227'], '20 Ω ±5%'),
      desc: '电阻是导体本身的一种性质,用来限制电流、分压和保护电路。定值电阻的阻值固定不变,常与灯泡、电表配合使用。',
      params: [['本程序可调阻值', '5 Ω ~ 100 Ω'], ['常见精度', '±1% / ±5%'], ['额定功率', '常用 1/4 W']],
      variants: [
        { name: '5 Ω', spec: '色环:绿黑黑金', note: '限流作用强,常做保护电阻', art: ART.resistorAxial(['#2e8b57', '#000000', '#000000', '#c9a227'], '5 Ω') },
        { name: '10 Ω', spec: '色环:棕黑黑金', note: '与 3 V 电源配合电流约 0.3 A', art: ART.resistorAxial(['#8b5a2b', '#000000', '#000000', '#c9a227'], '10 Ω') },
        { name: '20 Ω', spec: '色环:红黑黑金', note: '本程序默认值', art: ART.resistorAxial(['#c02a2a', '#000000', '#000000', '#c9a227'], '20 Ω') },
        { name: '50 Ω', spec: '色环:绿黑黑金', note: '阻值大、电流小,适合做分压实验', art: ART.resistorAxial(['#2e8b57', '#000000', '#000000', '#c9a227'], '50 Ω') }
      ],
      tips: ['色环口诀:棕1 红2 橙3 黄4 绿5 蓝6 紫7 灰8 白9 黑0', '电阻串联相当于变长、并联相当于变粗']
    },
    {
      id: 'conductor', name: '导体', cat: '研究对象', sym: SYM.conductor(), art: ART.conductorArt('copper'),
      desc: '导体是容易导电的物体。它的电阻由材料、长度、横截面积共同决定:R = ρL/S —— 材料不同(电阻率 ρ 不同)、越长、越细,电阻就越大。',
      params: [['可换材料', '13 种(银/铜/金/铝/铁/镍铬合金/铅笔芯/盐水/湿木/硅/干木/玻璃/橡胶)'], ['长度 L', '0.1 m ~ 2 m'], ['横截面积 S', '0.01 mm² ~ 1 mm²']],
      variants: [
        { name: '铜', spec: 'ρ = 0.017', note: '导电性能极好,导线都用铜芯,排在银之后', art: ART.conductorArt('copper') },
        { name: '铁', spec: 'ρ = 0.10', note: '同样粗细长度时,电阻约为铜的 6 倍', art: ART.conductorArt('iron') },
        { name: '铅笔芯(石墨)', spec: 'ρ = 10', note: '非金属导体,电阻比金属大得多', art: ART.conductorArt('graphite') },
        { name: '盐水', spec: 'ρ = 500', note: '酸碱盐的水溶液都能导电,属于离子导电', art: ART.conductorArt('salt') },
        { name: '镍铬合金', spec: 'ρ = 1.1', note: '电阻率大,做发热丝和实验电阻丝', art: ART.conductorArt('nichrome') }
      ],
      tips: ['教材实验:控制长度和横截面积不变,只换材料,比较电流大小', '绝缘体(橡胶、玻璃)电阻率极大,几乎不导电;半导体(硅、锗)介于两者之间']
    },
    {
      id: 'rheostat', name: '滑动变阻器', cat: '控制元件', sym: SYM.rheostat(), art: ART.rheostat('20 Ω'),
      desc: '滑动变阻器通过移动滑片改变接入电路的电阻丝长度,从而连续改变电阻。常用于调节电流、控制灯泡亮度、做“伏安法测电阻”实验。',
      params: [['本程序可调阻值', '0 Ω ~ 50 Ω'], ['真实规格', '常见 10 Ω / 20 Ω / 50 Ω / 100 Ω,额定电流 1 A~2 A'], ['接法', '“一上一下”两个接线柱接入电路']],
      variants: [
        { name: '10 Ω 滑动变阻器', spec: '最大阻值 10 Ω', note: '阻值范围小,调节灵敏', art: ART.rheostat('10 Ω') },
        { name: '20 Ω 滑动变阻器', spec: '最大阻值 20 Ω', note: '本程序默认值', art: ART.rheostat('20 Ω') },
        { name: '50 Ω 滑动变阻器', spec: '最大阻值 50 Ω', note: '实验室最常见规格', art: ART.rheostat('50 Ω') },
        { name: '100 Ω 滑动变阻器', spec: '最大阻值 100 Ω', note: '阻值大,可用于大幅度限流', art: ART.rheostat('100 Ω') }
      ],
      tips: ['闭合开关前,应把滑片移到阻值最大处,保护电路', '接“一上一下”时滑片才起作用;接“两上”或“两下”电阻不变']
    },
    {
      id: 'ammeter', name: '电流表', cat: '测量仪表', sym: SYM.ammeter(), art: ART.meter('A', '#1d7f5f', '量程 0~0.6 A / 0~3 A'),
      desc: '电流表用来测量电路中的电流,必须串联在被测电路中。它的内阻很小(理想情况下为零),所以不能直接接到电源两极上,否则会短路。',
      params: [['本程序内阻', '约 0.02 Ω(理想电流表)'], ['真实量程', '0~0.6 A(0.02 A/格)或 0~3 A(0.1 A/格)'], ['接法', '串联,电流从“+”接线柱流入']],
      variants: [
        { name: '0 ~ 0.6 A 量程', spec: '分度值 0.02 A', note: '精度高,适合小电流(如小灯泡 0.3 A)', art: ART.meter('A', '#1d7f5f', '0~0.6 A   0.02 A/格') },
        { name: '0 ~ 3 A 量程', spec: '分度值 0.1 A', note: '量程大,适合电动机、大电流场合', art: ART.meter('A', '#1d7f5f', '0~3 A   0.1 A/格') }
      ],
      tips: ['“+”接线柱接电流流入端,反接指针会反偏', '使用前先估计电流大小,选合适的量程(可先试触)']
    },
    {
      id: 'voltmeter', name: '电压表', cat: '测量仪表', sym: SYM.voltmeter(), art: ART.meter('V', '#2d6fae', '量程 0~3 V / 0~15 V'),
      desc: '电压表用来测量某段电路两端的电压,必须并联在被测元件两端。它的内阻很大(理想情况下无穷大),几乎不通过电流,所以可以直接并在电源两端测电源电压。',
      params: [['本程序内阻', '约 1 MΩ(理想电压表)'], ['真实量程', '0~3 V(0.1 V/格)或 0~15 V(0.5 V/格)'], ['接法', '并联,电流从“+”接线柱流入']],
      variants: [
        { name: '0 ~ 3 V 量程', spec: '分度值 0.1 V', note: '测量干电池、小灯泡电压常用', art: ART.meter('V', '#2d6fae', '0~3 V   0.1 V/格') },
        { name: '0 ~ 15 V 量程', spec: '分度值 0.5 V', note: '测量电源电压或较高电压', art: ART.meter('V', '#2d6fae', '0~15 V   0.5 V/格') }
      ],
      tips: ['电压表要与被测元件并联,不能串联', '量程选大了读数不准,选小了会打表']
    },
    {
      id: 'motor', name: '电动机', cat: '用电器', sym: SYM.motor(), art: ART.motorArt(),
      desc: '电动机把电能转化为机械能。通电线圈在磁场中受力转动,电流越大转速越快。生活中的电风扇、玩具车、洗衣机都用到电动机。',
      params: [['本程序可调线圈电阻', '5 Ω ~ 50 Ω'], ['转速', '与电流成正比(程序中按电流换算)']],
      variants: [
        { name: '3 V 小电动机', spec: '线圈电阻约 15 Ω', note: '本程序默认值,配 3 V 电源转动明显', art: ART.motorArt() },
        { name: '6 V 小电动机', spec: '线圈电阻约 30 Ω', note: '功率更大,可带动小风扇叶片', art: ART.motorArt() }
      ],
      tips: ['电动机工作时电能主要转化为机械能,同时线圈发热', '把电动机卡住不转时电流会变大,容易烧坏线圈(本程序可观察电流变化)']
    },
    {
      id: 'led', name: '发光二极管(LED)', cat: '用电器', sym: SYM.led(), art: ART.ledArt('#d3453a'),
      desc: 'LED 具有单向导电性:电流只能从正极(阳极)流入、从负极(阴极)流出,这时才导通发光;反接时几乎不导电、不发光。它把电能转化为光能,效率比灯泡高得多。',
      params: [['本程序可调导通压降 Vf', '1.5 V ~ 2.5 V'], ['本程序内阻', '10 Ω ~ 100 Ω'], ['必须串联', '限流电阻,否则会因电流过大烧毁']],
      variants: [
        { name: '红色 LED', spec: 'Vf ≈ 1.8 V', note: '最常见,本程序默认值', art: ART.ledArt('#d3453a') },
        { name: '绿色 LED', spec: 'Vf ≈ 2.1 V', note: '亮度高,常用作指示灯', art: ART.ledArt('#2f9e44') },
        { name: '蓝色 / 白色 LED', spec: 'Vf ≈ 3.0 V', note: '需要 3 V 以上电源,通常要串联电阻限流', art: ART.ledArt('#2d6fae') }
      ],
      tips: ['长脚是正极,短脚是负极;管壳上的平面一侧是负极', '把 LED 直接接在电源两端很容易烧坏,必须串联限流电阻']
    },
    {
      id: 'bell', name: '电铃', cat: '用电器', sym: SYM.bell(), art: ART.bellArt(),
      desc: '电铃利用电磁铁工作:通电时电磁铁吸引衔铁,锤子敲击铃碗发声;同时电路被断开,电磁铁失磁,锤子弹回又接通电路,如此反复振动发声。',
      params: [['本程序可调线圈电阻', '5 Ω ~ 50 Ω'], ['音量', '随电流增大而变响、敲击变快(0.05 A 起响,0.25 A 满音量)']],
      variants: [
        { name: '3 V 直流电铃', spec: '线圈电阻约 12 Ω', note: '本程序默认值;串联滑动变阻器可以听到音量变化', art: ART.bellArt() },
        { name: '6 V 直流电铃', spec: '线圈电阻约 25 Ω', note: '声音更响,适合大教室演示', art: ART.bellArt() }
      ],
      tips: ['电铃把电能转化为机械能(声能),不是纯电阻', '串联滑动变阻器改变电流,就能听到音量变化']
    },
    {
      id: 'fuse', name: '保险丝', cat: '保护元件', sym: SYM.fuse(), art: ART.fuseArt('0.5 A'),
      desc: '保险丝由电阻较大、熔点较低的金属制成,串联在电路中。当电流超过额定值时,它先熔断切断电路,从而保护电源和其他元件。',
      params: [['本程序可调额定电流 Imax', '0.1 A ~ 3 A'], ['材料', '铅锑合金(熔点低、电阻大)'], ['熔断后', '需更换,不能简单用铜丝代替']],
      variants: [
        { name: '0.3 A 保险丝', spec: '额定电流 0.3 A', note: '保护小灯泡电路', art: ART.fuseArt('0.3 A') },
        { name: '0.5 A 保险丝', spec: '额定电流 0.5 A', note: '本程序默认值', art: ART.fuseArt('0.5 A') },
        { name: '1 A 保险丝', spec: '额定电流 1 A', note: '用于电流稍大的电路', art: ART.fuseArt('1 A') }
      ],
      tips: ['保险丝要串联在电路中,不能并联', '绝不能用铁丝、铜丝代替保险丝——它们不会及时熔断,起不到保护作用']
    },
    {
      id: 'junction', name: '接线点(接线柱)', cat: '连接件', sym: SYM.junction(), art: ART.junctionArt(),
      desc: '接线柱、接线夹用来把多根导线可靠地连接在一起。在电路图中,导线交汇且相连的地方要画一个实心点,表示这里电气上是同一个节点。',
      params: [['本程序功能', '四个方向内部导通,用于导线拐弯与分支'], ['电路图表示', '实心圆点=相连;无点=不相连']],
      variants: [
        { name: '接线柱', spec: '旋紧螺丝压紧导线', note: '实验室电源、电表上常见', art: ART.junctionArt() },
        { name: '导线分叉(节点)', spec: '多根导线交于一点', note: '并联电路的分支点,本程序用“接线点”元件表示', art: SYM.junction() }
      ],
      tips: ['并联电路中,干路电流等于各支路电流之和,节点处电流守恒', '接线要牢固,接触不良会使电阻变大、灯泡变暗']
    }
  ];

  const libOverlay = document.getElementById('libOverlay');
  const libSide = document.getElementById('libSide');
  const libMain = document.getElementById('libMain');
  let libCurrent = LIBRARY[0].id;

  function renderLibSide() {
    if (!libSide) return;
    libSide.innerHTML = LIBRARY.map(function (e) {
      return '<button class="lib-item' + (e.id === libCurrent ? ' on' : '') + '" data-lib="' + e.id + '">' +
        '<span class="lib-cat">' + e.cat + '</span>' + e.name + '</button>';
    }).join('');
  }
  function renderLibMain() {
    if (!libMain) return;
    let e = null;
    for (let i = 0; i < LIBRARY.length; i++) if (LIBRARY[i].id === libCurrent) e = LIBRARY[i];
    if (!e) return;
    let html = '<div class="lib-title">' + e.name + '<span class="lib-tag">' + e.cat + '</span></div>' +
      '<div class="lib-figs">' +
      '<figure class="lib-fig"><figcaption>电路符号</figcaption>' + e.sym + '</figure>' +
      '<figure class="lib-fig"><figcaption>实物示意</figcaption>' + e.art + '</figure>' +
      '</div>' +
      '<div class="lib-desc">' + e.desc + '</div>' +
      '<div class="lib-h">主要参数</div><table class="lib-table">' +
      e.params.map(function (p) { return '<tr><th>' + p[0] + '</th><td>' + p[1] + '</td></tr>'; }).join('') +
      '</table>';
    if (e.variants && e.variants.length) {
      html += '<div class="lib-h">常见规格(多种参数)</div><div class="lib-variants">' +
        e.variants.map(function (v) {
          return '<div class="lib-variant">' +
            '<div class="lib-vart">' + v.name + '</div>' +
            '<div class="lib-varspec">' + v.spec + '</div>' +
            '<div class="lib-varart">' + v.art + '</div>' +
            '<div class="lib-varnote">' + v.note + '</div>' +
            '</div>';
        }).join('') + '</div>';
    }
    if (e.tips && e.tips.length) {
      html += '<div class="lib-h">实验提示</div><ul class="lib-tips">' +
        e.tips.map(function (t) { return '<li>' + t + '</li>'; }).join('') + '</ul>';
    }
    libMain.innerHTML = html;
  }
  // 在 body 的 class 上增删一个标记(保留暗色主题等其他类)
  // 给元素增删一个 class(有的环境/测试桩没有 classList,做兼容)
  function setElClass(el, name, on) {
    if (!el) return;
    if (el.classList && el.classList.add) {
      if (on) el.classList.add(name); else el.classList.remove(name);
      return;
    }
    const parts = String(el.className || '').split(/\s+/).filter(function (c) { return c && c !== name; });
    if (on) parts.push(name);
    el.className = parts.join(' ');
  }
  function setBodyFlag(name, on) {
    if (!document.body) return;
    const parts = String(document.body.className || '').split(/\s+/).filter(function (c) { return c && c !== name; });
    if (on) parts.push(name);
    document.body.className = parts.join(' ');
  }
  function openLibrary(id) {
    if (!libOverlay) return;
    if (id) libCurrent = id;
    renderLibSide(); renderLibMain();
    libOverlay.hidden = false;
    setBodyFlag('lib-open', true);
    libMain.scrollTop = 0;
    if (learnOn) learnHighlight();   // 图鉴打开后立刻把"关闭键"高亮与提示补上
  }
  function closeLibrary() {
    if (!libOverlay) return;
    libOverlay.hidden = true;
    setBodyFlag('lib-open', false);
    if (learnOn) {
      state.learnLibDone = true;     // 主动返回操作界面 → 学习自动进入下一步
      learnHighlight();              // 气泡与高亮立刻收起
    }
  }
  const btnLib = document.getElementById('btnLib');
  if (btnLib) btnLib.addEventListener('click', function () { openLibrary(); Sound.click(0.5); });
  const libCloseBtn = document.getElementById('libClose');
  if (libCloseBtn) libCloseBtn.addEventListener('click', closeLibrary);
  if (libOverlay) {
    libOverlay.addEventListener('click', function (ev) {
      if (ev.target === libOverlay) { closeLibrary(); return; }   // 点遮罩关闭
      const id = ev.target && ev.target.dataset ? ev.target.dataset.lib : null;
      if (id) { libCurrent = id; renderLibSide(); renderLibMain(); }
    });
  }

  /* ---------- 关于 / 帮助 浮层 ---------- */
  const aboutOverlay = document.getElementById('aboutOverlay');
  const aboutMain = document.getElementById('aboutMain');
  function openAbout() {
    if (!aboutOverlay) return;
    aboutOverlay.hidden = false;
    setBodyFlag('lib-open', true);
    if (aboutMain) aboutMain.scrollTop = 0;
    Sound.click(0.5);
  }
  function closeAbout() {
    if (!aboutOverlay) return;
    aboutOverlay.hidden = true;
    setBodyFlag('lib-open', false);
  }
  const btnAbout = document.getElementById('btnAbout');
  if (btnAbout) btnAbout.addEventListener('click', openAbout);
  const mBtnAboutEl = document.getElementById('mBtnAbout');
  if (mBtnAboutEl) mBtnAboutEl.addEventListener('click', openAbout);   // 手机端底部栏的「帮助」
  const aboutCloseBtn = document.getElementById('aboutClose');
  if (aboutCloseBtn) aboutCloseBtn.addEventListener('click', closeAbout);
  if (aboutOverlay) {
    aboutOverlay.addEventListener('click', function (ev) {
      if (ev.target === aboutOverlay) { closeAbout(); return; }
      const go = ev.target && ev.target.dataset ? ev.target.dataset.goto : null;
      if (go) {
        const el = document.getElementById(go);
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        Array.prototype.forEach.call(aboutOverlay.querySelectorAll('.about-nav'), b => {
          setElClass(b, 'on', b.dataset.goto === go);
        });
      }
    });
  }

  let last = 0;
  // 单帧逻辑(不含 rAF 注册),便于自动化测试手动驱动
  // 灯泡过载寿命倒计时:超过额定 1.5 倍开始计时,累计 1.6 秒烧断;回到安全区就清零(可以救回)
  const BULB_BURN_SEC = 1.6;
  function updateBulbLife(s, dt) {
    if (!s || !s.info) return;
    state.components.forEach(c => {
      if (c.type !== 'bulb' || c.props.burned) { return; }
      const d = s.info.get(c.id);
      if (!d) return;
      const rated = c.props.rated || 1.0;
      if (d.P > rated * 1.5) {
        c.props._hot = (c.props._hot || 0) + dt;
        if (c.props._hot >= BULB_BURN_SEC) {
          c.props.burned = true;
          c.props._hot = 0;
          state.dirty = true;                    // 触发重算:烧断后按断路处理
          state.events.push({ type: 'bulb-burn', x: c.x, y: c.y, P: d.P, rated: rated, cid: c.id });
        }
      } else if (c.props._hot) {
        c.props._hot = 0;                        // 降压/减少过载 → 恢复
      }
    });
  }
  function frameLogic(ts) {
    const s = ensureSolved();
    if (!last) last = ts;
    const dt = Math.min(0.05, Math.max(0, (ts - last) / 1000));
    s._t = (s._t || 0) + dt;
    last = ts;

    if (frameLogic._learnAcc === undefined) frameLogic._learnAcc = 0;
    frameLogic._learnAcc += dt;
    if (frameLogic._learnAcc > 0.5) { frameLogic._learnAcc = 0; try { learnTick(); } catch (e) { } }
    // 长按接线的兜底:setTimeout 可能被节流甚至丢失 → 每帧再看一眼是否已按够时长
    if (state.termPress && !state.termPress.moved) {
      const nowMs = (typeof performance !== 'undefined' ? performance.now() : Date.now());
      if (nowMs - state.termPress.t0 >= TERM_HOLD_MS) { try { tryEnterWireMode(state.termPress); } catch (e) { } }
    }
    updateBulbLife(s, dt);      // 灯泡过载"寿命倒计时"(过载够久才烧断,降压可救回)
    drainEvents();
    updateSparks(s, dt);
    if (state.flash) state.flash.t += dt;
    Sound.tick(dt, audioTargets(s));

    // 世界坐标 → 屏幕坐标:先按缩放,再按平移(tx/ty 是必须的,否则画面会和鼠标错位)
    ctx.setTransform(view.dpr * view.scale, 0, 0, view.dpr * view.scale, view.dpr * view.tx, view.dpr * view.ty);
    const vw = visibleWorld(); ctx.clearRect(vw.x0, vw.y0, vw.w, vw.h);
    drawGrid();
    drawWires(s);
    drawCurrentDots(s);
    state.components.forEach(c => { if (c.type !== 'junction') drawComponent(c, s); });
    state.components.forEach(c => { if (c.type === 'junction') drawComponent(c, s); });
    drawSparks();
    drawTerminals();
    if (!exportMode) {                 // 导出图片时跳过"选中框/框选/拖线预览/长按HUD/缩略图"
      drawSelection();
      drawMarquee();
      drawDragWire();
      try { drawHoldHud(); } catch (e) { }
    }
    drawNotes();
    drawFlash();
    if (!exportMode) drawMinimap(s);
  }
  function frame(ts) {
    frameLogic(ts);
    requestAnimationFrame(frame);
  }

  /* 供自动化测试与排查使用 */
  /* =======================================================================
     简化电路图:从实物连线自动生成标准电路图
     ① 网表:导线 + 接线点做并查集 → 元件成为"支路"(两端是节点)
     ② 归约:串并联识别(串 = 度为 2 的中间节点;并 = 同端节点的两条边)
     ③ 布局:先算尺寸,再产出图元(primitives),与绘制分离(便于测试)
     ④ 绘制:课本标准符号
     ======================================================================= */
  const SchematicLab = (function () {
    const SZ = {
      ELEM_W: 84, ELEM_H: 42,
      GAP_SER: 24, GAP_PAR: 58, RAIL: 26,
      PAD: 36, BAT_W: 58, LEAD: 22,
      FONT: 12, TAG: 11
    };
    /* 每种元件"本体"的半宽:符号从本体边缘一直画到盒子边缘,保证导线接得上 */
    const BODY_HALF = {
      bulb: 13, resistor: 22, conductor: 22, fuse: 22, rheostat: 22,
      switch: 13, ammeter: 14, voltmeter: 14, motor: 14, led: 9, bell: 13, battery: 7
    };
    const INK = '#1b2b45', ACCENT = '#25558f', MUTED = '#6b7f9e';
    const ARROW = '#ff9d2e';   // 电流方向箭头(与主画布橙色电流箭头同色)

    /* 电流方向:I 为元件电流(t0→t1),flip 表示"t0 画在右侧"。
       返回 +1 = 画在右侧的箭头朝右 / -1 = 朝左 / 0 = 无电流(不画)。 */
    function arrowDir(I, flip) {
      if (typeof I !== 'number' || Math.abs(I) < 1e-4) return 0;
      return ((I > 0) === (!flip)) ? 1 : -1;
    }
    function drawArrow(ctx, x, y, axis, dir) {
      ctx.save();
      ctx.fillStyle = ARROW;
      ctx.beginPath();
      if (axis === 'h') {                    // dir +1 = 朝右
        const d = dir >= 0 ? 1 : -1;
        ctx.moveTo(x - 5 * d, y - 5); ctx.lineTo(x + 6 * d, y); ctx.lineTo(x - 5 * d, y + 5);
      } else {                               // dir +1 = 朝下
        const d = dir >= 0 ? 1 : -1;
        ctx.moveTo(x - 5, y - 5 * d); ctx.lineTo(x, y + 6 * d); ctx.lineTo(x + 5, y - 5 * d);
      }
      ctx.closePath();
      ctx.fill();
      ctx.restore();
    }

    /* ---------- 1. 网表 ---------- */
    function buildNetlist() {
      const parent = new Map();
      const find = function (k) {
        let r = k;
        while (parent.get(r) !== r) r = parent.get(r);
        let c = k;
        while (parent.get(c) !== r) { const nx = parent.get(c); parent.set(c, r); c = nx; }
        return r;
      };
      const uni = function (x, y) {
        const rx = find(x), ry = find(y);
        if (rx !== ry) parent.set(rx, ry);
      };
      const key = function (cid, ti) { return cid + '#' + ti; };
      const comps = (state.components || []);
      comps.forEach(function (c) {
        const n = (DEFS[c.type] && DEFS[c.type].terminals.length) || 2;
        for (let i = 0; i < n; i++) { const k = key(c.id, i); if (!parent.has(k)) parent.set(k, k); }
      });
      (state.wires || []).forEach(function (w) {
        const ka = key(w.a.cid, w.a.ti), kb = key(w.b.cid, w.b.ti);
        if (parent.has(ka) && parent.has(kb)) uni(ka, kb);
      });
      comps.forEach(function (c) {
        if (c.type !== 'junction') return;
        for (let i = 1; i < 4; i++) uni(key(c.id, 0), key(c.id, i));
      });
      const idOf = new Map();
      const net = function (k) {
        const r = find(k);
        if (!idOf.has(r)) idOf.set(r, idOf.size);
        return idOf.get(r);
      };
      const branches = [];
      comps.forEach(function (c) {
        if (c.type === 'junction') return;
        const a = net(key(c.id, 0)), b = net(key(c.id, 1));
        branches.push({ id: c.id, c: c, a: a, b: b, short: a === b });
      });
      return { branches: branches, netCount: idOf.size };
    }

    /* ---------- 2. 串并联归约 ---------- */
    function spReduce(edges, A, B) {
      let list = edges.map(function (e) { return { leaf: e.leaf, a: e.a, b: e.b }; });
      let guard = 0;
      while (list.length > 1 && guard++ < 4000) {
        let done = false;
        for (let i = 0; i < list.length && !done; i++) {
          for (let j = i + 1; j < list.length && !done; j++) {
            const e1 = list[i], e2 = list[j];
            if (!((e1.a === e2.a && e1.b === e2.b) || (e1.a === e2.b && e1.b === e2.a))) continue;
            const kids = [];
            if (e1.kind === 'par') kids.push.apply(kids, e1.kids); else kids.push(e1);
            if (e2.kind === 'par') kids.push.apply(kids, e2.kids); else kids.push(e2);
            const node = { kind: 'par', a: e1.a, b: e1.b, kids: kids };
            list = list.filter(function (x) { return x !== e1 && x !== e2; });
            list.push(node);
            done = true;
          }
        }
        if (done) continue;
        const deg = new Map();
        list.forEach(function (e) {
          deg.set(e.a, (deg.get(e.a) || 0) + 1);
          deg.set(e.b, (deg.get(e.b) || 0) + 1);
        });
        let mid = -1;
        deg.forEach(function (d, v) { if (mid < 0 && d === 2 && v !== A && v !== B) mid = v; });
        if (mid < 0) break;
        const e1 = list.find(function (e) { return e.a === mid || e.b === mid; });
        const e2 = list.find(function (e) { return e !== e1 && (e.a === mid || e.b === mid); });
        if (!e1 || !e2) break;
        const o1 = e1.a === mid ? e1.b : e1.a;
        const o2 = e2.a === mid ? e2.b : e2.a;
        list = list.filter(function (x) { return x !== e1 && x !== e2; });
        list.push({ kind: 'ser', a: o1, b: o2, kids: [{ child: e1 }, { child: e2 }] });
      }
      if (list.length !== 1) return null;
      const root = list[0];
      const ok = (root.a === A && root.b === B) || (root.a === B && root.b === A);
      return ok ? root : null;
    }

    /* ---------- 3. 建模 ---------- */
    function build() {
      const nl = buildNetlist();
      const branches = nl.branches;
      const srcs = branches.filter(function (b) { return b.c.type === 'battery'; });
      if (!srcs.length) return { ok: false, reason: '画布上还没有电源,先放一个电池。', kind: null };
      const src = srcs[0];
      if (src.short) return { ok: false, reason: '电源两端直接短接了,没有可以画的回路。', kind: null };
      const A = src.a, B = src.b;
      const others = branches.filter(function (b) { return b !== src && !b.short; });

      const adj = new Map();
      const push = function (n, e) { if (!adj.has(n)) adj.set(n, []); adj.get(n).push(e); };
      others.forEach(function (e) { push(e.a, e); push(e.b, e); });
      const seen = new Set([A]); const queue = [A]; const inMain = new Set();
      while (queue.length) {
        const v = queue.shift();
        (adj.get(v) || []).forEach(function (e) {
          if (inMain.has(e)) return;
          inMain.add(e);
          const w = e.a === v ? e.b : e.a;
          if (!seen.has(w)) { seen.add(w); queue.push(w); }
        });
      }
      const main = others.filter(function (e) { return inMain.has(e); });
      const unconnected = others.filter(function (e) { return !inMain.has(e); });
      const model = {
        ok: true, kind: 'sp', reason: '', src: src, main: main,
        unconnected: unconnected,
        shorted: branches.filter(function (b) { return b.short && b !== src; }),
        tree: null, w: 0, h: 0
      };
      if (!main.length) { model.kind = 'none'; model.reason = '电源没有接成闭合回路。'; return model; }
      if (!seen.has(B)) { model.kind = 'open'; model.reason = '电路没有闭合(电源只有一端接着电路)。'; return model; }

      const tree = spReduce(main.map(function (e) { return { leaf: e, a: e.a, b: e.b }; }), A, B);
      if (!tree) {
        model.kind = 'graph';
        model.reason = '这个连接不是简单串并联(例如电桥),已按连接关系示意。';
        model.graphEdges = [src].concat(main);
        return model;
      }
      model.tree = tree;
      return model;
    }

    /* ---------- 4. 布局 ---------- */
    function measure(n) {
      if (n.leaf) { n.w = SZ.ELEM_W; n.h = SZ.ELEM_H; return n; }
      if (n.kind === 'ser') {
        let w = 0, h = 0;
        n.kids.forEach(function (k, i) {
          measure(k.child);
          w += k.child.w + (i ? SZ.GAP_SER : 0);
          h = Math.max(h, k.child.h);
        });
        n.w = w; n.h = h;
      } else {
        let w = 0, h = 0;
        n.kids.forEach(function (k, i) {
          measure(k);
          w = Math.max(w, k.w + 2 * SZ.RAIL);
          h += k.h + (i ? SZ.GAP_PAR : 0);
        });
        n.w = w; n.h = Math.max(h, SZ.ELEM_H);
      }
      return n;
    }

    function layoutNode(prims, n, x, y, fromNet, netPts) {
      if (n.leaf) {
        const cy = y + n.h / 2;
        const flip = n.a !== fromNet;
        prims.push({ k: 'sym', c: n.leaf.c, cx: x + n.w / 2, cy: cy, flip: flip });
        if (netPts) {
          /* 节点位置要跟翻转走:flip 时 t0 在右、t1 在左 */
          const pl = { x: x, y: cy }, pr = { x: x + n.w, y: cy };
          if (!netPts[n.a]) netPts[n.a] = flip ? pr : pl;
          if (!netPts[n.b]) netPts[n.b] = flip ? pl : pr;
        }
        return { x: x, y: y, w: n.w, h: n.h, cy: cy };
      }
      if (n.kind === 'ser') {
        let cur = x, prev = null;
        /* 到达端是 n.b 时(链相对到达方向是反的):kids 逆序铺,
           否则左端会画成 n.a、与父级导线的网络对不上(元件方向全反)。 */
        const kids = (n.kids.length > 1 && fromNet === n.b && fromNet !== n.a)
          ? n.kids.slice().reverse() : n.kids;
        let netIn = fromNet;
        kids.forEach(function (k) {
          const ch = k.child.h;
          const cyOff = y + (n.h - ch) / 2;
          const r = layoutNode(prims, k.child, cur, cyOff, netIn, netPts);
          if (prev) {
            const x1 = prev.x + prev.w, y1 = prev.cy, x2 = r.x, y2 = r.cy;
            if (Math.abs(y1 - y2) < 0.5) prims.push({ k: 'wire', pts: [[x1, y1], [x2, y2]] });
            else {
              const mx = (x1 + x2) / 2;
              prims.push({ k: 'wire', pts: [[x1, y1], [mx, y1], [mx, y2], [x2, y2]] });
            }
          }
          netIn = (k.child.a === netIn) ? k.child.b : k.child.a;
          prev = r;
          cur += k.child.w + SZ.GAP_SER;
        });
        return { x: x, y: y, w: n.w, h: n.h, cy: y + n.h / 2 };
      }
      // 并联
      const leftX = x + SZ.RAIL / 2, rightX = x + n.w - SZ.RAIL / 2;
      let cur = y; const ys = [];
      n.kids.forEach(function (k) {
        measure(k);
        const kx = leftX + (rightX - leftX - k.w) / 2;
        /* 分支左端接的是"实际到达节点" fromNet —— 并联块本身可能反着存(n.a 在右),
           一律传 n.a 会把分支的翻转算反(对称元件看不出来,箭头会标反)。 */
        const r = layoutNode(prims, k, kx, cur, fromNet, netPts);
        ys.push(r.cy);
        prims.push({ k: 'wire', pts: [[leftX, r.cy], [r.x, r.cy]] });
        prims.push({ k: 'wire', pts: [[r.x + r.w, r.cy], [rightX, r.cy]] });
        cur += k.h + SZ.GAP_PAR;
      });
      const mid = y + n.h / 2;
      const top = Math.min.apply(null, ys.concat([mid]));
      const bot = Math.max.apply(null, ys.concat([mid]));
      prims.push({ k: 'wire', pts: [[leftX, top], [leftX, bot]] });
      prims.push({ k: 'wire', pts: [[rightX, top], [rightX, bot]] });
      prims.push({ k: 'wire', pts: [[x, mid], [leftX, mid]] });
      prims.push({ k: 'wire', pts: [[rightX, mid], [x + n.w, mid]] });
      return { x: x, y: y, w: n.w, h: n.h, cy: mid };
    }

    function layoutLoop(prims, model, sol) {
      measure(model.tree);
      const netW = model.tree.w, netH = model.tree.h;
      const xL = SZ.PAD + 14;                             // 左竖线
      /* 上母线高度 = 网络端口高度:网络垂直居中于上母线,元件沿上边均匀排开 */
      const yP = SZ.PAD + Math.max(24, netH / 2 + 8);
      const netX = xL + SZ.LEAD;                          // 网络左端口
      const netY = yP - netH / 2;
      const portY = yP;
      const yB = Math.max(yP + 96, netY + netH + 30);     // 下母线
      const rightX = netX + netW + SZ.LEAD;
      const W = rightX + SZ.PAD;
      const H = yB + 60;                                  // 底部给电源数值标签 + 读数行留位
      const netPts = {};                                  // 节点 → 画布上的位置(画"被短路元件"用)

      layoutNode(prims, model.tree, netX, netY, model.tree.a, netPts);
      netPts[model.tree.a] = netPts[model.tree.a] || { x: netX, y: portY };
      netPts[model.tree.b] = netPts[model.tree.b] || { x: netX + netW, y: portY };

      /* 四条边:上左 / 上右母线 + 左右竖线;下母线中间断开、让电源横躺在正中 */
      prims.push({ k: 'wire', pts: [[xL, yP], [netX, portY]] });
      prims.push({ k: 'wire', pts: [[netX + netW, portY], [rightX, portY]] });
      prims.push({ k: 'wire', pts: [[xL, yP], [xL, yB]] });
      prims.push({ k: 'wire', pts: [[rightX, portY], [rightX, yB]] });

      const batX = Math.round((xL + rightX) / 2 / 10) * 10;    // 下母线正中
      prims.push({ k: 'wire', pts: [[xL, yB], [batX - 7, yB]] });     // 下母线左段(兼作左引线)
      prims.push({ k: 'wire', pts: [[batX + 7, yB], [rightX, yB]] }); // 下母线右段(兼作右引线)
      /* 电源极性:左端接 tree.a 网络 —— 左板默认画"负"(t0),tree.a 是 t1(正)网络时翻转 */
      const batFlip = model.tree.a === model.src.b;
      prims.push({ k: 'bat', x: batX, y: yB, c: model.src.c, flip: batFlip });

      /* 电流方向箭头(放电顺时针为基准,s 取反即充电/翻转):
         下两段 = s,上两段 = -s,右竖 = -s(向上),左竖 = s(向下)。
         无求解结果或无电流时 s=0,只占位不画。 */
      const s = arrowDir(sol ? sol.battI : 0, batFlip);
      const segs = [
        { x: (xL + netX) / 2, y: yP, axis: 'h', base: -1 },              // 上左:向左
        { x: (netX + netW + rightX) / 2, y: yP, axis: 'h', base: -1 },   // 上右:向左
        { x: rightX, y: (yP + yB) / 2, axis: 'v', base: -1 },            // 右竖:向上
        { x: xL, y: (yP + yB) / 2, axis: 'v', base: 1 },                 // 左竖:向下
        { x: (xL + batX - 7) / 2, y: yB, axis: 'h', base: 1 },           // 下左:向右
        { x: (batX + 7 + rightX) / 2, y: yB, axis: 'h', base: 1 }        // 下右:向右
      ];
      segs.forEach(function (g) {
        prims.push({ k: 'arrow', x: g.x, y: g.y, axis: g.axis, dir: s * g.base });
      });

      /* 被短路的元件:两端落在同一个节点上,串并联树里表达不了(会变成自环),
         但它恰恰是"用电器短路"这类演示的主角,必须画出来:
         画成"元件 + 旁边一根跨接导线"的小回路,挂在该节点的位置下方。 */
      let extraBottom = 0;
      (model.shorted || []).forEach(function (b, i) {
        const at = netPts[b.a] || { x: netX, y: portY };
        const x0 = Math.min(at.x, W - 130);
        const y0 = yB + 50 + i * 96;                   // 50:避开电源数值标签(yB+25..39)
        const boxW = SZ.ELEM_W, boxH = 40;   // boxW = 元件盒宽 → 灯泡引线正好接到左右竖线
        prims.push({ k: 'wire', pts: [[x0, y0], [x0, y0 + boxH]] });
        prims.push({ k: 'sym', c: b.c, cx: x0 + boxW / 2, cy: y0 + boxH, flip: false });
        prims.push({ k: 'wire', pts: [[x0 + boxW, y0 + boxH], [x0 + boxW, y0]] });
        prims.push({ k: 'wire', pts: [[x0, y0], [x0 + boxW, y0]] });        // 跨接导线:就是把它短路的那根
        /* 虚线接回"它真正的节点" at:先在电源下方(yB+46)横移,再沿节点 x 上去;
           若节点正落在电源正上方(±30),绕到电源右上方(yB-46)再进,避免穿过电池和它的标签。 */
        const mx = x0 + boxW / 2, jogY = yB + 46;
        let dashPts;
        if (Math.abs(at.x - batX) < 30) {
          const gate = batX + 52;
          dashPts = [[mx, y0], [mx, jogY], [gate, jogY], [gate, yB - 46], [at.x, yB - 46], [at.x, at.y]];
        } else {
          dashPts = [[mx, y0], [mx, jogY], [at.x, jogY], [at.x, at.y]];
        }
        prims.push({ k: 'wire', dashed: true, pts: dashPts });
        prims.push({ k: 'label', x: x0 + boxW / 2, y: y0 + boxH + 70, text: '被导线短路', size: 11 });
        extraBottom = Math.max(extraBottom, y0 + boxH + 86 - H);
      });
      return { w: W, h: H + Math.max(0, extraBottom) };
    }

    function layoutGraph(prims, model) {
      const edges = model.graphEdges || [];
      const nets = [];
      const idx = new Map();
      edges.forEach(function (e) {
        [e.a, e.b].forEach(function (v) { if (!idx.has(v)) { idx.set(v, nets.length); nets.push(v); } });
      });
      const n = Math.max(3, nets.length);
      const R = Math.max(90, Math.min(210, 46 + n * 16));
      const cx0 = SZ.PAD + R + 40, cy0 = SZ.PAD + R + 20;
      const pos = new Map();
      nets.forEach(function (v, i) {
        const a = -Math.PI / 2 + i * 2 * Math.PI / n;
        pos.set(v, { x: cx0 + R * Math.cos(a), y: cy0 + R * Math.sin(a) });
      });
      nets.forEach(function (v) { const p = pos.get(v); prims.push({ k: 'dot', x: p.x, y: p.y }); });
      edges.forEach(function (e) {
        const p1 = pos.get(e.a), p2 = pos.get(e.b);
        if (!p1 || !p2) return;
        const mx = (p1.x + p2.x) / 2, my = (p1.y + p2.y) / 2;
        prims.push({ k: 'wire', pts: [[p1.x, p1.y], [mx - 20, my], [mx + 20, my], [p2.x, p2.y]] });
        prims.push({ k: 'sym', c: e.c, cx: mx, cy: my, flip: false });
      });
      return { w: cx0 + R + SZ.PAD + 60, h: cy0 + R + SZ.PAD + 40 };
    }

    function layout(model, sol) {
      const prims = [];
      if (!model.ok) return { primitives: prims, w: 460, h: 140, empty: true };
      if (model.kind === 'sp') { const sz = layoutLoop(prims, model, sol); return { primitives: prims, w: sz.w, h: sz.h }; }
      if (model.kind === 'graph') { const sz = layoutGraph(prims, model); return { primitives: prims, w: sz.w, h: sz.h }; }
      return { primitives: prims, w: 460, h: 140, empty: true };
    }

    /* ---------- 5. 绘制 ---------- */
    function line(ctx, x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); }
    function tagText(c) {
      try {
        if (typeof tagOf === 'function') return String(tagOf(c)).trim();
      } catch (e) { }
      return '';
    }
    function valueText(c) {
      const f = function (v, d) { return (typeof fmt === 'function') ? fmt(v, d) : String(v); };
      switch (c.type) {
        case 'battery': return f(c.props.V, 1) + ' V';
        case 'bulb': return 'R=' + f(c.props.R, 0) + ' Ω';
        case 'resistor': return 'R=' + f(c.props.R, 0) + ' Ω';
        case 'rheostat': return f(c.props.R, 0) + ' Ω';
        case 'switch': return c.props.closed ? '' : '断开';
        case 'fuse': return f(c.props.Imax, 1) + ' A';
        case 'conductor': return '导体';
        case 'led': return 'LED';
        case 'motor': return '';
        case 'ammeter': return '';
        case 'voltmeter': return '';
        case 'bell': return '';
        default: return '';
      }
    }

    function drawSym(ctx, p, sol) {
      const c = p.c, cx = p.cx, cy = p.cy, flip = !!p.flip;
      const HW = SZ.ELEM_W / 2;                       // 盒子半宽 = 引线端点
      const bh = BODY_HALF[c.type] != null ? BODY_HALF[c.type] : 20;
      ctx.save();
      ctx.strokeStyle = INK; ctx.fillStyle = 'none'; ctx.lineWidth = 2;
      ctx.lineCap = 'round'; ctx.lineJoin = 'round';

      /* ---- 本体(只画盒子中间那一段) ---- */
      if (c.type === 'battery') {
        // 横放:左短(负)右长(正)
        line(ctx, cx - 7, cy - 14, cx - 7, cy + 14);
        line(ctx, cx + 7, cy - 20, cx + 7, cy + 20);
      } else if (c.type === 'bulb') {
        ctx.beginPath(); ctx.arc(cx, cy, 13, 0, Math.PI * 2); ctx.stroke();
        line(ctx, cx - 9, cy - 9, cx + 9, cy + 9);
        line(ctx, cx + 9, cy - 9, cx - 9, cy + 9);
      } else if (c.type === 'resistor' || c.type === 'conductor') {
        ctx.strokeRect(cx - 22, cy - 9, 44, 18);
      } else if (c.type === 'fuse') {
        ctx.strokeRect(cx - 22, cy - 9, 44, 18);
        line(ctx, cx - 22, cy, cx + 22, cy);
      } else if (c.type === 'rheostat') {
        ctx.strokeRect(cx - 22, cy - 9, 44, 18);
        line(ctx, cx - 12, cy + 17, cx + 12, cy - 17);
        const ax = cx + 12, ay = cy - 17;
        ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(ax - 7, ay + 2); ctx.lineTo(ax - 2, ay + 7); ctx.closePath();
        ctx.fillStyle = INK; ctx.fill();
      } else if (c.type === 'switch') {
        const px = flip ? cx + 13 : cx - 13;          // 转轴
        const tx = flip ? cx - 13 : cx + 13;          // 另一触点
        line(ctx, cx - 13, cy, cx - 7, cy);           // 左触点(短短一段,中间留缺口)
        line(ctx, cx + 7, cy, cx + 13, cy);           // 右触点
        ctx.beginPath(); ctx.moveTo(px, cy);
        if (c.props && c.props.closed) ctx.lineTo(tx, cy);   // 闭合:刀落下接通
        else ctx.lineTo(tx, cy - 16);                        // 断开:刀抬起
        ctx.stroke();
        ctx.beginPath(); ctx.arc(px, cy, 2.6, 0, Math.PI * 2); ctx.fillStyle = INK; ctx.fill();
      } else if (c.type === 'ammeter' || c.type === 'voltmeter' || c.type === 'motor') {
        ctx.beginPath(); ctx.arc(cx, cy, 14, 0, Math.PI * 2); ctx.stroke();
        ctx.fillStyle = INK;
        ctx.font = '700 15px "Times New Roman", serif';
        ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
        ctx.fillText(c.type === 'ammeter' ? 'A' : c.type === 'voltmeter' ? 'V' : 'M', cx, cy + 1);
      } else if (c.type === 'led') {
        const dir = flip ? -1 : 1;
        ctx.beginPath();
        ctx.moveTo(cx - 9 * dir, cy - 12);
        ctx.lineTo(cx - 9 * dir, cy + 12);
        ctx.lineTo(cx + 6 * dir, cy);
        ctx.closePath(); ctx.fillStyle = INK; ctx.fill();
        line(ctx, cx + 6 * dir, cy - 12, cx + 6 * dir, cy + 12);
        line(ctx, cx + 10 * dir, cy - 17, cx + 18 * dir, cy - 23);
        line(ctx, cx + 10 * dir, cy - 9, cx + 18 * dir, cy - 15);
      } else if (c.type === 'bell') {
        ctx.beginPath(); ctx.arc(cx, cy + 4, 13, Math.PI, 0); ctx.stroke();
        line(ctx, cx - 13, cy + 4, cx + 13, cy + 4);
        ctx.beginPath(); ctx.arc(cx, cy + 9, 3.2, 0, Math.PI * 2); ctx.fillStyle = INK; ctx.fill();
      } else {
        ctx.strokeRect(cx - 20, cy - 10, 40, 20);
      }

      /* ---- 引线:从本体边缘一直画到盒子边缘(这样导线不会和元件脱节) ---- */
      ctx.strokeStyle = INK;
      line(ctx, cx - HW, cy, cx - bh, cy);
      line(ctx, cx + bh, cy, cx + HW, cy);

      /* ---- 标签 ---- */
      ctx.fillStyle = ACCENT;
      ctx.font = '600 ' + SZ.TAG + 'px "PingFang SC","Microsoft YaHei",sans-serif';
      ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
      const tg = tagText(c);
      if (tg) ctx.fillText(tg, cx, cy - 28);
      const vt = valueText(c);
      if (vt) {
        ctx.fillStyle = MUTED;
        ctx.font = SZ.TAG + 'px "PingFang SC","Microsoft YaHei",sans-serif';
        ctx.fillText(vt, cx, cy + 36);
      }

      /* ---- 电流方向 + 读数(需要求解结果;没有就不画) ---- */
      if (sol && sol.info && c && typeof c.id !== 'undefined') {
        const d = sol.info.get(c.id);
        if (d && typeof d.I === 'number') {
          const dir = arrowDir(d.I, flip);
          if (dir) drawArrow(ctx, cx + 30, cy, 'h', dir);      // 方向箭头:画在右引线上
          const f2 = function (v, k) { return (typeof fmt === 'function') ? fmt(v, k) : String(v); };
          let rt;
          if (c.type === 'voltmeter') rt = (d.U >= 0 ? '+' : '−') + f2(Math.abs(d.U), 3) + ' V';  // 表读数(带接法正负)
          else if (c.type === 'ammeter') rt = f2(Math.abs(d.I), 3) + ' A';
          else rt = 'I=' + f2(Math.abs(d.I), 3) + ' A';
          ctx.fillStyle = ACCENT;
          ctx.font = '600 ' + SZ.TAG + 'px "PingFang SC","Microsoft YaHei",sans-serif';
          ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
          ctx.fillText(rt, cx, cy + 52);
        }
      }
      ctx.restore();
    }

    function drawBatteryV(ctx, p, sol) {
      const x = p.x, y = p.y;
      /* 横放电源(躺在下母线上):默认左短板(负)右长板(正),flip 时左右对调。
         极性依据:左端接 tree.a 网络 —— tree.a 是 t1(正)网络时翻转。
         +/− 符号跟着"极性"走(长板旁永远是 +),不跟位置走。 */
      const d = p.flip ? -1 : 1;
      const shortX = x - 7 * d, longX = x + 7 * d;
      ctx.save();
      ctx.strokeStyle = INK; ctx.lineWidth = 2.4; ctx.lineCap = 'butt';
      line(ctx, shortX, y - 14, shortX, y + 14);     // 短板 = 负
      line(ctx, longX, y - 20, longX, y + 20);       // 长板 = 正
      ctx.restore();
      ctx.save();
      ctx.fillStyle = ACCENT;
      ctx.font = '700 13px "Times New Roman", serif';
      ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
      ctx.fillText(p.flip ? '−' : '+', x + 52, y - 10);   // 右侧符号
      ctx.fillText(p.flip ? '+' : '−', x - 52, y - 10);   // 左侧符号
      ctx.font = '600 ' + SZ.TAG + 'px "PingFang SC","Microsoft YaHei",sans-serif';
      const tg = tagText(p.c), vt = valueText(p.c);
      if (tg) ctx.fillText(tg, x, y - 30);                 // 型号在上(回路内侧)
      if (vt) { ctx.fillStyle = MUTED; ctx.fillText(vt, x, y + 36); }   // 数值在下(回路外侧)
      /* 读数行:电源输出电流 + 路端电压(与面板同源;开路时 I=0、U=E 正好教学) */
      if (sol) {
        const f2 = function (v, k) { return (typeof fmt === 'function') ? fmt(v, k) : String(v); };
        ctx.fillStyle = ACCENT;
        ctx.font = '600 ' + SZ.TAG + 'px "PingFang SC","Microsoft YaHei",sans-serif';
        ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
        ctx.fillText('I=' + f2(sol.battI, 3) + ' A · U=' + f2(sol.battU, 3) + ' V', x, y + 54);
      }
      ctx.restore();
    }

    function render(ctx, L, w, h, sol) {
      ctx.save();
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, w, h);
      ctx.strokeStyle = INK; ctx.lineWidth = 2; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
      // 实线导线
      L.primitives.forEach(function (p) {
        if (p.k !== 'wire' || p.dashed) return;
        ctx.beginPath();
        p.pts.forEach(function (pt, i) { if (i) ctx.lineTo(pt[0], pt[1]); else ctx.moveTo(pt[0], pt[1]); });
        ctx.stroke();
      });
      // 虚线导线("与主回路是同一节点"的示意)
      L.primitives.forEach(function (p) {
        if (p.k !== 'wire' || !p.dashed) return;
        ctx.save();
        ctx.setLineDash([5, 5]);
        ctx.strokeStyle = MUTED;
        ctx.beginPath();
        p.pts.forEach(function (pt, i) { if (i) ctx.lineTo(pt[0], pt[1]); else ctx.moveTo(pt[0], pt[1]); });
        ctx.stroke();
        ctx.restore();
      });
      L.primitives.forEach(function (p) {
        if (p.k === 'dot') { ctx.beginPath(); ctx.arc(p.x, p.y, 3.2, 0, Math.PI * 2); ctx.fillStyle = INK; ctx.fill(); }
      });
      // 电流方向箭头(母线上;dir=0 表示无电流不画)
      L.primitives.forEach(function (p) {
        if (p.k !== 'arrow' || !p.dir) return;
        drawArrow(ctx, p.x, p.y, p.axis, p.dir);
      });
      L.primitives.forEach(function (p) { if (p.k === 'bat') drawBatteryV(ctx, p, sol); });
      L.primitives.forEach(function (p) { if (p.k === 'sym') drawSym(ctx, p, sol); });
      // 纯文字标注
      L.primitives.forEach(function (p) {
        if (p.k !== 'label') return;
        ctx.save();
        ctx.fillStyle = MUTED;
        ctx.font = (p.size || 11) + 'px "PingFang SC","Microsoft YaHei",sans-serif';
        ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
        ctx.fillText(p.text, p.x, p.y);
        ctx.restore();
      });
      if (L.empty) {
        ctx.fillStyle = MUTED;
        ctx.font = '14px "PingFang SC","Microsoft YaHei",sans-serif';
        ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
      }
      ctx.restore();
    }

    /* ---------- 6. 汇总 ---------- */
    function summarize(model, L) {
      const syms = L.primitives.filter(function (p) { return p.k === 'sym'; });
      const groups = []; let depth = 0;
      (function walk(n, d) {
        if (!n || n.leaf) return;
        if (n.kind === 'par') groups.push(n.kids.length);
        if (n.kind === 'ser') depth = Math.max(depth, d + 1);
        (n.kids || []).forEach(function (k) { walk(k.child !== undefined ? k.child : k, d + 1); });
      })(model.tree, 0);
      return {
        ok: !!model.ok, reason: model.reason || '', kind: model.kind,
        symbols: syms.map(function (p) { return p.c.type; }),
        tags: syms.map(function (p) { return tagText(p.c); }),
        wireCount: L.primitives.filter(function (p) { return p.k === 'wire'; }).length,
        arrows: L.primitives.filter(function (p) { return p.k === 'arrow' && p.dir; }).length,
        parallelGroups: groups, seriesDepth: depth,
        unconnected: (model.unconnected || []).length,
        shorted: (model.shorted || []).length,
        w: L.w, h: L.h
      };
    }

    return {
      build: build, layout: layout, render: render, summarize: summarize,
      drawSym: drawSym, drawBatteryV: drawBatteryV, SZ: SZ,
      buildNetlist: buildNetlist, spReduce: spReduce, measure: measure,
      arrowDir: arrowDir
    };
  })();

  /* ---------- 简化电路图:浮层 ---------- */
  const schemOverlay = document.getElementById('schemOverlay');
  const schemCanvasEl = document.getElementById('schemCanvas');
  const schemNoteEl = document.getElementById('schemNote');
  const schemSubEl = document.getElementById('schemSub');
  let schemState = null;

  function schemRender() {
    const model = SchematicLab.build();
    /* 求解一次,把电流方向与读数标到图上(拿不到结果就只画结构,不抛错) */
    let sol = null;
    try { sol = (typeof ensureSolved === 'function') ? ensureSolved() : null; } catch (e) { sol = null; }
    const L = SchematicLab.layout(model, sol);
    const summary = SchematicLab.summarize(model, L);
    schemState = { model: model, L: L, summary: summary, sol: sol };
    if (schemCanvasEl) {
      const dpr = Math.min(2, Math.max(1, window.devicePixelRatio || 1));
      const w = Math.max(320, Math.round(L.w));
      const h = Math.max(90, Math.round(L.h));
      schemCanvasEl.width = Math.round(w * dpr);
      schemCanvasEl.height = Math.round(h * dpr);
      schemCanvasEl.style.width = w + 'px';
      schemCanvasEl.style.height = h + 'px';
      let ctx = null;
      try { ctx = schemCanvasEl.getContext && schemCanvasEl.getContext('2d'); } catch (e) { ctx = null; }
      if (ctx) {
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        SchematicLab.render(ctx, L, w, h, sol);
      }
    }
    if (schemSubEl) schemSubEl.textContent = model.ok ? '由实物连线自动生成' : '无法生成';
    if (schemNoteEl) {
      let t;
      if (!model.ok) t = model.reason;
      else if (model.kind === 'graph') t = model.reason + '(共 ' + summary.symbols.length + ' 个元件)';
      else {
        t = summary.parallelGroups.length
          ? '串并联结构:并联 ' + summary.parallelGroups.length + ' 组,共 ' + summary.symbols.length + ' 个元件'
          : '串联回路:共 ' + summary.symbols.length + ' 个元件';
        if (summary.shorted) t += ' · ' + summary.shorted + ' 个元件被导线短路';
        if (summary.unconnected) t += ' · ' + summary.unconnected + ' 个元件未接入电路';
      }
      schemNoteEl.textContent = t;
    }
    return schemState;
  }

  function openSchematic() {
    if (!schemOverlay) return;
    schemOverlay.hidden = false;
    try { setBodyFlag('lib-open', true); } catch (e) { }
    schemRender();
    Sound.click(0.5);
  }
  function closeSchematic() {
    if (!schemOverlay) return;
    schemOverlay.hidden = true;
    try { setBodyFlag('lib-open', false); } catch (e) { }
  }
  function saveSchematic() {
    if (!schemCanvasEl || !schemState || !schemState.L) return;
    try {
      const L = schemState.L;
      const w = Math.max(320, Math.round(L.w)), h = Math.max(90, Math.round(L.h));
      /* 屏幕画布只有 1×/2×,直接导出会糊:
         导出时离屏按倍数重渲一遍 —— 线条、文字、箭头全部跟着放大,永远清晰。
         倍数按"长边约1800px"自适应(打印/插文档都够用),限制在4~8×。 */
      const S = Math.min(8, Math.max(4, Math.ceil(1800 / Math.max(w, h))));
      const cv = document.createElement('canvas');
      cv.width = Math.round(w * S);
      cv.height = Math.round(h * S);
      let ctx = null;
      try { ctx = cv.getContext && cv.getContext('2d'); } catch (e) { ctx = null; }
      let url = null;
      if (ctx) {
        ctx.setTransform(S, 0, 0, S, 0, 0);
        SchematicLab.render(ctx, L, w, h, schemState.sol);
        url = cv.toDataURL('image/png');
      }
      if (!url && schemCanvasEl.toDataURL) url = schemCanvasEl.toDataURL('image/png');   // 兜底:原样导出
      if (!url) throw new Error('无法生成图像');
      const a = document.createElement('a');
      a.href = url;
      a.download = '电路图.png';
      if (a.style) a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      showToast('电路图已保存为 PNG(' + cv.width + '×' + cv.height + ')');
    } catch (e) {
      showToast('保存失败:' + (e && e.message ? e.message : '未知错误'));
    }
  }
  (function bindSchematic() {
    const btn = document.getElementById('btnSchem');
    if (btn) btn.addEventListener('click', openSchematic);
    const mBtn = document.getElementById('mBtnSchem');
    if (mBtn) mBtn.addEventListener('click', openSchematic);
    const close = document.getElementById('schemClose');
    if (close) close.addEventListener('click', closeSchematic);
    const save = document.getElementById('schemSave');
    if (save) save.addEventListener('click', saveSchematic);
    const re = document.getElementById('schemRefresh');
    if (re) re.addEventListener('click', function () { schemRender(); Sound.click(0.4); });
    if (schemOverlay) {
      schemOverlay.addEventListener('click', function (ev) {
        if (ev.target === schemOverlay) closeSchematic();
      });
    }
    // Esc 关闭:只在浮层打开时生效(并做能力判断,方便在无 DOM 的环境里单测)
    if (document && typeof document.addEventListener === 'function') {
      document.addEventListener('keydown', function (ev) {
        if (ev.key === 'Escape' && schemOverlay && !schemOverlay.hidden) {
          closeSchematic();
          if (ev.stopPropagation) ev.stopPropagation();
        }
      }, true);
    }
  })();


  /* =======================================================================
     关卡系统(v2.0 M1):题库 + 判分引擎 + 关卡界面
     -----------------------------------------------------------------------
     设计原则(见 circuit-lab-大版本计划.md):
     · 关卡 = 自由创造 + 约束 + 判分 —— 共用画布/求解器/元件库,不写第二套引擎
     · 题面/目标/判分规则全在 EXAM_DB(JSON 结构,可直接改文字)
     · 判分只复用 solveNow / analyzeConnection,不新增物理逻辑
     · 手动判分:学生点「检查」才判,不当场揭晓
     ======================================================================= */
  const EXAM_DB = {
    chapters: [
      {
        id: 'ch00', name: '上手引导(可跳过)',
        desc: '先学会三件事:怎么接线、怎么挪元件、怎么读数。6 关走完再进第一章会顺很多(已经会了就直接跳过)。',
        skippable: true,
        levels: [
          {
            id: 'ch00-01', no: 1, title: '连成回路:把灯点亮', type: '引导',
            task: '从右侧器材篮把<b>电池</b>和<b>灯泡</b>各放一个到画布。然后<b>点一下电池的接线柱</b>(它会亮起、等待接另一端),<b>再点灯泡的接线柱</b>就连上一根线;换另一对再连一根,让回路闭合、灯泡亮起来。',
            gear: [{ type: 'battery', n: 1 }, { type: 'bulb', n: 1 }],
            goals: [
              { id: 'lit', type: 'lit', text: '灯泡亮起来' }
            ],
            tips: ['先点一个接线柱、再点另一个接线柱就连上一根线(点得快也一样)',
              '电池和灯泡之间要接<b>两根</b>线,首尾都连上才算闭合'],
            explain: 'v2.0 的接线是「点一下就连」:点第一个接线柱让它亮起、等待接另一端,再点另一个接线柱就接好。<b>两根线</b>把电池和灯泡接成闭合回路,电流流过灯泡,灯才亮。'
          },
          {
            id: 'ch00-02', no: 2, title: '串进一个开关:控制通断', type: '引导',
            task: '在回路里<b>串进一个开关</b>:把回路断开一处,把开关的两个接线柱分别接到断点两侧;然后<b>点一下开关</b>闭合它,让灯亮。',
            gear: [{ type: 'battery', n: 1 }, { type: 'switch', n: 1 }, { type: 'bulb', n: 1 }],
            goals: [
              { id: 'lit', type: 'lit', text: '灯泡亮起来' },
              { id: 'closed', type: 'closed', text: '电路闭合(有电流)' },
              { id: 'gear', type: 'gearAll', text: '器材都用上了(开关在回路里)' }
            ],
            tips: ['串接开关 = 把回路断开一段,开关两头分别接到断点两侧', '点一下开关 = 在「断开 / 闭合」之间切换;闭合时才有电流'],
            explain: '开关串在回路里控制通断:闭合才有电流、灯才亮。点它就能在「断开」「闭合」之间切换。'
          },
          {
            id: 'ch00-03', no: 3, title: '拖动元件:挪个位置', type: '引导',
            task: '这盏灯已经亮了。按住<b>灯泡本体拖动</b>,把它挪到画面里更空的位置——导线会跟着元件走,<b>灯要一直亮着</b>。',
            startPreset: 'lamp',
            gear: [{ type: 'battery', n: 1 }, { type: 'bulb', n: 1 }],
            goals: [
              { id: 'lit', type: 'lit', text: '灯泡仍然亮着' },
              { id: 'closed', type: 'closed', text: '电路仍然闭合' },
              { id: 'moved', type: 'moved', tag: 'L1', dist: 80, text: '把灯泡拖动了位置' }
            ],
            tips: ['按住元件<b>本体</b>拖动 = 移动元件;按在接线柱上拖动也一样,只要动起来就是拖动', '拖动过程不接线;松手后导线仍连在元件上'],
            explain: '拖动元件只是挪位置,电气连接不会断:导线跟随元件一起移动,所以灯仍然亮。这就是调整布局的方法。'
          },
          {
            id: 'ch00-04', no: 4, title: '接电流表:读出电流', type: '引导',
            task: '在回路里<b>串进一个电流表</b>(电流表要串联),闭合后到右侧「读数 · 实验数据」表里看看电流表的读数,让灯亮、电流表有读数。',
            gear: [{ type: 'battery', n: 1 }, { type: 'bulb', n: 1 }, { type: 'ammeter', n: 1 }],
            goals: [
              { id: 'lit', type: 'lit', text: '灯泡亮起来' },
              { id: 'read', type: 'readIn', a: 'A1', prop: 'I', min: 0.05, max: 1, text: '电流表读出电流(0.05 ~ 1 A)' }
            ],
            tips: ['电流表要<b>串联</b>在回路里,电流从「+」接线柱流进', '读数在右侧「读数 · 实验数据」表里看 I 这一列'],
            explain: '电流表必须<b>串联</b>在回路中才有读数。灯亮 + 电流表显示电流,说明回路闭合、电流表接法正确。读数是分析电路的第一步。'
          },
          {
            id: 'ch00-05', no: 5, title: '断开与闭合:看读数变化', type: '引导',
            task: '用<b>电池、开关、小灯泡</b>接成一个回路,把开关<b>串在回路里</b>。先让开关断开,看看灯灭、没有电流;再点一下把它<b>闭合</b>,让灯亮起来。然后选出正确结论。',
            gear: [{ type: 'battery', n: 1 }, { type: 'switch', n: 1 }, { type: 'bulb', n: 1 }],
            goals: [
              { id: 'lit', type: 'lit', text: '闭合后灯泡亮起来' },
              { id: 'closed', type: 'closed', text: '电路闭合' },
              { id: 'gear', type: 'gearAll', text: '器材都用上了(开关要串在回路里)' },
              {
                id: 'q', type: 'choice', text: '选结论:开关断开时,回路里的电流是多少?',
                options: ['0 A(断路,没有电流)', '一半的电流', '最大的电流'],
                answer: 0
              }
            ],
            tips: ['开关<b>串在回路里</b>才能控制通断;断开 = 断路,电流为 0、灯不亮', '开关闭合 = 通路,电流才有'],
            explain: '开关断开时电路断路,<b>没有电流(I=0)</b>,灯不亮;闭合后形成通路,才有电流。这是「通断」最基本的观察。'
          },
          {
            id: 'ch00-06', no: 6, title: '小结:接对一盏灯的完整电路', type: '引导',
            task: '不给你预置了——自己用「电池 + 开关 + 小灯泡 + 电流表」接一个完整回路:开关串在回路里、电流表串联,闭合后灯亮、电流表有读数。',
            gear: [{ type: 'battery', n: 1 }, { type: 'switch', n: 1 }, { type: 'bulb', n: 1 }, { type: 'ammeter', n: 1 }],
            goals: [
              { id: 'lit', type: 'lit', text: '灯泡亮起来' },
              { id: 'closed', type: 'closed', text: '电路闭合' },
              { id: 'gear', type: 'gearAll', text: '器材都用上了' },
              { id: 'read', type: 'readIn', a: 'A1', prop: 'I', min: 0.05, max: 1, text: '电流表读出电流(0.05 ~ 1 A)' }
            ],
            tips: ['顺序:电池 → 开关 → 灯泡 → 电流表 → 回电池', '电流表、开关都是<b>串</b>在回路里,不要并到元件两端'],
            explain: '这就是一盏灯的完整电路:电源、开关、用电器、电流表串联成闭合回路。有了这个底子,第一章的两灯串联/并联就好接了。'
          }
        ]
      },
      {
        id: 'ch01', name: '串并联入门',
        desc: '从一盏灯到两盏灯:接法不同,电流和电压的规律完全不同。',
        levels: [
          {
            id: 'ch01-01', no: 1, title: '认识电路:一盏灯点亮', type: '接线',
            task: '用电池、开关和一盏小灯泡,连成闭合回路,让灯亮起来。',
            gear: [{ type: 'battery', n: 1 }, { type: 'switch', n: 1 }, { type: 'bulb', n: 1 }],
            goals: [
              { id: 'lit', type: 'lit', text: '至少一盏灯亮起' },
              { id: 'closed', type: 'closed', text: '电路闭合(有电流流过)' },
              { id: 'gear', type: 'gearAll', text: '器材都用上了(开关要在回路里)' }
            ],
            tips: ['点一下接线柱让它亮起,再点另一端就连上(点得快也行)',
              '点一下开关可以切换"断开 / 闭合",闭合后电路才有电流'],
            explain: '电流从电源正极出发,经开关、灯泡回到负极,形成<b>闭合回路</b>,灯泡才会亮。断路(开关断开、导线没连上)时没有电流。<b>器材是给定的</b>:本关要用开关控制通断,用别的元件替掉开关不算完成。'
          },
          {
            id: 'ch01-02', no: 2, title: '两灯串联:电流处处相等', type: '接线',
            task: '把两盏小灯泡接成<b>串联</b>,两灯都要亮起来。',
            gear: [{ type: 'battery', n: 1 }, { type: 'bulb', n: 2 }],
            goals: [
              { id: 'series', type: 'series', text: '两灯为串联' },
              { id: 'all', type: 'allLit', text: '两灯都亮' },
              { id: 'ieq', type: 'eqReading', prop: 'I', a: 'L1', b: 'L2', text: '两灯电流相等 I₁=I₂' },
              { id: 'gear', type: 'gearAll', text: '器材都用上了' }
            ],
            tips: ['串联:首尾相连,电流只有一条路可走', '两灯电流相等是串联的判据之一'],
            explain: '串联电路中<b>电流处处相等</b>:I = I₁ = I₂;总电压等于各部分电压之和 U = U₁ + U₂。'
          },
          {
            id: 'ch01-03', no: 3, title: '两灯并联:各支路电压相等', type: '接线',
            task: '把两盏小灯泡接成<b>并联</b>,两灯都要亮起来。',
            gear: [{ type: 'battery', n: 1 }, { type: 'bulb', n: 2 }, { type: 'junction', free: true }],
            goals: [
              { id: 'parallel', type: 'parallel', text: '两灯为并联' },
              { id: 'all', type: 'allLit', text: '两灯都亮' },
              { id: 'ueq', type: 'eqReading', prop: 'U', a: 'L1', b: 'L2', text: '两灯电压相等 U₁=U₂' },
              { id: 'gear', type: 'gearAll', text: '器材都用上了' }
            ],
            tips: ['并联:首首相连、尾尾相连,电流有两条路',
              '导线要分叉时,用「接线点」(三根线以上交汇,不限量)'],
            explain: '并联电路<b>各支路电压相等</b>:U = U₁ = U₂;干路电流等于各支路电流之和 I = I₁ + I₂。'
          },
          {
            id: 'ch01-04', no: 4, title: '谁更亮:比较实际功率', type: '接线',
            task: '两灯并联,把其中一盏的电阻改小,让两灯亮度明显不同,然后<b>选出正确结论</b>。',
            gear: [{ type: 'battery', n: 1 }, { type: 'bulb', n: 2 }],
            goals: [
              { id: 'parallel', type: 'parallel', text: '两灯为并联' },
              { id: 'all', type: 'allLit', text: '两灯都亮' },
              { id: 'power', type: 'neReading', prop: 'P', a: 'L1', b: 'L2', text: '两灯亮度不同(功率不同)' },
              {
                id: 'why', type: 'choice', text: '选结论:为什么改小电阻的那盏更亮?',
                options: [
                  '它把另一盏灯的电流"抢"过来了,总电流变大了',
                  '电压相同时,P = U²/R:电阻越小、功率越大',
                  '它分到的电压比另一盏多,所以更亮'
                ],
                answer: 1
              },
              { id: 'gear', type: 'gearAll', text: '器材都用上了' }
            ],
            tips: ['选中灯泡可以改"灯丝电阻"', '亮度看实际功率 P,不是看电阻大小'],
            explain: '并联时电压相同,电阻小的支路电流大,实际功率 <b>P = U²/R</b> 越大,灯越亮——所以改小电阻的那盏更亮。'
          },
          {
            id: 'ch01-05', no: 5, title: '用电器短路:为什么不亮', type: '判断',
            task: '已接好<b>两灯串联</b>,开关并在 L1 两端(现在断开):<b>闭合开关</b>,观察两灯亮灭,然后<b>选出正确结论</b>。',
            startPreset: 'seriesShort',
            gear: [{ type: 'battery', n: 1 }, { type: 'switch', n: 1 }, { type: 'bulb', n: 2 }, { type: 'junction', free: true }],
            goals: [
              { id: 'shorted', type: 'hasShorted', text: 'L1 被短路(两端近乎无电压)' },
              { id: 'oneoff', type: 'oneLit', text: '被短路的灯不亮,另一盏仍亮' },
              {
                id: 'why', type: 'choice', text: '选结论:被短路的灯为什么不亮?',
                options: [
                  '电流被另一盏灯用完了,轮不到它',
                  '闭合开关把它烧坏了(灯丝断了)',
                  '它两端电压为 0,几乎没有电流通过'
                ],
                answer: 2
              },
              { id: 'gear', type: 'gearAll', text: '器材都用上了' }
            ],
            tips: ['开关断开时两灯串联:都亮,但比较暗',
              '闭合开关 = 电流改走开关这条"捷径",L1 被短路'],
            explain: '串联电路中,用导线(或闭合的开关)跨接在某个用电器两端 = <b>局部短路</b>:该用电器<b>电压为 0、电流为 0</b>,不亮;另一盏灯分得全部电压,反而更亮。<b>注意</b>:若两灯是<b>并联</b>,跨接其中一盏的两端会直接<b>短路电源</b>(两灯全灭、电流暴增)——这是另一种危险情况,两种别混!'
          },
          {
            id: 'ch01-06', no: 6, title: '混联判断(挑战)', type: '判断',
            task: '接一个"两灯并联后再与第三盏灯串联"的电路,让三盏灯都亮。',
            gear: [{ type: 'battery', n: 1 }, { type: 'bulb', n: 3 }, { type: 'junction', free: true }],
            goals: [
              { id: 'mixed', type: 'mixedConn', text: '电路为混联(非纯串/并联)' },
              { id: 'all3', type: 'allLit', text: '三盏灯都亮' },
              { id: 'gear', type: 'gearAll', text: '器材都用上了' }
            ],
            tips: ['两灯并联后,整体再串进主回路', '接线点可以让导线一分为二'],
            explain: '混联:先算并联部分(电压相等、电流相加),再与串联部分相加。3 灯全亮说明回路完整。'
          }
        ]
      }
    ]
  };

  /* ---------- 判分引擎:全部复用现有求解与判定 ---------- */
  function examFind(tag) {
    return state.components.find(function (c) {
      try { return String(tagOf(c)).trim() === String(tag).trim(); } catch (e) { return false; }
    }) || null;
  }
  function examGoal(g, s, level) {
    const comps = state.components;
    switch (g.type) {
      case 'gearAll': {
        // 器材都用上了:本关给定的每件器材都已摆出、接进回路且有电流
        //(被短路的灯泡电流为 0 属正常:它两端等电位,正是实验要观察的现象)
        const gear = (level && level.gear) || [];
        return gear.every(function (gi) {
          if (gi.free) return true;
          const placed = comps.filter(function (c) { return c.type === gi.type; });
          if (placed.length < gi.n) return false;
          return placed.every(function (c) {
            const wiredT = {};
            state.wires.forEach(function (w) {
              if (w.a.cid === c.id) wiredT[w.a.ti] = 1;
              if (w.b.cid === c.id) wiredT[w.b.ti] = 1;
            });
            const nt = (DEFS[c.type] && DEFS[c.type].terminals) ? DEFS[c.type].terminals.length : 2;
            for (let i = 0; i < nt; i++) if (!wiredT[i]) return false;
            const d = s.info.get(c.id);
            if (!d) return false;
            return Math.abs(d.I) > 1e-4 || (c.type === 'bulb' && Math.abs(d.U) < 0.05);
          });
        });
      }
      case 'lit': {
        return comps.some(function (c) {
          if (c.type !== 'bulb' || c.props.burned) return false;
          const d = s.info.get(c.id);
          return d && d.P > 0.02;
        });
      }
      case 'allLit': {
        const bulbs = comps.filter(function (c) { return c.type === 'bulb' && !c.props.burned; });
        return bulbs.length >= 2 && bulbs.every(function (c) {
          const d = s.info.get(c.id);
          return d && d.P > 0.02;
        });
      }
      case 'oneLit': {
        const lit = comps.filter(function (c) {
          if (c.type !== 'bulb' || c.props.burned) return false;
          const d = s.info.get(c.id);
          return d && d.P > 0.02;
        });
        const dead = comps.filter(function (c) {
          if (c.type !== 'bulb' || c.props.burned) return false;
          const d = s.info.get(c.id);
          return d && d.P <= 0.02;
        });
        return lit.length >= 1 && dead.length >= 1;
      }
      case 'closed': return s.status === 'on' || s.status === 'heavy' || s.status === 'charge';
      case 'series': return analyzeConnection(s) === 'series';
      case 'parallel': return analyzeConnection(s) === 'parallel';
      case 'mixedConn': return analyzeConnection(s) === 'mixed';
      case 'hasShorted': return (s.sol && s.sol.shortCircuit) ? false : comps.some(function (c) {
        if (c.type !== 'bulb') return false;
        const d = s.info.get(c.id);
        // 被短路 = 两端近乎等电位(跨接的开关/导线有毫伏级压降,阈值取 50mV)
        return d && Math.abs(d.U) < 0.05 && s.status !== 'short';
      });
      case 'eqReading':
      case 'neReading': {
        const ca = examFind(g.a), cb = examFind(g.b);
        if (!ca || !cb) return false;
        const da = s.info.get(ca.id), db = s.info.get(cb.id);
        if (!da || !db) return false;
        const va = (g.prop === 'I' ? da.I : g.prop === 'U' ? da.U : da.P);
        const vb = (g.prop === 'I' ? db.I : g.prop === 'U' ? db.U : db.P);
        if (typeof va !== 'number' || typeof vb !== 'number') return false;
        const diff = Math.abs(Math.abs(va) - Math.abs(vb));
        const eq = Math.abs(va) > 1e-4 && diff <= Math.max(1e-4, 0.03 * Math.abs(va));
        return g.type === 'eqReading' ? eq : !eq;
      }
      case 'readIn': {
        // 读数型:某元件的读数(I/U/P)落在给定区间内 —— 章 0 引导与 M3 计算题复用
        const c = examFind(g.a);
        if (!c) return false;
        const d = s.info.get(c.id);
        if (!d) return false;
        const v = Math.abs(g.prop === 'U' ? d.U : g.prop === 'P' ? d.P : d.I);
        const lo = (typeof g.min === 'number') ? g.min : 0;
        const hi = (typeof g.max === 'number') ? g.max : Infinity;
        return v >= lo && v <= hi;
      }
      case 'moved': {
        // 拖动教学:某元件相对"进入关卡时的位置"移动了足够远(章 0 第 3 关)
        const c = examFind(g.tag);
        if (!c) return false;
        const o = (state.level && state.level.origPos) ? state.level.origPos[c.id] : null;
        if (!o) return false;
        return Math.hypot(c.x - o.x, c.y - o.y) >= (typeof g.dist === 'number' ? g.dist : 80);
      }
      case 'choice': {
        // 「选结论」:做完实验选出正确说法(没选 = 未达成,判分前不揭晓)
        const ans = state.level && state.level.answers ? state.level.answers[g.id] : undefined;
        return typeof ans === 'number' && ans === g.answer;
      }
      default: return true;
    }
  }
  function examJudge(level) {
    const s = ensureSolved();
    const results = level.goals.map(function (g) {
      let ok = false;
      try { ok = !!examGoal(g, s, level); } catch (e) { ok = false; }
      return { id: g.id, text: g.text, ok: ok };
    });
    const pass = results.every(function (r) { return r.ok; });
    return { pass: pass, goals: results, s: s };
  }
  /* 星级:首次检查通过=3★,两次=2★,三次及以上=1★(提示不扣分,只记次数) */
  function examStars(attempts) {
    return attempts <= 1 ? 3 : attempts <= 2 ? 2 : 1;
  }
  /* 进度:localStorage,{ 'ch01-01': 3, ... }(存最高星;0/缺省=未通过) */
  function examProgress() {
    try {
      const raw = window.localStorage && window.localStorage.getItem('circuitLab.exam');
      return raw ? JSON.parse(raw) : {};
    } catch (e) { return {}; }
  }
  function examSaveResult(levelId, stars) {
    try {
      const p = examProgress();
      if (!(p[levelId] >= stars)) {
        p[levelId] = stars;
        window.localStorage.setItem('circuitLab.exam', JSON.stringify(p));
      }
    } catch (e) { }
  }
  /* 章是否完成:本章所有关都通过;可跳过的引导章,跳过也算完成 */
  function examChapterDone(ch) {
    const p = examProgress();
    if (ch && ch.skippable && p[ch.id + ':skip']) return true;
    return (ch.levels || []).every(function (lv) { return (p[lv.id] || 0) > 0; });
  }
  function examUnlocked(ch, idx) {
    const p = examProgress();
    const i = EXAM_DB.chapters.indexOf(ch);
    if (idx === 0) {
      // 章的第一关:第一章恒可进;其余章要求前一章完成(未完成不解锁下一章)
      if (i <= 0) return true;
      return examChapterDone(EXAM_DB.chapters[i - 1]);
    }
    return (p[ch.levels[idx - 1].id] || 0) > 0;
  }
  function examLevelById(id) {
    for (const ch of EXAM_DB.chapters) {
      for (const lv of ch.levels) if (lv.id === id) return { ch: ch, level: lv };
    }
    return null;
  }

  /* ---------- 关卡界面 ---------- */
  function enterHub() {
    const el = document.getElementById('hubOverlay');
    if (!el) return;
    try {
      const p = examProgress();
      const total = EXAM_DB.chapters.reduce(function (n, ch) { return n + ch.levels.length; }, 0);
      const levelIds = {};
      EXAM_DB.chapters.forEach(function (ch) { ch.levels.forEach(function (lv) { levelIds[lv.id] = 1; }); });
      const done = Object.keys(p).filter(function (k) { return levelIds[k] && p[k] > 0; }).length;
      const hd = document.getElementById('hubDone'); if (hd) hd.textContent = String(done);
      const ht = document.getElementById('hubTotal'); if (ht) ht.textContent = String(total);
    } catch (e) { }
    el.hidden = false;
  }
  function closeHub() {
    const el = document.getElementById('hubOverlay');
    if (el) el.hidden = true;
  }
  function openPick() {
    closeHub();
    const el = document.getElementById('pickOverlay');
    const body = document.getElementById('pickBody');
    if (!el || !body) return;
    const p = examProgress();
    let html = '';
    EXAM_DB.chapters.forEach(function (ch) {
      html += '<div style="display:flex;align-items:center;gap:8px;margin:10px 0 4px">' +
        '<h3 style="margin:0;color:#25558f">' + ch.name + '</h3>' +
        (ch.skippable ? '<button class="pick-skip" data-skip-ch="' + ch.id + '" title="跳过本章,直接进入后面的章节">跳过引导 →</button>' : '') +
        '</div>' +
        '<div style="font-size:12px;color:#7b8db0;margin-bottom:8px">' + ch.desc + '</div>';
      ch.levels.forEach(function (lv, i) {
        const stars = p[lv.id] || 0;
        const un = examUnlocked(ch, i);
        html += '<div class="pick-item' + (un ? '' : ' locked') + '" data-level="' + lv.id + '">' +
          '<div class="pi-no">' + (lv.no < 10 ? '0' + lv.no : lv.no) + '</div>' +
          '<div class="pi-name"><b>' + lv.title + '</b><br><span style="font-size:11.5px;color:#7b8db0">' + lv.type + ' · ' + lv.goals.length + ' 个目标</span></div>' +
          '<div class="pi-star">' + (un ? (stars ? '★'.repeat(stars) + '☆'.repeat(3 - stars) : '☆☆☆') : '<span style="letter-spacing:0;color:#7b8db0">未解锁</span>') + '</div>' +
          (un ? '<button data-level="' + lv.id + '">▶</button>' : '') +
          '</div>';
      });
    });
    body.innerHTML = html;
    el.hidden = false;
  }
  function closePick() {
    const el = document.getElementById('pickOverlay');
    if (el) el.hidden = true;
  }
  function enterLevel(id) {
    const found = examLevelById(id);
    if (!found) return;
    closeHub(); closePick();
    const lv = found.level;
    state.level = { id: id, attempts: 0, hints: 0, hintShown: 0, passed: false, answers: {}, origPos: {} };
    // 关卡从空画布开始:学生自己接线;带 startPreset 的关卡给出预置电路(M3 的故障题/伏安法题也用它)
    state.components = []; state.wires = []; state.notes = [];
    state.selected = null; state.selectedIds = []; state.drag = null; state.wireMode = null;
    state.idSeq = 0; state.dirty = true; state.solved = null;
    if (lv.startPreset && PRESETS[lv.startPreset]) {
      withoutHistory(function () { loadPreset(lv.startPreset); });   // 预置不算"学生操作",不进撤销
    }
    // 记录进入关卡时的元件位置:「拖动」类判分拿它做参照(预置电路已摆好)
    state.components.forEach(function (c) { state.level.origPos[c.id] = { x: c.x, y: c.y }; });
    setElClass(document.body, 'level-mode', true);
    buildPalette();                       // 元件栏变成"器材篮子":只显示本关给定器材
    const t = document.getElementById('lbTitle');
    if (t) t.textContent = '第 ' + lv.no + ' 关 · ' + lv.title;
    const gearTxt = (lv.gear || []).map(function (gi) {
      const item = PALETTE.find(x => x.type === gi.type);
      return (item ? item.name : gi.type) + (gi.free ? '(不限)' : (gi.n > 1 ? ' ×' + gi.n : ''));
    }).join(' · ');
    const tk = document.getElementById('lbTask');
    if (tk) tk.innerHTML = lv.task + ' <span style="color:#7b8db0">器材:' + gearTxt + ' · 接线点不限量</span>';
    renderLevelGoals([]);
    renderLevelChoices();
    renderInspector();
    ensureSolved();
    fitView();
    showToast('第 ' + lv.no + ' 关:' + lv.title);
  }
  function exitLevel() {
    setElClass(document.body, 'level-mode', false);
    state.level = null;
    buildPalette();                       // 回自由创造:元件栏恢复全部 13 种
    openPick();
  }
  function renderLevelGoals(results) {
    const el = document.getElementById('lbGoals');
    if (!el) return;
    const lv = state.level ? examLevelById(state.level.id) : null;
    if (!lv) { el.innerHTML = ''; return; }
    el.innerHTML = lv.level.goals.map(function (g, i) {
      const r = results && results[i];
      const cls = r === undefined ? '' : (r.ok ? ' done' : ' fail');
      return '<span class="goal-chip' + cls + '">' + (r === undefined ? '○' : (r.ok ? '✓' : '✗')) + ' ' + g.text + '</span>';
    }).join('');
  }
  function renderLevelChoices() {
    const el = document.getElementById('lbChoices');
    if (!el) return;
    const lv = state.level ? examLevelById(state.level.id) : null;
    const cs = lv ? (lv.level.goals || []).filter(function (g) { return g.type === 'choice'; }) : [];
    if (!cs.length) { el.innerHTML = ''; return; }
    const ans = (state.level && state.level.answers) || {};
    el.innerHTML = cs.map(function (g) {
      return '<div style="margin:7px 0 2px"><div style="font-size:12px;color:#7b8db0;margin-bottom:4px">' + g.text + '</div>' +
        (g.options || []).map(function (o, i) {
          const sel = ans[g.id] === i;
          return '<button class="choice-opt' + (sel ? ' sel' : '') + '" data-choice="' + g.id + '" data-idx="' + i + '">' +
            String.fromCharCode(65 + i) + '. ' + o + '</button>';
        }).join('') + '</div>';
    }).join('');
  }
  function judgeLevel() {
    if (!state.level) return;
    const lv = examLevelById(state.level.id);
    if (!lv) return;
    state.level.attempts++;
    const r = examJudge(lv.level);
    renderLevelGoals(r.goals);
    const res = document.getElementById('resultOverlay');
    if (!res) return;
    const ok = r.pass;
    const rt = document.getElementById('resTitle');
    if (rt) rt.textContent = ok ? '✔ 通过' : '✗ 还差一点';
    const rs = document.getElementById('resSub');
    if (rs) rs.textContent = '第 ' + lv.level.no + ' 关 · ' + lv.level.title;
    const stars = ok ? examStars(state.level.attempts) : 0;
    if (ok && !state.level.passed) {
      state.level.passed = true;
      examSaveResult(lv.level.id, stars);
    }
    const st = document.getElementById('resStars');
    if (st) st.textContent = ok ? '★'.repeat(stars) + '☆'.repeat(3 - stars) + '  (' + state.level.attempts + ' 次检查)' : '';
    const gl = document.getElementById('resGoals');
    if (gl) {
      gl.innerHTML = r.goals.map(function (g) {
        return '<div class="goal-chip' + (g.ok ? ' done' : ' fail') + '" style="display:flex;font-size:13px;padding:8px 13px;border-radius:8px">' +
          (g.ok ? '✓ 达成' : '✗ 未达成') + ' · ' + g.text + '</div>';
      }).join('');
    }
    const ex = document.getElementById('resExplain');
    if (ex) ex.innerHTML = '<b>解析:</b>' + lv.level.explain;
    const nx = document.getElementById('resNext');
    if (nx) nx.style.display = ok ? '' : 'none';
    res.hidden = false;
    Sound.click(ok ? 0.6 : 0.3);
  }
  function nextLevel() {
    const cur = state.level ? examLevelById(state.level.id) : null;
    if (!cur) return;
    const idx = cur.ch.levels.indexOf(cur.level);
    const nxt = cur.ch.levels[idx + 1];
    document.getElementById('resultOverlay').hidden = true;
    if (nxt) enterLevel(nxt.id);
    else { exitLevel(); showToast('本章全部完成!'); }
  }
  function retryLevel() {
    if (!state.level) return;
    const id = state.level.id;
    const a = state.level.attempts, h = state.level.hints;
    enterLevel(id);
    if (state.level) { state.level.attempts = a; state.level.hints = h; }
  }
  function hintLevel() {
    if (!state.level) return;
    const lv = examLevelById(state.level.id);
    if (!lv) return;
    state.level.hints++;
    const tips = lv.level.tips || [];
    const i = Math.min(state.level.hintShown || 0, tips.length - 1);
    if (tips.length) {
      showToast('提示 ' + (i + 1) + '/' + tips.length + ':' + tips[i]);
      state.level.hintShown = i + 1;
    } else showToast('本关没有提示');
  }
  function explainLevel() {
    if (!state.level) return;
    const lv = examLevelById(state.level.id);
    if (!lv) return;
    const res = document.getElementById('resultOverlay');
    if (!res) return;
    const rt = document.getElementById('resTitle'); if (rt) rt.textContent = '📖 本关解析';
    const rs = document.getElementById('resSub'); if (rs) rs.textContent = '第 ' + lv.level.no + ' 关 · ' + lv.level.title;
    const st = document.getElementById('resStars'); if (st) st.textContent = '';
    const gl = document.getElementById('resGoals'); if (gl) gl.innerHTML = '';
    const ex = document.getElementById('resExplain'); if (ex) ex.innerHTML = '<b>解析:</b>' + lv.level.explain;
    const nx = document.getElementById('resNext'); if (nx) nx.style.display = 'none';
    res.hidden = false;
  }
  /* 绑定 */
  (function bindExam() {
    const on = function (id, fn) {
      const el = document.getElementById(id);
      if (el) el.addEventListener('click', function () { try { fn(); } catch (e) { showToast('出错了:' + e.message); } });
    };
    on('hubGoLevels', openPick);
    on('hubLevels', openPick);
    on('hubGoFree', function () { closeHub(); });
    on('hubFree', function () { closeHub(); });
    on('pickClose', function () { closePick(); enterHub(); });
    on('btnHome', function () { enterHub(); });
    on('btnExitLevel', exitLevel);
    on('btnJudge', judgeLevel);
    on('btnRetry', retryLevel);
    on('btnHint', hintLevel);
    on('btnExplain', explainLevel);
    on('resClose', function () { document.getElementById('resultOverlay').hidden = true; });
    on('resRetry', function () { document.getElementById('resultOverlay').hidden = true; retryLevel(); });
    on('resNext', nextLevel);
    on('resPick', function () { document.getElementById('resultOverlay').hidden = true; exitLevel(); });
    // 启动页快捷入口
    document.querySelectorAll('[data-hub]').forEach(function (b) {
      b.addEventListener('click', function () {
        const k = b.getAttribute('data-hub');
        closeHub();
        if (k === 'presets') { const t = document.getElementById('btnPresets'); if (t) t.click(); }
        if (k === 'learn') { const t = document.getElementById('btnLearn'); if (t) t.click(); }
        if (k === 'lib') { const t = document.getElementById('btnLib'); if (t) t.click(); }
        if (k === 'about') { const t = document.getElementById('btnAbout'); if (t) t.click(); }
      });
    });
    // 关卡列表:点条目或 ▶ 进入
    const pb = document.getElementById('pickBody');
    if (pb) pb.addEventListener('click', function (ev) {
      // 跳过引导章:标记本章已完成,解锁后面的章节
      const sk = ev.target && ev.target.closest ? ev.target.closest('[data-skip-ch]') : null;
      if (sk) {
        const chId = sk.getAttribute('data-skip-ch');
        const ch = EXAM_DB.chapters.find(function (c) { return c.id === chId; });
        if (ch) {
          try {
            const p = examProgress();
            p[ch.id + ':skip'] = 1;
            window.localStorage.setItem('circuitLab.exam', JSON.stringify(p));
          } catch (e) { }
          openPick();
          showToast('已跳过「' + ch.name + '」,后面的章节已解锁');
        }
        return;
      }
      const el = ev.target && ev.target.closest ? ev.target.closest('[data-level]') : null;
      if (!el || el.classList.contains('locked')) return;
      enterLevel(el.getAttribute('data-level'));
    });
    // 「选结论」选项:选中记下,判分前不揭晓对错
    const lbc = document.getElementById('lbChoices');
    if (lbc) lbc.addEventListener('click', function (ev) {
      const el = ev.target && ev.target.closest ? ev.target.closest('[data-choice]') : null;
      if (!el || !state.level) return;
      const gi = el.getAttribute('data-choice');
      const idx = parseInt(el.getAttribute('data-idx'), 10);
      if (!state.level.answers) state.level.answers = {};
      state.level.answers[gi] = idx;
      renderLevelChoices();
      showToast('已选择 ' + String.fromCharCode(65 + idx) + '(点「检查」判分)');
    });
  })();

  /* ===== 实验记录(v2.0):记录多组读数,像做实验那样从反复数据中得出普遍结论 ===== */
  function recordTrial() {
    const s = ensureSolved();
    const list = state.components.filter(function (c) { return c.type !== 'junction'; }).map(function (c) {
      const d = s.info.get(c.id) || { I: 0, U: 0, P: 0 };
      return { t: tagOf(c).trim(), I: Math.abs(d.I), U: Math.abs(d.U), P: Math.abs(d.P) };
    });
    if (!list.length) { showToast('画布上还没有可记录的元件'); return; }
    if (!state.trials) state.trials = [];
    state.trials.push({ no: state.trials.length + 1, at: new Date().toTimeString().slice(0, 5), rows: list });
    renderTrials();
    showToast('已记录第 ' + state.trials.length + ' 组数据(' + list.length + ' 行)');
  }
  function clearTrials() {
    state.trials = [];
    renderTrials();
    showToast('实验记录已清空');
  }
  function renderTrials() {
    const el = document.getElementById('trialList');
    if (!el) return;
    const ts = state.trials || [];
    if (!ts.length) { el.innerHTML = '<div class="empty">多测几组、点「记录本组数据」,从数据里找规律</div>'; return; }
    el.innerHTML = ts.map(function (t) {
      return '<div class="trial"><div class="trial-h">试验 ' + t.no + ' · ' + t.at + '</div>' +
        t.rows.map(function (r) {
          return '<div class="trial-r"><span>' + r.t + '</span><span>I ' + fmt(r.I, 3) +
            '</span><span>U ' + fmt(r.U, 3) + '</span><span>P ' + fmt(r.P, 3) + '</span></div>';
        }).join('') + '</div>';
    }).join('');
  }
  (function bindTrials() {
    const b1 = document.getElementById('btnRecord');
    if (b1) b1.addEventListener('click', function () { try { recordTrial(); } catch (e) { showToast('记录失败:' + e.message); } });
    const b2 = document.getElementById('btnClearTrials');
    if (b2) b2.addEventListener('click', function () { try { clearTrials(); } catch (e) { } });
    renderTrials();
  })();

  window.__circuitLab = {
    state: state,
    view: view,
    solved: function () { return ensureSolved(); },
    frame: function (ts) { frameLogic(ts); },
    soundDebug: function () { return Sound.debug(); },
    audioTargets: function () { return audioTargets(ensureSolved()); },
    toScreen: function (wx, wy) { return worldToScreen(wx, wy); },
    toWorld: function (sx, sy) { return screenToWorld(sx, sy); },
    fitView: function () { fitView(); },
    contentBounds: function () { return contentBounds(); },
    visibleWorld: function () { return visibleWorld(); },
    setMinimapHidden: function (h) { setMinimapHidden(h); },
    minimapWorldMap: function () { return mmWorldMap(); },
    termWorld: function (cid, ti) { const c = compById(cid); return c ? termPos(c, ti) : null; },
    pendingTerm: function () { return state.pendingTerm; },
    schematic: function () { const s = schemRender(); return s ? s.summary : null; },
    schematicModel: function () { return SchematicLab.build(); },
    schematicLayout: function () { const m = SchematicLab.build(); return SchematicLab.layout(m); },
    schemArrowDir: function (I, flip) { return SchematicLab.arrowDir(I, flip); },
    openSchematic: function () { openSchematic(); },
    closeSchematic: function () { closeSchematic(); },
    hitTerminal: function (p) { const t = hitTerminal(p); return t ? { cid: t.cid, ti: t.ti } : null; },
    hitTerminalAny: function (p) { const t = hitTerminalAny(p); return t ? { cid: t.cid, ti: t.ti } : null; },
    wireMode: function () { return state.wireMode; },
    clearPendingTerm: function () { clearPendingTerm(); },
    layoutMode: function () { return layoutMode; },
    applyLayoutMode: function (m, remember) { applyLayoutMode(m, remember); },
    openSheet: function (k) { openSheet(k); },
    closeSheet: function () { closeSheet(); },
    sheetKind: function () { return sheetOpenKind; },
    toast: function () { const t = document.getElementById('toast'); return t ? t.textContent : ''; },
    refreshPanels: function () { renderInspector(); },
    notes: function () { return state.notes || []; },
    learnStep: function () { return { i: learnIdx, total: LEARN_STEPS.length, on: learnOn, open: !!(learnOverlay && !learnOverlay.hidden), title: (LEARN_STEPS[learnIdx] || {}).t || '' }; },
    learnExit: function () { learnExit(); },
    learnBack: function () { learnBack(); },
    analyzeConnection: function () { return analyzeConnection(solveNow()); },   // 供测试:串联/并联判定
    learnNext: function () { const b = document.getElementById('learnNext'); if (b) b.click(); },
    openLearn: function () { const b = document.getElementById('btnLearn'); if (b) b.click(); },
    flashId: function () { return state.flash ? state.flash.id : null; },
    undo: function () { return doUndo(); },
    redo: function () { return doRedo(); },
    historyInfo: function () { return historyInfo(); },
    /* —— 关卡系统(测试用)—— */
    examDB: function () { return EXAM_DB; },
    examState: function () { return state.level; },
    examProgress: function () { return examProgress(); },
    examEnter: function (id) { enterLevel(id); },
    examJudge: function () {
      const lv = state.level ? examLevelById(state.level.id) : null;
      return lv ? examJudge(lv.level) : null;
    },
    examJudgeLevel: function (id) {
      const lv = examLevelById(id);
      return lv ? examJudge(lv.level) : null;
    },
    examUnlocked: function (chId, idx) {
      const ch = EXAM_DB.chapters.find(c => c.id === chId);
      return ch ? examUnlocked(ch, idx) : null;
    },
    examChapterDone: function (chId) {
      const ch = EXAM_DB.chapters.find(c => c.id === chId);
      return ch ? examChapterDone(ch) : null;
    },
    examSkipChapter: function (chId) {
      const ch = EXAM_DB.chapters.find(c => c.id === chId);
      if (!ch) return false;
      try {
        const p = examProgress();
        p[ch.id + ':skip'] = 1;
        window.localStorage.setItem('circuitLab.exam', JSON.stringify(p));
      } catch (e) { }
      return true;
    },
    examGoalOf: function (g, s) { return examGoal(g, s); },
    trials: function () { return state.trials || []; },
    exportExperiment: function () { return exportExperimentJSON(); },
    importExperiment: function (t) { return importExperimentJSON(t); },
    saveExperiment: function () { return saveExperimentFile(); },
    openExperiment: function () { return openExperimentFile(); },
    exportCanvas: function () { return exportCanvasPNG(); },
    meterRangeOf: function (cid) { const c = compById(cid); return c ? meterRange(c) : null; },
    meterOverOf: function (cid) {
      const c = compById(cid); if (!c) return null;
      const s = ensureSolved();
      return meterOver(c, s.info.get(cid));
    }
  };

  /* ---------- 启动 ---------- */
  // 读取上次的缩略图设置
  try {
    const savedMM = window.localStorage && window.localStorage.getItem('circuitLab.minimap');
    if (savedMM) {
      const o = JSON.parse(savedMM);
      if (o && typeof o.w === 'number') state.mm.w = Math.max(96, Math.min(460, o.w));
      if (o && typeof o.h === 'number') state.mm.h = Math.max(64, Math.min(320, o.h));
      if (o && o.hidden) state.mm.hidden = true;
      if (o && o.pos && typeof o.pos.left === 'number' && typeof o.pos.top === 'number') {
        state.mm.pos = { left: o.pos.left, top: o.pos.top };
      }
    }
  } catch (e) { }
  if ((window.innerWidth || 1000) < 640 && state.mm.w > 140) { state.mm.w = 130; state.mm.h = 84; }
  mmApplySize();
  mmApplyPos();
  if (mmBox) mmBox.style.display = state.mm.hidden ? 'none' : 'block';
  if (btnMinimap) btnMinimap.addEventListener('click', () => setMinimapHidden(!state.mm.hidden));

  /* ================= 布局模式:手机版 / 电脑版 =================
     不弹窗问用户:默认自动识别(触屏 + 窄屏 = 手机版),工具栏一键切换并记住选择。 */
  const mbarEl = document.getElementById('mbar');
  // 手机端提示条:可收起,并记住选择(localStorage)
  const mHintEl = document.getElementById('mHint');
  try {
    if (window.localStorage && window.localStorage.getItem('circuitLab.hint') === 'off' && mHintEl) {
      mHintEl.className = (mHintEl.className + ' off').trim();
    }
  } catch (e) { }
  const mHintCloseEl = document.getElementById('mHintClose');
  if (mHintCloseEl && mHintEl) {
    mHintCloseEl.addEventListener('click', () => {
      mHintEl.className = (mHintEl.className + ' off').trim();
      try { if (window.localStorage) window.localStorage.setItem('circuitLab.hint', 'off'); } catch (e) { }
      resize();
    });
  }
  const mSheetEl = document.getElementById('mSheet');
  const mSheetBody = document.getElementById('mSheetBody');
  const mSheetTitle = document.getElementById('mSheetTitle');
  const mScrimEl = document.getElementById('mScrim');
  let cardHome = null;          // 记录卡片原来的位置,切回电脑版时放回去
  let sheetOpenKind = null;

  function detectLayoutMode() {
    const saved = readLayoutMode();
    if (saved) return saved;
    let coarse = false;
    try { coarse = !!(window.matchMedia && window.matchMedia('(pointer:coarse)').matches); } catch (e) { }
    const narrow = (window.innerWidth || 1000) <= 620;
    return (coarse || narrow) ? 'mobile' : 'desktop';
  }
  function readLayoutMode() {
    try {
      const v = window.localStorage ? window.localStorage.getItem('circuitLab.layout') : null;
      return (v === 'mobile' || v === 'desktop') ? v : null;
    } catch (e) { return null; }
  }
  function saveLayoutMode(mode) {
    try { if (window.localStorage) window.localStorage.setItem('circuitLab.layout', mode); } catch (e) { }
  }
  // 手机版要搬进抽屉的卡片(操作说明也要,否则手机上就没有操作提示了)
  const MOBILE_CARDS = ['paletteCard', 'statusCard', 'readoutCard', 'inspectorCard', 'tipsCard', 'hintCard', 'fileCard'];
  function applyLayoutMode(mode, remember) {
    const changed = layoutMode !== ((mode === 'mobile') ? 'mobile' : 'desktop');
    layoutMode = (mode === 'mobile') ? 'mobile' : 'desktop';
    if (remember) saveLayoutMode(layoutMode);
    setBodyFlag('mobile', layoutMode === 'mobile');   // 只增删 mobile,不影响 dark 等其他标记
    const btn = document.getElementById('btnLayout');
    if (btn) {
      btn.innerHTML = '<span class="icg">' + (layoutMode === 'mobile' ? '📱' : '🖥') + '</span>' +
        '<span class="lbl" id="lblLayout">' + (layoutMode === 'mobile' ? '手机版' : '电脑版') + '</span>';
      btn.title = layoutMode === 'mobile' ? '当前是手机版布局,点击切到电脑版' : '当前是电脑版布局,点击切到手机版';
    }
    // 把右侧卡片搬进/搬出抽屉
    const cards = MOBILE_CARDS
      .map(id => document.getElementById(id)).filter(Boolean);
    if (!cardHome || !cardHome.length) {
      // 记住原父节点和"原索引":还原时按索引插回去,
      // (只记 next 兄弟节点是不行的——还原时它自己也还在抽屉里,会导致全部被追加到末尾)
      cardHome = cards.map(c => ({
        el: c,
        parent: c.parentNode,
        index: c.parentNode ? Array.prototype.indexOf.call(c.parentNode.children, c) : -1
      }));
    }
    const fallbackHome = () => (cardHome && cardHome.map(h => h.parent).filter(Boolean)[0]) ||
      document.getElementById('panelHome') || null;
    if (layoutMode === 'mobile') {
      cardHome.forEach(h => { if (h.el.parentNode !== mSheetBody) mSheetBody.appendChild(h.el); });
        const hc = document.getElementById('hintCard');
        if (hc) hc.open = true;              // 手机版默认展开操作说明,打开抽屉就能看到
      // 手机版默认收起抽屉,只留底部栏;选中元件时再自动弹出"参数"
      if (changed) closeSheet();
    } else {
      // 按原索引从小到大依次插回,恢复原来的上下顺序
      cardHome.slice().sort((a, b) => a.index - b.index).forEach(h => {
        const home = h.parent || fallbackHome();
        if (!home || !home.appendChild) return;
        if (home === h.el.parentNode) return;
        const ref = (h.index >= 0 && home.children) ? home.children[h.index] || null : null;
        if (ref && ref !== h.el && home.insertBefore) home.insertBefore(h.el, ref);
        else home.appendChild(h.el);
      });
      if (changed) closeSheet();
    }
    renderInspector();
    resize();
  }
  function openSheet(kind) {
    if (state.pendingTerm) { state.pendingTerm = null; state.dirty = true; }   // 避免"半截连线"残留
    syncLearnBarForSheet(kind);        // 传 kind:此刻 sheetOpenKind 还没赋值
    if (layoutMode !== 'mobile' || !mSheetEl) return;
    const listEl = document.getElementById('presetList');
    if (kind === 'presets') {
      mSheetTitle.textContent = '演示电路';
      MOBILE_CARDS
        .forEach(id => { const c = document.getElementById(id); if (c) c.style.display = 'none'; });
      if (listEl) {
        listEl.style.display = 'flex';
        listEl.className = 'menulist mobile-presets';
        if (listEl.parentNode !== mSheetBody) mSheetBody.appendChild(listEl);
      }
      sheetOpenKind = kind;
      setElClass(mSheetEl, 'on', true);
      setElClass(mScrimEl, 'on', true);
      return;
    }
    if (listEl) { listEl.style.display = ''; listEl.className = 'menulist'; }
    const map = {
      palette: ['元件', ['paletteCard']],
      inspector: ['参数', ['inspectorCard']],
      data: ['数据', ['statusCard', 'readoutCard', 'tipsCard', 'hintCard']],
      file: ['文件', ['fileCard']]
    };
    const cfg = map[kind] || map.palette;
    mSheetTitle.textContent = cfg[0];
    const tipEl = document.getElementById('mSheetTip');
    if (tipEl) {
      tipEl.textContent = (kind === 'palette')
        ? '可以连续点多个元件,加完再收起(新元件会出现在抽屉上方可见处)' : '';
      tipEl.style.display = (kind === 'palette') ? '' : 'none';
    }
    const cards = MOBILE_CARDS
      .map(id => document.getElementById(id)).filter(Boolean);
    cards.forEach(c => { c.style.display = cfg[1].indexOf(c.id) >= 0 ? '' : 'none'; });
    sheetOpenKind = kind;
    setElClass(mSheetEl, 'on', true);
    setElClass(mScrimEl, 'on', true);
  }
  function closeSheet() {
    syncLearnBarForSheet(null);        // 收起抽屉后立刻恢复学习条
    sheetOpenKind = null;
    state.addStreak = null;
    setElClass(mSheetEl, 'on', false);
    setElClass(mScrimEl, 'on', false);
    MOBILE_CARDS
      .forEach(id => { const c = document.getElementById(id); if (c) c.style.display = ''; });
    // 演示电路列表放回下拉菜单里
    const listEl = document.getElementById('presetList');
    const menu = document.getElementById('presetMenu');
    if (listEl && menu && listEl.parentNode !== menu) { listEl.className = 'menulist'; menu.appendChild(listEl); }
  }
  if (mbarEl) {
    const bind = (id, kind) => {
      const b = document.getElementById(id);
      if (!b) return;
      b.addEventListener('click', () => {
        if (sheetOpenKind === kind) { closeSheet(); return; }
        openSheet(kind);
        Sound.click(0.4);
      });
    };
    bind('mBtnPalette', 'palette');
    bind('mBtnPresets', 'presets');
    bind('mBtnInspector', 'inspector');
    bind('mBtnData', 'data');
    bind('mBtnFile', 'file');
    const fitBtn = document.getElementById('mBtnFit');
    if (fitBtn) fitBtn.addEventListener('click', () => { fitView(); Sound.click(0.4); });
  }
  if (mSheetEl) {
    const closeBtn = document.getElementById('mSheetClose');
    if (closeBtn) closeBtn.addEventListener('click', closeSheet);
  }
  if (mScrimEl) mScrimEl.addEventListener('click', closeSheet);
  /* ---------- 演示电路下拉菜单 ---------- */
  const presetMenuEl = document.getElementById('presetMenu');
  const btnPresetsEl = document.getElementById('btnPresets');
  function closePresetMenu() { if (presetMenuEl) presetMenuEl.hidden = true; setElClass(btnPresetsEl, 'on', false); }
  function togglePresetMenu() {
    if (!presetMenuEl) return;
    const willOpen = !!presetMenuEl.hidden;
    presetMenuEl.hidden = !willOpen;
    setElClass(btnPresetsEl, 'on', willOpen);
    Sound.click(0.4);
  }
  if (btnPresetsEl) {
    btnPresetsEl.addEventListener('click', ev => {
      ev.stopPropagation();
      if (layoutMode === 'mobile') { openSheet('presets'); return; }   // 手机:用底部抽屉
      togglePresetMenu();
    });
  }
  if (presetMenuEl) {
    presetMenuEl.addEventListener('click', ev => {
      const b = ev.target && ev.target.closest ? ev.target.closest('[data-preset]') : null;
      if (b) closePresetMenu();                                       // 选中后收起
      ev.stopPropagation();
    });
  }
  window.addEventListener('click', () => closePresetMenu());
  window.addEventListener('keydown', ev => { if (ev.key === 'Escape') closePresetMenu(); });

  const btnLayoutEl = document.getElementById('btnLayout');
  if (btnLayoutEl) {
    btnLayoutEl.addEventListener('click', () => {
      applyLayoutMode(layoutMode === 'mobile' ? 'desktop' : 'mobile', true);
      Sound.click(0.5);
    });
  }
  // 触屏下轻点空白处应"取消选择",而不是等框选判定
  applyLayoutMode(detectLayoutMode(), false);

  resize();
  loadPreset('basic');
  undoStack.length = 0; redoStack.length = 0;   // 启动时的默认电路不算"一步操作"
  updateHistoryButtons();
  fitView();                       // 载入后把电路缩放居中显示
  requestAnimationFrame(frame);
  // 脚本成功运行 → 收起启动提示
  const bootEl = document.getElementById('boot');
  if (bootEl && bootEl.parentNode) bootEl.parentNode.removeChild(bootEl);
  // v2.0 M1:启动即见主菜单(关卡模式 / 自由创造 两大类)
  enterHub();
})();
</script>
</body>
</html>

Game Source: 简易电路实验展示 · 物理课堂演示

Creator: ElectricWizard16

Libraries: none

Complexity: complex (8608 lines, 467.6 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: game-electricwizard16" to link back to the original. Then publish at arcadelab.ai/publish.