philomena/assets/js/graph.ts

75 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-05-31 20:07:00 +02:00
/**
* Graph Logic
*
* Scales graphs, makes graphs resizable, and stuff like that
*/
import { $, $$ } from './utils/dom';
2024-06-03 23:07:10 +02:00
function setGraphWidth(el: SVGSVGElement, width: number) {
el.viewBox.baseVal.width = Math.max(width, 0);
const graph: SVGPathElement | null = $<SVGPathElement>('#js-graph', el);
if (graph) {
graph.style.transform = `scaleX(${Math.max(width, 0) / 375})`;
}
}
function graphSlice(el: SVGSVGElement, width: number, offset: number) {
setGraphWidth(el, width);
el.viewBox.baseVal.x = Math.max(offset, 0);
}
2024-05-31 20:07:00 +02:00
function resizeGraphs() {
2024-07-03 22:54:14 +02:00
$$<SVGSVGElement>('#js-graph-svg').forEach((el) => {
2024-05-31 20:07:00 +02:00
const parent: HTMLElement | null = el.parentElement;
if (parent) {
2024-06-03 23:07:10 +02:00
setGraphWidth(el, parent.clientWidth);
}
});
}
2024-05-31 20:07:00 +02:00
2024-06-03 23:07:10 +02:00
function scaleGraph(target: HTMLElement, min: number, max: number) {
const targetSvg = $<SVGSVGElement>('#js-graph-svg', target);
2024-05-31 20:07:00 +02:00
2024-07-03 22:54:14 +02:00
if (!targetSvg) return;
2024-06-03 23:07:10 +02:00
const cw = target.clientWidth;
const diff = 100 - (max - min);
const targetWidth = cw + cw * (diff / 100);
const targetOffset = targetWidth * (min / 100);
targetSvg.style.minWidth = `${targetWidth}px`;
graphSlice(targetSvg, targetWidth, targetOffset);
}
function setupSliders() {
2024-07-03 22:54:14 +02:00
$$<HTMLInputElement>('#js-graph-slider').forEach((el) => {
2024-06-03 23:07:10 +02:00
const targetId = el.getAttribute('data-target');
2024-07-03 22:54:14 +02:00
if (!targetId) return;
2024-06-03 23:07:10 +02:00
const target = $<HTMLElement>(targetId);
2024-07-03 22:54:14 +02:00
if (!target) return;
2024-06-03 23:07:10 +02:00
el.addEventListener('input', () => {
const min = Number(el.getAttribute('valuemin') || '0');
const max = Number(el.getAttribute('valuemax') || '0');
scaleGraph(target, min, max);
});
2024-05-31 20:07:00 +02:00
});
}
function sizeGraphs() {
resizeGraphs();
2024-06-03 23:07:10 +02:00
setupSliders();
2024-05-31 20:07:00 +02:00
window.addEventListener('resize', resizeGraphs);
}
export { sizeGraphs };