Files

44 lines
2.0 KiB
JavaScript

import { h } from '/static/admin2/vendor/preact.module.js';
import htm from '/static/admin2/vendor/htm.module.js';
const html = htm.bind(h);
// SVG-атрибуты, не style: CSP v2 запрещает inline-стили.
// Ширина полотна ПОСТОЯННАЯ: раньше она считалась от числа точек, и при одном месяце
// viewBox сжимался до единиц, а SVG с width:100% растягивался в многоэкранную полосу.
const W = 600;
export const Bars = ({ values, label, labels = [] }) => {
const max = Math.max(1, ...values.map((v) => Math.max(0, v)));
const h0 = 90;
const n = Math.max(1, values.length);
const slot = W / n;
const bw = Math.min(48, slot * 0.6);
return html`<figure class="chart">
<figcaption>${label}</figcaption>
<svg viewBox=${`0 0 ${W} ${h0 + 18}`} role="img" aria-label=${label}>
${values.map((v, i) => html`<rect key=${i} x=${i * slot + (slot - bw) / 2}
y=${h0 - Math.max(0, v) / max * h0}
width=${bw} height=${Math.max(1, v) / max * h0} rx="2" fill="#2457d6"></rect>`)}
${labels.map((m, i) => html`<text key=${'l' + i} x=${i * slot + slot / 2} y=${h0 + 14}
font-size="11" text-anchor="middle" fill="#667085">${String(m).slice(5)}</text>`)}
</svg>
</figure>`;
};
export const Line = ({ values, label }) => {
const max = Math.max(1, ...values.map((v) => Math.max(0, v)));
const n = values.length;
const step = n > 1 ? W / (n - 1) : 0;
const x = (i) => n > 1 ? i * step : W / 2;
const y = (v) => 90 - Math.max(0, v) / max * 80;
const pts = values.map((v, i) => `${x(i)},${y(v)}`).join(' ');
return html`<figure class="chart">
<figcaption>${label}</figcaption>
<svg viewBox=${`0 0 ${W} 94`} role="img" aria-label=${label}>
${n > 1
? html`<polyline points=${pts} fill="none" stroke="#067647" stroke-width="3"></polyline>`
: html`<circle cx=${x(0)} cy=${y(values[0] || 0)} r="4" fill="#067647"></circle>`}
</svg>
</figure>`;
};