import { escapeText } from "./text-runtime.js";
const types = new Set([
"line",
"area",
"bar",
"stacked",
"donut",
"gauge",
"sparkline",
]);
const format = (value, unit = "") =>
value == null
? "—"
: `${new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value)}${unit ? " " + unit : ""}`;
export function mountChart(root, initial) {
const abort = new AbortController(),
{ signal } = abort;
let model,
active = -1,
disposed = false;
root.classList.add("metric-chart");
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 = ``;
if (type === "gauge") {
const value = series[0]?.values[0] || 0,
ratio = Math.max(0, Math.min(1, value / model.max));
return (
base +
``
);
}
return (
base +
series
.map((item, index) => {
const length = total
? ((item.values[0] || 0) / total) * circumference
: 0,
result = ``;
offset += length;
return result;
})
.join("")
);
}
let output = [12, 88, 164]
.map(
(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 += ``;
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) {
const d = points
.map(([px, py], index) => `${index ? "L" : "M"}${px},${py}`)
.join(" ");
if (type === "area")
output += ``;
output += ``;
}
});
}
return (
output +
''
);
}
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 ? `
${escapeText(title)}
${description ? `
${escapeText(description)}
` : ""}
` : ""}${empty ? `${t("Нет данных за выбранный период.", "No data for this period.")}
` : `${round ? `
${escapeText(format(total, unit))}${type === "gauge" ? t("текущее значение", "current value") : t("всего", "total")}
` : ""}
${!round && type !== "sparkline" ? `${escapeText(labels[0])}${escapeText(labels[Math.floor((count - 1) / 2)])}${escapeText(labels.at(-1))}
${escapeText(format(model.min, unit))} — ${escapeText(format(model.max, unit))}
` : ""}${series.map((item, index) => `${escapeText(item.name)}`).join("")}
${type !== "sparkline" ? `${t("Числовые данные", "Numerical data")}
| ${round ? t("Показатель", "Metric") : t("Период", "Period")} | ${round ? `${escapeText(unit || t("Значение", "Value"))} | ` : series.map((item) => `${escapeText(item.name)}${unit ? ` (${escapeText(unit)})` : ""} | `).join("")}
${round ? series.map((item) => `| ${escapeText(item.name)} | ${escapeText(format(item.values[0], unit))} |
`).join("") : labels.map((label, index) => `| ${escapeText(label)} | ${series.map((item) => `${escapeText(format(item.values[index], unit))} | `).join("")}
`).join("")}
` : ""}`}`;
}
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
: (model.count < 2 ? 0.5 : active / (model.count - 1)) * 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) return;
if (["donut", "gauge"].includes(model.type)) {
const slice = event.target.closest("[data-chart-slice]");
if (slice) show(Number(slice.dataset.chartSlice));
} else {
const ratio =
(event.clientX - plot.getBoundingClientRect().left) /
Math.max(1, plot.clientWidth);
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(options) {
if (disposed) return;
model = normalize({ ...model, ...options });
render();
}
update(initial);
return {
update,
dispose() {
disposed = true;
abort.abort();
hide();
},
};
}