mingdao-timeseries.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /* ══════════════════════════════════════════════════════════════════
  2. 铭道 · 通用时间序列图(mts-* = Mingdao Time Series)
  3. v1.0 · 2026-08-14 · 从顾问端健康K线(mdk-*)泛化 · 净资产趋势/CFHI 等共用
  4. 用法:MingdaoTS.create({ mount, ranges, defaultRange, footFn, ... })
  5. 特性:周期档位 · 三态渲染(full/partial/empty)· 胶囊标注(起始/最高/最低/当前 · 同点自动合并)
  6. 整齐 Y 轴步长(2/4/5/10)· 家族/用户维度 points 映射 · compact 移动模式
  7. 纯 SVG 字符串渲染 · 零依赖 · CSS 自注入 · Phase 2 迁 RN 只换本渲染层
  8. ══════════════════════════════════════════════════════════════════ */
  9. window.MingdaoTS = (function () {
  10. var CSS = ''
  11. + '.mts-bar{display:flex;flex-direction:row;flex-wrap:wrap;gap:4px;justify-content:flex-end}'
  12. + '.mts-rbtn{font-family:"Noto Sans SC",sans-serif;font-size:.6rem;line-height:1;color:var(--text-muted,var(--ink-mute,#8A938E));background:transparent;border:1px solid rgba(44,110,73,.22);border-radius:99px;padding:5px 11px;cursor:pointer;transition:all .18s;white-space:nowrap}'
  13. + '.mts-rbtn:hover{color:var(--primary,#2C6E49);border-color:rgba(44,110,73,.5);background:rgba(44,110,73,.05)}'
  14. + '.mts-rbtn.active{color:#fff;background:var(--primary,#2C6E49);border-color:var(--primary,#2C6E49);font-weight:600}'
  15. + '.mts-rbtn.no-data{opacity:.62}'
  16. + '.mts-rbtn.no-data::after{content:"·";margin-left:4px;color:var(--amber,#C77A2C);font-weight:700}'
  17. + '.mts-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;min-height:240px;padding:22px 18px;text-align:center;background:repeating-linear-gradient(135deg,rgba(44,110,73,.028) 0 10px,transparent 10px 20px);border:1px dashed rgba(44,110,73,.26);border-radius:10px}'
  18. + '.mts-empty-ic{font-size:1.4rem;opacity:.5}'
  19. + '.mts-empty-t{font-family:"Noto Serif SC",serif;font-size:.78rem;font-weight:600;color:var(--text,var(--ink,#22312B))}'
  20. + '.mts-empty-d{font-family:"Noto Sans SC",sans-serif;font-size:.6rem;color:var(--text-muted,var(--ink-mute,#8A938E));line-height:1.8;max-width:540px}';
  21. function injectCSS() {
  22. if (document.getElementById('mts-css')) return;
  23. var st = document.createElement('style');
  24. st.id = 'mts-css';
  25. st.textContent = CSS;
  26. document.head.appendChild(st);
  27. }
  28. /* 整齐步长(2/4/5/10) */
  29. function cleanAxis(vMin, vMax) {
  30. var cands = [2, 4, 5, 10];
  31. for (var i = 0; i < cands.length; i++) {
  32. var st = cands[i];
  33. var l = Math.floor((vMin - 1.5) / st) * st;
  34. var h = Math.ceil((vMax + 1.5) / st) * st;
  35. var nb = (h - l) / st;
  36. if (nb >= 3 && nb <= 5) return { lo: l, hi: h, step: st, bands: nb };
  37. }
  38. var l5 = Math.floor((vMin - 1.5) / 5) * 5;
  39. return { lo: l5, hi: l5 + 20, step: 5, bands: 4 };
  40. }
  41. function textWidth(s, fs) {
  42. var w = 0;
  43. for (var c = 0; c < s.length; c++) {
  44. var ch = s[c];
  45. w += ch === ' ' ? .30 : ch === '·' ? .50 : (ch.charCodeAt(0) < 128 ? .56 : 1.0);
  46. }
  47. return w * fs;
  48. }
  49. function capsule(cx, cy, text, fs, fill, anchor, VB_W) {
  50. var w = textWidth(text, fs) + 24, h = fs + 12;
  51. var x = anchor === 'start' ? cx : anchor === 'end' ? cx - w : cx - w / 2;
  52. x = Math.max(2, Math.min(x, VB_W - w - 2));
  53. var y = cy - h / 2, tip = Math.min(Math.max(cx, x + 10), x + w - 10);
  54. return '<g><rect x="' + x.toFixed(1) + '" y="' + y.toFixed(1) + '" width="' + w.toFixed(1) + '" height="' + h + '" rx="' + (h / 2) + '" fill="' + fill + '"/>'
  55. + '<path d="M' + (tip - 5) + ',' + (y + h).toFixed(1) + ' L' + (tip + 5) + ',' + (y + h).toFixed(1) + ' L' + tip.toFixed(1) + ',' + (y + h + 6.5).toFixed(1) + ' Z" fill="' + fill + '"/>'
  56. + '<text x="' + (x + w / 2).toFixed(1) + '" y="' + (cy + fs * .36).toFixed(1) + '" text-anchor="middle" font-family="\'Playfair Display\',\'Noto Serif SC\',serif" font-size="' + fs + '" font-weight="700" fill="#fff" letter-spacing=".5">' + text + '</text></g>';
  57. }
  58. function resolvePoints(points, userKey) {
  59. if (!points) return null;
  60. if (points instanceof Array) return points;
  61. return points[userKey] || points['demo-user'] || null;
  62. }
  63. /* cfg: { mount, ranges, defaultRange, userKey|userFn, footFn(rangeKey,userKey,stats), emptyFn(R),
  64. compact, hero:{id, valueFn(userKey)} } */
  65. function create(cfg) {
  66. injectCSS();
  67. var mount = cfg.mount;
  68. var uid = 'mts' + Math.floor(Math.random() * 1e6);
  69. var cur = null;
  70. function userKey() { return cfg.userFn ? cfg.userFn() : (cfg.userKey || 'demo-user'); }
  71. var btns = Object.keys(cfg.ranges).map(function (rk) {
  72. return '<button type="button" class="mts-rbtn" data-range="' + rk + '">' + cfg.ranges[rk].label + '</button>';
  73. }).join('');
  74. // title === false → 只渲染档位行(宿主卡片自带标题时)
  75. mount.innerHTML = (cfg.title === false
  76. ? '<div style="display:flex;flex-direction:row;justify-content:flex-end;margin-bottom:8px"><div class="mts-bar" id="' + uid + '-bar">' + btns + '</div></div>'
  77. : '<div style="display:flex;flex-direction:row;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px">'
  78. + '<div style="font-family:\'Noto Serif SC\',serif;font-size:.6rem;font-weight:700;color:var(--text,var(--ink,#22312B))">' + (cfg.title || '📈 走势') + '</div>'
  79. + '<div class="mts-bar" id="' + uid + '-bar" style="margin-left:auto">' + btns + '</div></div>')
  80. + '<div id="' + uid + '-chart"></div>'
  81. + '<div id="' + uid + '-foot" style="font-size:.56rem;color:var(--text-muted,var(--ink-mute,#8A938E));line-height:1.7;padding-top:6px;border-top:1px dashed rgba(44,110,73,.14)"></div>';
  82. mount.querySelector('#' + uid + '-bar').addEventListener('click', function (e) {
  83. var btn = e.target.closest('.mts-rbtn');
  84. if (btn) render(btn.getAttribute('data-range'));
  85. });
  86. function render(rangeKey) {
  87. var R = cfg.ranges[rangeKey];
  88. if (!R) return;
  89. cur = rangeKey;
  90. var chart = mount.querySelector('#' + uid + '-chart');
  91. var foot = mount.querySelector('#' + uid + '-foot');
  92. // 按钮态
  93. mount.querySelectorAll('.mts-rbtn').forEach(function (b) {
  94. var rk = b.getAttribute('data-range');
  95. b.classList.toggle('active', rk === rangeKey);
  96. var rp = resolvePoints(cfg.ranges[rk].points, userKey());
  97. b.classList.toggle('no-data', !(rp && rp.some(function (v) { return v !== null; })));
  98. });
  99. var pts = resolvePoints(R.points, userKey());
  100. var hasAny = !!(pts && pts.some(function (v) { return v !== null; }));
  101. if (!hasAny) {
  102. chart.innerHTML = cfg.emptyFn ? cfg.emptyFn(R)
  103. : '<div class="mts-empty"><div class="mts-empty-ic">⏳</div><div class="mts-empty-t">' + R.label + ' · 数据待接入</div>'
  104. + '<div class="mts-empty-d">该区间数据须由后台按数据契约回填后自动点亮 · 缺失时点回 null(不可用 0 代替)。<br>接口规格见 docs/数据契约 · 健康K线 CFHI 时间序列 v1.0.md</div></div>';
  105. foot.innerHTML = cfg.footEmptyFn ? cfg.footEmptyFn(R) : '';
  106. return;
  107. }
  108. var n = pts.length;
  109. var firstIdx = pts.findIndex(function (v) { return v !== null; });
  110. var lastIdx = n - 1 - pts.slice().reverse().findIndex(function (v) { return v !== null; });
  111. var real = [];
  112. for (var i = firstIdx; i <= lastIdx; i++) if (pts[i] !== null) real.push({ i: i, v: pts[i] });
  113. var vals = real.map(function (o) { return o.v; });
  114. var vMin = Math.min.apply(null, vals), vMax = Math.max.apply(null, vals);
  115. var vStart = vals[0], vNow = vals[vals.length - 1];
  116. var iMax = real[vals.indexOf(vMax)].i, iMin = real[vals.indexOf(vMin)].i;
  117. var compact = !!cfg.compact;
  118. var VB_W = compact ? 420 : 1000, VB_H = compact ? 260 : 320; // 08-14 加高 + compact 改 420 窄坐标系(1单位≈1px · 否则 420px 容器下整图缩小 2.6 倍)
  119. var X0 = compact ? 34 : 52, X1 = compact ? 400 : 962, Y_TOP = compact ? 38 : 44, Y_BOT = compact ? 204 : 252;
  120. var ax = cleanAxis(vMin, vMax);
  121. var X = function (i) { return X0 + (X1 - X0) * (n === 1 ? 0 : i / (n - 1)); };
  122. var Y = function (v) { return Y_BOT - (v - ax.lo) / (ax.hi - ax.lo) * (Y_BOT - Y_TOP); };
  123. var colLine = cfg.color || '#2C6E49';
  124. var s = '<svg viewBox="0 0 ' + VB_W + ' ' + VB_H + '" style="width:100%;height:auto;display:block">';
  125. s += '<defs><linearGradient id="' + uid + 'g" x1="0" y1="0" x2="0" y2="1">'
  126. + '<stop offset="0" stop-color="' + colLine + '" stop-opacity=".22"/><stop offset="1" stop-color="' + colLine + '" stop-opacity="0"/></linearGradient>'
  127. + '<pattern id="' + uid + 'h" width="8" height="8" patternTransform="rotate(45)" patternUnits="userSpaceOnUse">'
  128. + '<rect width="8" height="8" fill="rgba(154,148,132,.05)"/><line x1="0" y1="0" x2="0" y2="8" stroke="rgba(154,148,132,.3)" stroke-width="1.4"/></pattern></defs>';
  129. for (var g = 0; g <= ax.bands; g++) {
  130. var gv = ax.lo + ax.step * g;
  131. s += '<line x1="' + X0 + '" y1="' + Y(gv).toFixed(1) + '" x2="' + X1 + '" y2="' + Y(gv).toFixed(1) + '" stroke="rgba(44,110,73,.10)" stroke-width="1" stroke-dasharray="4 4"/>';
  132. s += '<text x="' + (X0 - 9) + '" y="' + (Y(gv) + 4.5).toFixed(1) + '" text-anchor="end" font-family="\'Playfair Display\',serif" font-size="13" fill="#9A9484">' + Math.round(gv) + '</text>';
  133. }
  134. if (firstIdx > 0) {
  135. var mw = X(firstIdx) - X0;
  136. s += '<rect x="' + X0 + '" y="' + Y_TOP + '" width="' + mw.toFixed(1) + '" height="' + (Y_BOT - Y_TOP) + '" fill="url(#' + uid + 'h)"/>';
  137. s += '<text x="' + (X0 + mw / 2).toFixed(1) + '" y="' + ((Y_TOP + Y_BOT) / 2).toFixed(1) + '" text-anchor="middle" font-family="\'Noto Sans SC\',sans-serif" font-size="13" fill="#9A9484">该区间暂无数据</text>';
  138. s += '<line x1="' + X(firstIdx).toFixed(1) + '" y1="' + Y_TOP + '" x2="' + X(firstIdx).toFixed(1) + '" y2="' + Y_BOT + '" stroke="rgba(154,148,132,.5)" stroke-width="1.2" stroke-dasharray="3 3"/>';
  139. }
  140. var d = real.map(function (o, k) { return (k ? 'L' : 'M') + X(o.i).toFixed(1) + ',' + Y(o.v).toFixed(1); }).join(' ');
  141. s += '<path d="' + d + ' L' + X(lastIdx).toFixed(1) + ',' + Y_BOT + ' L' + X(firstIdx).toFixed(1) + ',' + Y_BOT + ' Z" fill="url(#' + uid + 'g)"/>';
  142. s += '<path d="' + d + '" fill="none" stroke="' + colLine + '" stroke-width="2.6" stroke-linejoin="round"/>';
  143. if (real.length <= 40) real.forEach(function (o) {
  144. if (o.i !== iMax && o.i !== iMin && o.i !== lastIdx)
  145. s += '<circle cx="' + X(o.i).toFixed(1) + '" cy="' + Y(o.v).toFixed(1) + '" r="2.2" fill="' + colLine + '" opacity=".38"/>';
  146. });
  147. // 胶囊:同点自动合并(起始=最低 / 最高=当前)
  148. var GOLD = '#B8954A', RED = '#B5433A';
  149. var fsMax = compact ? 13 : 14, fsMin = compact ? 12.5 : 13.5, fsNow = compact ? 14 : 15.5;
  150. var sameSM = (iMin === firstIdx && vMin === vStart);
  151. var sameMN = (vMax === vNow); // 平台尾段首现最高≠末点也算同值 → 合并(与顾问端 mdk 一致)
  152. // 最高
  153. if (!sameMN) {
  154. s += '<line x1="' + X(iMax).toFixed(1) + '" y1="' + Y(vMax).toFixed(1) + '" x2="' + X(iMax).toFixed(1) + '" y2="' + Y_BOT + '" stroke="rgba(184,149,74,.42)" stroke-width="1.2" stroke-dasharray="3 4"/>';
  155. s += '<circle cx="' + X(iMax).toFixed(1) + '" cy="' + Y(vMax).toFixed(1) + '" r="5.5" fill="' + GOLD + '" stroke="#fff" stroke-width="2.2"/>';
  156. s += capsule(X(iMax), Y(vMax) - (compact ? 24 : 26), '最高 ' + vMax, fsMax, GOLD, 'middle', VB_W);
  157. }
  158. // 起始/最低
  159. s += '<line x1="' + X(iMin).toFixed(1) + '" y1="' + Y(vMin).toFixed(1) + '" x2="' + X(iMin).toFixed(1) + '" y2="' + Y_BOT + '" stroke="rgba(181,67,58,.35)" stroke-width="1.2" stroke-dasharray="3 4"/>';
  160. s += '<circle cx="' + X(iMin).toFixed(1) + '" cy="' + Y(vMin).toFixed(1) + '" r="5.5" fill="' + RED + '" stroke="#fff" stroke-width="2.2"/>';
  161. s += capsule(X(iMin), Y(vMin) - (compact ? 24 : 26), (sameSM ? '起始 · 最低 ' : '最低 ') + vMin, fsMin, RED, 'start', VB_W);
  162. if (!sameSM) {
  163. s += '<circle cx="' + X(firstIdx).toFixed(1) + '" cy="' + Y(vStart).toFixed(1) + '" r="4.5" fill="#8A8A7A" stroke="#fff" stroke-width="2"/>';
  164. s += capsule(X(firstIdx), Y(vStart) - (compact ? 22 : 24), '起始 ' + vStart, compact ? 12 : 13, '#8A8A7A', 'start', VB_W);
  165. }
  166. // 当前
  167. s += '<circle cx="' + X(lastIdx).toFixed(1) + '" cy="' + Y(vNow).toFixed(1) + '" r="10" fill="' + colLine + '" opacity=".2">'
  168. + '<animate attributeName="r" values="7;15;7" dur="2.2s" repeatCount="indefinite"/>'
  169. + '<animate attributeName="opacity" values=".3;.05;.3" dur="2.2s" repeatCount="indefinite"/></circle>';
  170. s += '<circle cx="' + X(lastIdx).toFixed(1) + '" cy="' + Y(vNow).toFixed(1) + '" r="6" fill="' + colLine + '" stroke="#fff" stroke-width="2.4"/>';
  171. s += capsule(X(lastIdx), Y(vNow) - (compact ? 26 : 28), (sameMN ? '当前 · 最高 ' : '当前 ') + vNow, fsNow, colLine, 'end', VB_W);
  172. // x 轴
  173. s += '<line x1="' + X0 + '" y1="' + Y_BOT + '" x2="' + X1 + '" y2="' + Y_BOT + '" stroke="rgba(44,110,73,.2)" stroke-width="1.2"/>';
  174. var axl = R.axis || [];
  175. axl.forEach(function (t, k) {
  176. var px = X0 + (X1 - X0) * k / (axl.length - 1);
  177. var an = k === 0 ? 'start' : k === axl.length - 1 ? 'end' : 'middle';
  178. s += '<text x="' + px.toFixed(1) + '" y="' + (Y_BOT + 20) + '" text-anchor="' + an + '" font-size="12" fill="#9A9484">' + t + '</text>';
  179. });
  180. s += '<text x="' + X0 + '" y="' + (Y_BOT + (compact ? 40 : 43)) + '" text-anchor="start" font-family="\'Playfair Display\',serif" font-size="13" fill="#6B6B5E">区间 ' + vMin + ' – ' + vMax + ' 振幅 ' + (+(vMax - vMin).toFixed(1)) + ' 分 净变 <tspan fill="' + colLine + '" font-weight="700">' + (vNow - vStart >= 0 ? '+' : '') + (+(vNow - vStart).toFixed(1)) + '</tspan></text>';
  181. s += '<text x="' + X1 + '" y="' + (Y_BOT + (compact ? 40 : 43)) + '" text-anchor="end" font-family="\'Playfair Display\',serif" font-size="12" letter-spacing="2" fill="#C9A84C">' + (cfg.brandTag || 'MINGDAO') + ' · ' + rangeKey + '</text>';
  182. s += '</svg>';
  183. chart.innerHTML = s;
  184. if (foot) foot.innerHTML = cfg.footFn ? cfg.footFn(rangeKey, userKey(), {
  185. start: vStart, min: vMin, max: vMax, now: vNow, n: n, real: real.length,
  186. partial: firstIdx > 0 || lastIdx < n - 1
  187. }) : '';
  188. }
  189. render(cfg.defaultRange || Object.keys(cfg.ranges)[0]);
  190. return { render: render, current: function () { return cur; } };
  191. }
  192. return { create: create };
  193. })();