@magic-circle/performance
Version:
Magic Circle performance management
78 lines (77 loc) • 3.28 kB
JSX
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
import { useEffect, useLayoutEffect, useRef } from 'react';
import styled from 'styled-components';
import { COLORS } from '@magic-circle/styles';
var Canvas = styled.canvas(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n width: 100%;\n height: 50px;\n border-bottom: 1px solid ", ";\n"], ["\n width: 100%;\n height: 50px;\n border-bottom: 1px solid ", ";\n"])), COLORS.shades.s300.css);
var ChartViz = /** @class */ (function () {
function ChartViz(canvas, max) {
this.values = [];
this.canvas = canvas;
this.PR = Math.round(window.devicePixelRatio || 1);
this.width = this.canvas.offsetWidth * this.PR;
this.height = this.canvas.offsetHeight * this.PR;
this.barWidth = 3 * this.PR;
this.canvas.width = this.width;
this.canvas.height = this.height;
this.canvas.style.width = String(this.canvas.width / this.PR);
this.canvas.style.height = String(this.canvas.height / this.PR);
var context = this.canvas.getContext('2d');
if (!context)
throw new Error('Canvas context could not be created');
this.context = context;
this.max = max;
}
ChartViz.prototype.set = function (values) {
this.values = values;
this.render();
};
ChartViz.prototype.render = function () {
var _a = this, values = _a.values, max = _a.max;
var context = this.canvas.getContext('2d');
if (context && !this.context)
this.context = context;
// Clear all drawed elements
this.context.clearRect(0, 0, this.width, this.height);
// Add bars
for (var i = values.length; i > 0; i -= 1) {
var value = values[i];
var height = (value / max) * this.height;
var x = this.width - (values.length - i) * this.barWidth;
if (value >= 0) {
// top bar
this.context.fillStyle = String(COLORS.accent.opacity(0.2));
this.context.fillRect(x, this.height - height, this.barWidth, height);
// performance bar
this.context.fillStyle = COLORS.accent.css;
this.context.fillRect(x, this.height - height, this.barWidth, 2 * this.PR);
}
// else if (value === 'restart' && values.length > 1) {
// const rWidth = this.PR;
// this.context.fillStyle = '#555';
// this.context.fillRect(x + rWidth, 0, 1 * rWidth, this.height);
// }
}
};
return ChartViz;
}());
var Chart = function (_a) {
var max = _a.max, values = _a.values;
var ref = useRef(null);
var viz = useRef();
useLayoutEffect(function () {
if (ref.current) {
viz.current = new ChartViz(ref.current, max);
}
}, [max]);
useEffect(function () {
if (viz.current) {
viz.current.set(values);
}
}, [values]);
return <Canvas ref={ref}/>;
};
export default Chart;
var templateObject_1;