Split activity graph into component & typed

This commit is contained in:
2022-08-08 18:44:07 +02:00
parent 96c412ca49
commit dc69b4086c
5 changed files with 399 additions and 314 deletions

View File

@@ -444,8 +444,8 @@ const unlinkPlexAccount = () => {
// - - - User graphs - - - // - - - User graphs - - -
const fetchChart = (urlPath, days, chartType) => { const fetchGraphData = (urlPath, days, chartType) => {
const url = new URL("/api/v1/user" + urlPath, SEASONED_URL); const url = new URL("/api/v1/user/" + urlPath, SEASONED_URL);
url.searchParams.append("days", days); url.searchParams.append("days", days);
url.searchParams.append("y_axis", chartType); url.searchParams.append("y_axis", chartType);
@@ -544,7 +544,7 @@ export {
logout, logout,
getSettings, getSettings,
updateSettings, updateSettings,
fetchChart, fetchGraphData,
getEmoji, getEmoji,
elasticSearchMoviesAndShows elasticSearchMoviesAndShows
}; };

191
src/components/Graph.vue Normal file
View File

@@ -0,0 +1,191 @@
<template>
<canvas ref="graphCanvas"></canvas>
</template>
<script setup lang="ts">
import { ref, computed, defineProps, onMounted, watch } from "vue";
import Chart from "chart.js";
import type { Ref } from "vue";
enum GraphValueTypes {
Number = "number",
Time = "time"
}
interface IGraphDataset {
name: string;
data: Array<number>;
}
interface IGraphData {
labels: Array<string>;
series: Array<IGraphDataset>;
}
interface Props {
name?: string;
data: IGraphData;
type: string; // TODO import types from chart.js
stacked: boolean;
datasetDescriptionSuffix: string;
tooltipDescriptionSuffix: string;
graphValueType?: GraphValueTypes;
}
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hitRadius = 10;
Chart.defaults.global.elements.point.pointHoverRadius = 10;
Chart.defaults.global.elements.point.hoverBorderWidth = 4;
const props = defineProps<Props>();
const graphInstance: Ref<any> = ref(null);
const graphCanvas: Ref<HTMLCanvasElement> = ref(null);
onMounted(() => generateGraph());
watch(() => props.data, generateGraph);
const graphTemplates = [
{
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 1
},
{
backgroundColor: "rgba(255, 159, 64, 0.2)",
borderColor: "rgba(255, 159, 64, 1)",
borderWidth: 1
},
{
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "rgba(255, 99, 132, 1)",
borderWidth: 1
}
];
const gridColor = getComputedStyle(document.documentElement).getPropertyValue(
"--text-color-5"
);
function hydrateGraphLineOptions(dataset: IGraphDataset, index: number) {
return {
label: `${dataset.name} ${props.datasetDescriptionSuffix}`,
data: dataset.data,
...graphTemplates[index]
};
}
function removeEmptyDataset(dataset: IGraphDataset) {
return dataset.data.every(point => point === 0) ? false : true;
}
function generateGraph() {
const datasets = props.data.series
.filter(removeEmptyDataset)
.map(hydrateGraphLineOptions);
const graphOptions = {
maintainAspectRatio: false,
tooltips: {
callbacks: {
title: (tooltipItem, data) => `Watch date: ${tooltipItem[0].label}`,
label: (tooltipItem, data) => {
let label = data.datasets[tooltipItem.datasetIndex].label;
let value = tooltipItem.value;
const context = label.split(" ")[0];
const text = `${context} ${props.tooltipDescriptionSuffix}`;
if (props.graphValueType === GraphValueTypes.Time) {
value = convertSecondsToHumanReadable(value);
}
return ` ${text}: ${value}`;
}
}
},
scales: {
yAxes: [
{
gridLines: {
color: gridColor
},
stacked: props.stacked,
ticks: {
// suggestedMax: 10000,
callback: (value, index, values) => {
if (props.graphValueType === GraphValueTypes.Time) {
return convertSecondsToHumanReadable(value, values);
}
return value;
},
beginAtZero: true
}
}
],
xAxes: [
{
stacked: props.stacked,
gridLines: {
display: false
}
}
]
}
};
const chartData = {
labels: props.data.labels,
datasets
};
if (graphInstance.value) {
graphInstance.value.clear();
graphInstance.value.data = chartData;
graphInstance.value.update();
return;
}
graphInstance.value = new Chart(graphCanvas.value, {
type: props.type,
data: chartData,
options: graphOptions
});
}
function convertSecondsToHumanReadable(value, values = null) {
const highestValue = values ? values[0] : value;
// minutes
if (highestValue < 3600) {
const minutes = Math.floor(value / 60);
value = `${minutes} m`;
}
// hours and minutes
else if (highestValue > 3600 && highestValue < 86400) {
const hours = Math.floor(value / 3600);
const minutes = Math.floor((value % 3600) / 60);
value = hours != 0 ? `${hours} h ${minutes} m` : `${minutes} m`;
}
// days and hours
else if (highestValue > 86400 && highestValue < 31557600) {
const days = Math.floor(value / 86400);
const hours = Math.floor((value % 86400) / 3600);
value = days != 0 ? `${days} d ${hours} h` : `${hours} h`;
}
// years and days
else if (highestValue > 31557600) {
const years = Math.floor(value / 31557600);
const days = Math.floor((value % 31557600) / 86400);
value = years != 0 ? `${years} y ${days} d` : `${days} d`;
}
return value;
}
</script>
<style lang="scss" scoped></style>

View File

@@ -5,13 +5,17 @@
width="24" width="24"
height="24" height="24"
viewBox="0 0 24 24" viewBox="0 0 24 24"
fill="none"
stroke="currentColor" stroke="currentColor"
stroke-width="2" stroke-width="2"
stroke-linecap="round" stroke-linecap="round"
stroke-linejoin="round" stroke-linejoin="round"
style="transition: stroke-width 0.5s ease"
> >
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline> <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline>
</svg> </svg>
</template> </template>
<style lang="scss" scoped>
svg {
fill: none !important;
}
</style>

View File

@@ -10,7 +10,6 @@
stroke-width="2" stroke-width="2"
stroke-linecap="round" stroke-linecap="round"
stroke-linejoin="round" stroke-linejoin="round"
style="transition: stroke-width 0.5s ease"
> >
<line x1="4" y1="21" x2="4" y2="14"></line> <line x1="4" y1="21" x2="4" y2="14"></line>
<line x1="4" y1="10" x2="4" y2="3"></line> <line x1="4" y1="10" x2="4" y2="3"></line>

View File

@@ -12,6 +12,7 @@
type="number" type="number"
pattern="[0-9]*" pattern="[0-9]*"
:style="{ maxWidth: `${3 + 0.5 * days.length}rem` }" :style="{ maxWidth: `${3 + 0.5 * days.length}rem` }"
@change="fetchChartData"
/> />
</label> </label>
@@ -19,348 +20,238 @@
<span>Data sorted by:</span> <span>Data sorted by:</span>
<toggle-button <toggle-button
class="filter-item" class="filter-item"
:options="chartTypes" :options="[GraphTypes.Plays, GraphTypes.Duration]"
:selected.sync="selectedChartDataType" v-model:selected="graphViewMode"
@change="fetchChartData"
/> />
</label> </label>
</div> </div>
<div class="chart-section"> <div class="chart-section">
<h3 class="chart-header">Activity per day:</h3> <h3 class="chart-header">Activity per day:</h3>
<div class="chart"> <div class="graph">
<canvas ref="activityCanvas"></canvas> <Graph
v-if="playsByDayData"
:data="playsByDayData"
type="line"
:stacked="false"
:datasetDescriptionSuffix="`watch last ${days} days`"
:tooltipDescriptionSuffix="selectedGraphViewMode.tooltipLabel"
:graphValueType="selectedGraphViewMode.valueType"
/>
</div> </div>
<h3 class="chart-header">Activity per day of week:</h3> <h3 class="chart-header">Activity per day of week:</h3>
<div class="chart"> <div class="graph">
<canvas ref="playsByDayOfWeekCanvas"></canvas> <Graph
v-if="playsByDayofweekData"
class="graph"
:data="playsByDayofweekData"
type="bar"
:stacked="true"
:datasetDescriptionSuffix="`watch last ${days} days`"
:tooltipDescriptionSuffix="selectedGraphViewMode.tooltipLabel"
:graphValueType="selectedGraphViewMode.valueType"
/>
</div> </div>
</div> </div>
</div> </div>
<div v-else> <div v-else class="not-authenticated">
<h1>Must be authenticated</h1> <h1><IconStop /> Must be authenticated</h1>
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { mapGetters } from "vuex"; import { ref, computed, onMounted } from "vue";
import ToggleButton from "@/components/ui/ToggleButton"; import Chart from "chart.js";
import { fetchChart } from "@/api"; import { useStore } from "vuex";
var Chart = require("chart.js"); import Graph from "@/components/Graph.vue";
Chart.defaults.global.elements.point.radius = 0; import ToggleButton from "@/components/ui/ToggleButton.vue";
Chart.defaults.global.elements.point.hitRadius = 10; import IconStop from "@/icons/IconStop.vue";
Chart.defaults.global.elements.point.pointHoverRadius = 10; import { fetchGraphData } from "../api";
Chart.defaults.global.elements.point.hoverBorderWidth = 4; import type { Ref } from "vue";
import type { ChartType } from "chart.js";
export default { enum GraphTypes {
components: { ToggleButton }, Plays = "plays",
data() { Duration = "duration"
return { }
days: 30,
selectedChartDataType: "plays", enum GraphValueTypes {
charts: [ Number = "number",
{ Time = "time"
name: "Watch activity", }
ref: "activityCanvas",
data: null, const store = useStore();
urlPath: "/plays_by_day",
graphType: "line" const days: Ref<number> = ref(30);
}, const graphViewMode: Ref<GraphTypes> = ref(GraphTypes.Plays);
{ const plexId = computed(() => store.getters["user/plexId"]);
name: "Plays by day of week",
ref: "playsByDayOfWeekCanvas", const selectedGraphViewMode = computed(() =>
data: null, graphValueViewMode.find(viewMode => viewMode.type === graphViewMode.value)
urlPath: "/plays_by_dayofweek", );
graphType: "bar" const graphValueViewMode = [
} {
], type: GraphTypes.Plays,
chartData: [ tooltipLabel: "play count",
{ valueType: GraphValueTypes.Number
type: "plays", },
tooltipLabel: "Play count" {
}, type: GraphTypes.Duration,
{ tooltipLabel: "watched duration",
type: "duration", valueType: GraphValueTypes.Time
tooltipLabel: "Watched duration", }
valueConvertFunction: this.convertSecondsToHumanReadable ];
}
], const playsByDayData: Ref<any> = ref(null);
gridColor: getComputedStyle(document.documentElement).getPropertyValue( const playsByDayofweekData: Ref<any> = ref(null);
"--text-color-5" fetchChartData();
)
}; function fetchChartData() {
}, fetchPlaysByDay();
computed: { fetchPlaysByDayOfWeek();
...mapGetters("user", ["plexId"]), }
chartTypes() {
return this.chartData.map(chart => chart.type); async function fetchPlaysByDay() {
}, playsByDayData.value = await fetchGraphData(
selectedChartType() { "plays_by_day",
return this.chartData.filter( days.value,
data => data.type == this.selectedChartDataType graphViewMode.value
)[0]; ).then(data => convertDateLabels(data?.data));
} }
},
watch: { async function fetchPlaysByDayOfWeek() {
days(newValue) { playsByDayofweekData.value = await fetchGraphData(
if (newValue !== "") { "plays_by_dayofweek",
this.fetchChartData(this.charts); days.value,
} graphViewMode.value
}, ).then(data => convertDateLabels(data?.data));
selectedChartDataType(selectedChartDataType) { }
this.fetchChartData(this.charts);
}, function convertDateLabels(data) {
plexId(newValue) { return {
if (newValue) return this.fetchChartData(this.charts); labels: data.categories.map(convertDateStringToDayMonth),
} series: data.series
}, };
beforeMount() { }
if (typeof this.days == "number") {
this.days = this.days.toString(); function convertDateStringToDayMonth(date: string): string {
} if (!date.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)) {
}, return date;
methods: { }
fetchChartData(charts) {
if (!this.plexId) { const [year, month, day] = date.split("-");
console.log("NF plexID:", this.plexId); return `${day}.${month}`;
return;
}
for (let chart of charts) {
fetchChart(chart.urlPath, this.days, this.selectedChartType.type).then(
data => {
this.series = data.data.series.filter(
group => group.name === "TV"
)[0].data; // plays pr date in groups (movie/tv/music)
this.categories = data.data.categories; // dates
const x_labels = data.data.categories.map(date => {
if (date.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)) {
const [year, month, day] = date.split("-");
return `${day}.${month}`;
}
return date;
});
let y_activityMovies = data.data.series.filter(
group => group.name === "Movies"
)[0].data;
let y_activityTV = data.data.series.filter(
group => group.name === "TV"
)[0].data;
const datasets = [
{
label: `Movies watch last ${this.days} days`,
data: y_activityMovies,
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 1
},
{
label: `Shows watch last ${this.days} days`,
data: y_activityTV,
backgroundColor: "rgba(255, 159, 64, 0.2)",
borderColor: "rgba(255, 159, 64, 1)",
borderWidth: 1
}
];
if (chart.data == null) {
this.generateChart(chart, x_labels, datasets);
} else {
chart.data.clear();
chart.data.data.labels = x_labels;
chart.data.data.datasets = datasets;
chart.data.update();
}
}
);
}
},
generateChart(chart, labels, datasets) {
const chartInstance = new Chart(this.$refs[chart.ref], {
type: chart.graphType,
data: {
labels: labels,
datasets: datasets
},
options: {
// hitRadius: 8,
maintainAspectRatio: false,
tooltips: {
callbacks: {
title: (tooltipItem, data) =>
`Watch date: ${tooltipItem[0].label}`,
label: (tooltipItem, data) => {
let label = data.datasets[tooltipItem.datasetIndex].label;
let value = tooltipItem.value;
let text = "Duration watched";
const context = label.split(" ")[0];
if (context) {
text = `${context} ${this.selectedChartType.tooltipLabel.toLowerCase()}`;
}
if (this.selectedChartType.valueConvertFunction) {
value = this.selectedChartType.valueConvertFunction(
tooltipItem.value
);
}
return ` ${text}: ${value}`;
}
}
},
scales: {
yAxes: [
{
gridLines: {
color: this.gridColor
},
stacked: chart.graphType === "bar",
ticks: {
// suggestedMax: 10000,
callback: (value, index, values) => {
if (this.selectedChartType.valueConvertFunction) {
return this.selectedChartType.valueConvertFunction(
value,
values
);
}
return value;
},
beginAtZero: true
}
}
],
xAxes: [
{
stacked: chart.graphType === "bar",
gridLines: {
display: false
}
}
]
}
}
});
chart.data = chartInstance;
},
convertSecondsToHumanReadable(value, values = null) {
const highestValue = values ? values[0] : value;
// minutes
if (highestValue < 3600) {
const minutes = Math.floor(value / 60);
value = `${minutes} m`;
}
// hours and minutes
else if (highestValue > 3600 && highestValue < 86400) {
const hours = Math.floor(value / 3600);
const minutes = Math.floor((value % 3600) / 60);
value = hours != 0 ? `${hours} h ${minutes} m` : `${minutes} m`;
}
// days and hours
else if (highestValue > 86400 && highestValue < 31557600) {
const days = Math.floor(value / 86400);
const hours = Math.floor((value % 86400) / 3600);
value = days != 0 ? `${days} d ${hours} h` : `${hours} h`;
}
// years and days
else if (highestValue > 31557600) {
const years = Math.floor(value / 31557600);
const days = Math.floor((value % 31557600) / 86400);
value = years != 0 ? `${years} y ${days} d` : `${days} d`;
}
return value;
}
} }
};
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@import "src/scss/variables"; @import "src/scss/variables";
.wrapper { .wrapper {
padding: 2rem; padding: 2rem;
@include mobile-only { @include mobile-only {
padding: 0 0.8rem; padding: 0 0.8rem;
} }
}
.filter {
margin-top: 0.5rem;
display: inline-flex;
flex-direction: column;
font-size: 1.2rem;
&:not(:first-of-type) {
margin-left: 1.25rem;
} }
input { .filter {
width: 100%; margin-top: 0.5rem;
font-size: inherit; display: inline-flex;
max-width: 3rem; flex-direction: column;
background-color: $background-ui; font-size: 1.2rem;
color: $text-color;
&:not(:first-of-type) {
margin-left: 1.25rem;
}
input {
width: 100%;
font-size: inherit;
max-width: 3rem;
background-color: $background-ui;
color: $text-color;
}
span {
font-size: inherit;
line-height: 1;
margin: 0.5rem 0;
font-weight: 300;
}
} }
span { // .filter {
font-size: inherit; // display: flex;
line-height: 1; // flex-direction: row;
margin: 0.5rem 0; // flex-wrap: wrap;
font-weight: 300; // align-items: center;
} // margin-bottom: 2rem;
}
// .filter { // h2 {
// display: flex; // margin-bottom: 0.5rem;
// flex-direction: row; // width: 100%;
// flex-wrap: wrap; // font-weight: 400;
// align-items: center; // }
// margin-bottom: 2rem;
// h2 { // &-item:not(:first-of-type) {
// margin-bottom: 0.5rem; // margin-left: 1rem;
// width: 100%; // }
// font-weight: 400;
// }
// &-item:not(:first-of-type) { // .dayinput {
// margin-left: 1rem; // font-size: 1.2rem;
// } // max-width: 3rem;
// background-color: $background-ui;
// color: $text-color;
// }
// }
// .dayinput { .chart-section {
// font-size: 1.2rem; display: flex;
// max-width: 3rem; flex-wrap: wrap;
// background-color: $background-ui;
// color: $text-color;
// }
// }
.chart-section { .graph {
display: flex; position: relative;
flex-wrap: wrap; height: 35vh;
width: 90vw;
margin-bottom: 2rem;
}
.chart { .chart-header {
position: relative; font-weight: 300;
height: 35vh; }
width: 90vw;
margin-bottom: 2rem;
} }
.chart-header { .not-authenticated {
font-weight: 300; padding: 2rem;
h1 {
display: flex;
align-items: center;
font-size: 3rem;
svg {
margin-right: 1rem;
height: 3rem;
width: 3rem;
}
}
@include mobile {
padding: 1rem;
padding-right: 0;
h1 {
font-size: 1.65rem;
svg {
margin-right: 1rem;
height: 2rem;
width: 2rem;
}
}
}
} }
}
</style> </style>