335 lines
13 KiB
JavaScript
335 lines
13 KiB
JavaScript
import { escapeText } from "./text-runtime.js";
|
|
const types = new Set([
|
|
"line",
|
|
"area",
|
|
"bar",
|
|
"stacked",
|
|
"donut",
|
|
"gauge",
|
|
"sparkline",
|
|
]);
|
|
export function mountChart(root, initial) {
|
|
const abort = new AbortController(),
|
|
{ signal } = abort;
|
|
let options = {},
|
|
model,
|
|
active = -1,
|
|
disposed = false;
|
|
root.classList.add("metric-chart");
|
|
const format = (value, unit = "") =>
|
|
value == null
|
|
? "—"
|
|
: `${new Intl.NumberFormat(model.t("ru-RU", "en-US"), { maximumFractionDigits: 1 }).format(value)}${unit ? " " + unit : ""}`;
|
|
function normalize(options) {
|
|
const type = options.type || "line";
|
|
if (!types.has(type)) throw new TypeError("Unknown chart type");
|
|
const series = (options.series || []).slice(0, 8).map((item) => ({
|
|
name: String(item.name || ""),
|
|
values: (item.values || [])
|
|
.slice(0, 120)
|
|
.map((value) => (value == null ? null : Number(value))),
|
|
}));
|
|
if (
|
|
series.some((item) =>
|
|
item.values.some((value) => value !== null && !Number.isFinite(value)),
|
|
)
|
|
)
|
|
throw new TypeError("Chart data must be finite numbers or null");
|
|
if (
|
|
["stacked", "donut", "gauge"].includes(type) &&
|
|
series.some((item) =>
|
|
item.values.some((value) => value !== null && value < 0),
|
|
)
|
|
)
|
|
throw new TypeError("This chart needs non-negative data");
|
|
const count = Math.max(0, ...series.map((item) => item.values.length)),
|
|
labels = Array.from({ length: count }, (_, index) =>
|
|
String(options.labels?.[index] ?? index + 1),
|
|
);
|
|
const values = series
|
|
.flatMap((item) => item.values)
|
|
.filter((value) => value !== null);
|
|
let min = options.min ?? Math.min(0, ...values),
|
|
max = options.max ?? Math.max(1, ...values);
|
|
if (type === "stacked")
|
|
max =
|
|
options.max ??
|
|
Math.max(
|
|
1,
|
|
...labels.map((_, index) =>
|
|
series.reduce((sum, item) => sum + (item.values[index] || 0), 0),
|
|
),
|
|
);
|
|
if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min) {
|
|
min = 0;
|
|
max = 1;
|
|
}
|
|
return {
|
|
...options,
|
|
type,
|
|
series,
|
|
labels,
|
|
count,
|
|
min,
|
|
max,
|
|
unit: String(options.unit || ""),
|
|
t: options.t || ((ru) => ru),
|
|
};
|
|
}
|
|
const x = (index) =>
|
|
["bar", "stacked"].includes(model.type)
|
|
? 12 + ((index + 0.5) * 616) / Math.max(1, model.count)
|
|
: model.count < 2
|
|
? 320
|
|
: 12 + (index / (model.count - 1)) * 616,
|
|
y = (value) => 164 - ((value - model.min) / (model.max - model.min)) * 152;
|
|
function paths() {
|
|
const { type, series, count } = model;
|
|
if (["donut", "gauge"].includes(type)) {
|
|
const radius = 66,
|
|
circumference = 2 * Math.PI * radius;
|
|
let total = series.reduce((sum, item) => sum + (item.values[0] || 0), 0),
|
|
offset = 0;
|
|
const base = `<circle class="chart-ring-track" cx="120" cy="90" r="${radius}" ${type === "gauge" ? `stroke-dasharray="${circumference * 0.75} ${circumference}" transform="rotate(135 120 90)"` : ""}/>`;
|
|
if (type === "gauge") {
|
|
const value = series[0]?.values[0] || 0,
|
|
ratio = Math.max(0, Math.min(1, value / model.max));
|
|
return (
|
|
base +
|
|
`<circle class="chart-ring series-0" cx="120" cy="90" r="${radius}" stroke-dasharray="${ratio * circumference * 0.75} ${circumference}" transform="rotate(135 120 90)" data-chart-slice="0"/>`
|
|
);
|
|
}
|
|
return (
|
|
base +
|
|
series
|
|
.map((item, index) => {
|
|
const length = total
|
|
? ((item.values[0] || 0) / total) * circumference
|
|
: 0,
|
|
result = `<circle class="chart-ring series-${index}" cx="120" cy="90" r="${radius}" stroke-dasharray="${length} ${circumference}" stroke-dashoffset="${-offset}" transform="rotate(-90 120 90)" data-chart-slice="${index}"/>`;
|
|
offset += length;
|
|
return result;
|
|
})
|
|
.join("")
|
|
);
|
|
}
|
|
let output = [12, 88, 164]
|
|
.map(
|
|
(value) =>
|
|
`<line class="chart-grid" x1="0" x2="640" y1="${value}" y2="${value}"/>`,
|
|
)
|
|
.join("");
|
|
if (type === "bar" || type === "stacked") {
|
|
const group = 616 / Math.max(1, count),
|
|
width = Math.max(
|
|
1,
|
|
(group * 0.72) /
|
|
(type === "stacked" ? 1 : Math.max(1, series.length)),
|
|
);
|
|
for (let index = 0; index < count; index++) {
|
|
let sum = 0;
|
|
series.forEach((item, s) => {
|
|
const value = item.values[index];
|
|
if (value == null) return;
|
|
const from = type === "stacked" ? sum : 0,
|
|
to = from + value;
|
|
output += `<rect class="chart-bar series-${s}" x="${12 + index * group + (type === "stacked" ? group * 0.14 : group * 0.14 + s * width)}" y="${Math.min(y(from), y(to))}" width="${width}" height="${Math.abs(y(to) - y(from))}" rx="2"/>`;
|
|
sum += value;
|
|
});
|
|
}
|
|
} else {
|
|
series.forEach((item, s) => {
|
|
const runs = [];
|
|
let run = [];
|
|
item.values.forEach((value, index) => {
|
|
if (value == null) {
|
|
if (run.length) runs.push(run);
|
|
run = [];
|
|
} else run.push([x(index), y(value)]);
|
|
});
|
|
if (run.length) runs.push(run);
|
|
for (const points of runs) {
|
|
if (points.length === 1)
|
|
output += `<circle class="chart-bar series-${s}" cx="${points[0][0]}" cy="${points[0][1]}" r="3"/>`;
|
|
const d = points
|
|
.map(([px, py], index) => `${index ? "L" : "M"}${px},${py}`)
|
|
.join(" ");
|
|
if (type === "area")
|
|
output += `<path class="chart-area series-${s}" d="${d} L${points.at(-1)[0]},${y(0)} L${points[0][0]},${y(0)} Z"/>`;
|
|
output += `<path class="chart-line series-${s}" d="${d}"/>`;
|
|
}
|
|
});
|
|
}
|
|
return (
|
|
output +
|
|
'<line class="chart-crosshair" x1="0" x2="0" y1="0" y2="180" hidden/>'
|
|
);
|
|
}
|
|
function render() {
|
|
active = -1;
|
|
const {
|
|
title = "",
|
|
description = "",
|
|
type,
|
|
series,
|
|
labels,
|
|
t,
|
|
unit,
|
|
count,
|
|
} = model,
|
|
round = ["donut", "gauge"].includes(type),
|
|
empty =
|
|
!count ||
|
|
!series.some((item) => item.values.some((value) => value !== null));
|
|
const total =
|
|
type === "gauge"
|
|
? series[0]?.values[0] || 0
|
|
: series.reduce((sum, item) => sum + (item.values[0] || 0), 0);
|
|
root.dataset.chartType = type;
|
|
root.dataset.chartTone = ["danger", "warning"].includes(model.tone)
|
|
? model.tone
|
|
: "default";
|
|
root.innerHTML = `${title ? `<div class="chart-heading"><h3>${escapeText(title)}</h3>${description ? `<p>${escapeText(description)}</p>` : ""}</div>` : ""}${empty ? `<div class="chart-empty">${t("Нет данных за выбранный период.", "No data for this period.")}</div>` : `<div class="chart-plot ${round ? "chart-round" : ""}" tabindex="0" role="group" aria-label="${escapeText(title)}. ${t("Стрелки для просмотра значений", "Use arrow keys to inspect values")}"><svg viewBox="0 0 ${round ? "240 180" : "640 180"}" preserveAspectRatio="${round ? "xMidYMid meet" : "none"}" aria-hidden="true">${paths()}</svg>${round ? `<div class="chart-center"><strong>${escapeText(format(total, unit))}</strong><span>${type === "gauge" ? t("текущее значение", "current value") : t("всего", "total")}</span></div>` : ""}<div class="chart-tooltip" hidden role="status" aria-live="off"></div></div>${!round && type !== "sparkline" ? `<div class="chart-axis"><span>${escapeText(labels[0])}</span><span>${escapeText(labels[Math.floor((count - 1) / 2)])}</span><span>${escapeText(labels.at(-1))}</span></div><div class="chart-scale">${escapeText(format(model.min, unit))} — ${escapeText(format(model.max, unit))}</div>` : ""}<div class="chart-legend">${series.map((item, index) => `<span><i class="series-${index}" aria-hidden="true"></i>${escapeText(item.name)}</span>`).join("")}</div>${type !== "sparkline" ? `<details class="chart-data"><summary>${t("Числовые данные", "Numerical data")}</summary><div class="table-wrap"><table><thead><tr><th>${round ? t("Показатель", "Metric") : t("Период", "Period")}</th>${round ? `<th>${escapeText(unit || t("Значение", "Value"))}</th>` : series.map((item) => `<th>${escapeText(item.name)}${unit ? ` (${escapeText(unit)})` : ""}</th>`).join("")}</tr></thead><tbody>${round ? series.map((item) => `<tr><th>${escapeText(item.name)}</th><td>${escapeText(format(item.values[0], unit))}</td></tr>`).join("") : labels.map((label, index) => `<tr><th>${escapeText(label)}</th>${series.map((item) => `<td>${escapeText(format(item.values[index], unit))}</td>`).join("")}</tr>`).join("")}</tbody></table></div></details>` : ""}`}`;
|
|
}
|
|
function show(index, keyboard = false) {
|
|
const plot = root.querySelector(".chart-plot"),
|
|
tooltip = root.querySelector(".chart-tooltip");
|
|
if (!plot || !tooltip) return;
|
|
const round = ["donut", "gauge"].includes(model.type),
|
|
size = round ? model.series.length : model.count;
|
|
active = Math.max(0, Math.min(size - 1, index));
|
|
tooltip.replaceChildren();
|
|
const title = document.createElement("strong");
|
|
title.textContent = round
|
|
? model.series[active]?.name
|
|
: model.labels[active];
|
|
tooltip.append(title);
|
|
for (const item of round ? [model.series[active]] : model.series) {
|
|
if (!item) continue;
|
|
const line = document.createElement("span");
|
|
line.textContent =
|
|
(round ? "" : item.name + ": ") +
|
|
format(item.values[round ? 0 : active], model.unit);
|
|
tooltip.append(line);
|
|
}
|
|
tooltip.hidden = false;
|
|
tooltip.setAttribute("aria-live", keyboard ? "polite" : "off");
|
|
const width = plot.clientWidth,
|
|
px = round ? width / 2 : (x(active) / 640) * width;
|
|
tooltip.style.left =
|
|
Math.max(
|
|
6,
|
|
Math.min(px - tooltip.offsetWidth / 2, width - tooltip.offsetWidth - 6),
|
|
) + "px";
|
|
const cross = root.querySelector(".chart-crosshair");
|
|
if (cross) {
|
|
cross.removeAttribute("hidden");
|
|
cross.setAttribute("x1", x(active));
|
|
cross.setAttribute("x2", x(active));
|
|
}
|
|
}
|
|
function hide() {
|
|
root.querySelector(".chart-tooltip")?.setAttribute("hidden", "");
|
|
root.querySelector(".chart-crosshair")?.setAttribute("hidden", "");
|
|
}
|
|
root.addEventListener(
|
|
"pointermove",
|
|
(event) => {
|
|
const plot = event.target.closest(".chart-plot");
|
|
if (!plot) {
|
|
hide();
|
|
return;
|
|
}
|
|
if (["donut", "gauge"].includes(model.type)) {
|
|
const slice = event.target.closest("[data-chart-slice]");
|
|
if (slice) show(Number(slice.dataset.chartSlice));
|
|
else hide();
|
|
} else {
|
|
const ratio =
|
|
(((event.clientX - plot.getBoundingClientRect().left) /
|
|
Math.max(1, plot.clientWidth)) *
|
|
640 -
|
|
12) /
|
|
616;
|
|
show(
|
|
["bar", "stacked"].includes(model.type)
|
|
? Math.floor(ratio * model.count)
|
|
: Math.round(ratio * (model.count - 1)),
|
|
);
|
|
}
|
|
},
|
|
{ signal },
|
|
);
|
|
root.addEventListener(
|
|
"pointerleave",
|
|
() => {
|
|
if (!root.contains(document.activeElement)) hide();
|
|
},
|
|
{ signal },
|
|
);
|
|
root.addEventListener(
|
|
"focusin",
|
|
(event) => {
|
|
if (event.target.matches(".chart-plot")) show(Math.max(0, active), true);
|
|
},
|
|
{ signal },
|
|
);
|
|
root.addEventListener(
|
|
"focusout",
|
|
(event) => {
|
|
if (!root.contains(event.relatedTarget)) hide();
|
|
},
|
|
{ signal },
|
|
);
|
|
root.addEventListener(
|
|
"keydown",
|
|
(event) => {
|
|
if (
|
|
!event.target.matches(".chart-plot") ||
|
|
event.ctrlKey ||
|
|
event.metaKey ||
|
|
event.altKey
|
|
)
|
|
return;
|
|
if (
|
|
["ArrowLeft", "ArrowRight", "Home", "End", "Escape"].includes(event.key)
|
|
) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
if (event.key === "Escape") {
|
|
hide();
|
|
return;
|
|
}
|
|
const size = ["donut", "gauge"].includes(model.type)
|
|
? model.series.length
|
|
: model.count;
|
|
show(
|
|
event.key === "Home"
|
|
? 0
|
|
: event.key === "End"
|
|
? size - 1
|
|
: Math.max(0, active) + (event.key === "ArrowRight" ? 1 : -1),
|
|
true,
|
|
);
|
|
}
|
|
},
|
|
{ signal },
|
|
);
|
|
function update(next) {
|
|
if (disposed) return;
|
|
const candidate = { ...options, ...next };
|
|
model = normalize(candidate);
|
|
options = candidate;
|
|
render();
|
|
}
|
|
update(initial);
|
|
return {
|
|
update,
|
|
dispose() {
|
|
disposed = true;
|
|
abort.abort();
|
|
hide();
|
|
},
|
|
};
|
|
}
|