Sharkey/packages/client/src/components/mini-chart.vue

84 lines
2.1 KiB
Vue
Raw Normal View History

2018-06-11 02:24:29 +00:00
<template>
2018-06-11 03:52:47 +00:00
<svg :viewBox="`0 0 ${ viewBoxX } ${ viewBoxY }`" style="overflow:visible">
2018-06-11 02:24:29 +00:00
<defs>
<linearGradient :id="gradientId" x1="0" x2="0" y1="1" y2="0">
2022-06-24 01:51:45 +00:00
<stop offset="0%" :stop-color="color"></stop>
<stop offset="100%" :stop-color="colorAlpha"></stop>
2018-06-11 02:24:29 +00:00
</linearGradient>
<mask :id="maskId" x="0" y="0" :width="viewBoxX" :height="viewBoxY">
<polygon
:points="polygonPoints"
fill="#fff"
2022-06-21 05:39:23 +00:00
fill-opacity="0.5"
/>
2018-06-11 02:24:29 +00:00
</mask>
</defs>
<rect
2018-06-11 03:52:47 +00:00
x="-10" y="-10"
:width="viewBoxX + 20" :height="viewBoxY + 20"
2022-06-21 05:39:23 +00:00
:style="`stroke: none; fill: url(#${ gradientId }); mask: url(#${ maskId })`"
/>
2022-06-24 01:51:45 +00:00
<polyline
:points="polylinePoints"
fill="none"
:stroke="color"
stroke-width="2"
/>
<circle
:cx="headX"
:cy="headY"
r="3"
:fill="color"
/>
2018-06-11 02:24:29 +00:00
</svg>
</template>
2022-06-21 05:39:23 +00:00
<script lang="ts" setup>
import { onUnmounted, watch } from 'vue';
import { v4 as uuid } from 'uuid';
2022-06-24 01:51:45 +00:00
import tinycolor from 'tinycolor2';
2018-06-11 02:24:29 +00:00
2022-06-21 05:39:23 +00:00
const props = defineProps<{
src: number[];
}>();
const viewBoxX = 50;
const viewBoxY = 50;
const gradientId = uuid();
const maskId = uuid();
let polylinePoints = $ref('');
let polygonPoints = $ref('');
let headX = $ref<number | null>(null);
let headY = $ref<number | null>(null);
let clock = $ref<number | null>(null);
2022-06-24 01:51:45 +00:00
const accent = tinycolor(getComputedStyle(document.documentElement).getPropertyValue('--accent'));
const color = accent.toRgbString();
const colorAlpha = accent.clone().setAlpha(1).toRgbString();
2022-06-21 05:39:23 +00:00
function draw(): void {
const stats = props.src.slice().reverse();
const peak = Math.max.apply(null, stats) || 1;
const _polylinePoints = stats.map((n, i) => [
i * (viewBoxX / (stats.length - 1)),
(1 - (n / peak)) * viewBoxY,
]);
polylinePoints = _polylinePoints.map(xy => `${xy[0]},${xy[1]}`).join(' ');
2018-06-11 17:18:29 +00:00
2022-06-21 05:39:23 +00:00
polygonPoints = `0,${ viewBoxY } ${ polylinePoints } ${ viewBoxX },${ viewBoxY }`;
2018-06-11 02:24:29 +00:00
2022-06-21 05:39:23 +00:00
headX = _polylinePoints[_polylinePoints.length - 1][0];
headY = _polylinePoints[_polylinePoints.length - 1][1];
}
2018-06-11 03:52:47 +00:00
2022-06-21 05:39:23 +00:00
watch(() => props.src, draw, { immediate: true });
2018-06-11 02:24:29 +00:00
2022-06-21 05:39:23 +00:00
// Vueが何故かWatchを発動させない場合があるので
clock = window.setInterval(draw, 1000);
2018-06-11 02:24:29 +00:00
2022-06-21 05:39:23 +00:00
onUnmounted(() => {
window.clearInterval(clock);
2018-06-11 02:24:29 +00:00
});
</script>