Refactor LearningPathDiagram

This commit is contained in:
Daniel Egger 2022-12-07 09:57:01 +01:00
parent 2c17012686
commit 299ff5271d
1 changed files with 369 additions and 357 deletions

View File

@ -1,66 +1,85 @@
<script> <script setup lang="ts">
import colors from "@/colors.json";
import * as d3 from "d3"; import * as d3 from "d3";
import * as _ from "lodash"; import * as _ from "lodash";
import * as log from "loglevel"; import * as log from "loglevel";
// type DiagramType = "horizontal" | "vertical" | "horizontalSmall"; // @ts-ignore
import colors from "@/colors.json";
import { Circle } from "@/services/circle";
import { LearningPath } from "@/services/learningPath";
import type { LearningSequence, Topic } from "@/types";
import { computed, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
export default { type DiagramType = "horizontal" | "vertical" | "horizontalSmall";
props: {
diagramType: { export interface Props {
type: String, diagramType?: DiagramType;
default: "horizontal", postfix?: string;
}, learningPath: LearningPath;
postfix: { }
type: String,
default: "", const props = withDefaults(defineProps<Props>(), {
}, diagramType: "horizontal",
learningPath: { postfix: "",
required: true, });
type: Object,
}, const state = reactive({ width: 1640, height: 384 });
},
data() { const svgId = computed(() => {
return { return `learningpath-diagram-${props.learningPath?.slug}-${props.diagramType}${props.postfix}`;
width: 1640, });
height: 384,
}; const viewBox = computed(() => {
}, return `0 0 ${state.width} ${state.height}`;
computed: { });
svgId() {
return `learningpath-diagram-${this.learningPath.slug}-${this.diagramType}${this.postfix}`; const vueRouter = useRouter();
},
viewBox() { onMounted(async () => {
return `0 0 ${this.width} ${this.height}`; log.debug("CircleDiagram mounted");
}, render();
circles() { });
function someFinished(circle, learningSequence) {
function someFinished(circle: Circle, learningSequence: LearningSequence) {
if (circle) { if (circle) {
return circle.someFinishedInLearningSequence( return circle.someFinishedInLearningSequence(learningSequence.translation_key);
learningSequence.translation_key
);
} }
return false; return false;
} }
function allFinished(circle, learningSequence) { function allFinished(circle: Circle, learningSequence: LearningSequence) {
if (circle) { if (circle) {
return circle.allFinishedInLearningSequence(learningSequence.translation_key); return circle.allFinishedInLearningSequence(learningSequence.translation_key);
} }
return false; return false;
} }
if (this.learningPath) { interface CirclePie extends d3.PieArcDatum<number> {
const internalCircles = []; someFinished: boolean;
this.learningPath.circles.forEach((circle) => { allFinished: boolean;
const pieWeights = new Array( done: boolean;
Math.max(circle.learningSequences.length, 1) }
).fill(1);
interface InternalCircle {
id: number;
title: string;
frontend_url: string;
slug: string;
pieData: CirclePie[];
}
const circles = computed(() => {
if (props.learningPath) {
const internalCircles: InternalCircle[] = [];
props.learningPath.circles.forEach((circle) => {
const pieWeights = new Array(Math.max(circle.learningSequences.length, 1)).fill(
1
);
const pieGenerator = d3.pie(); const pieGenerator = d3.pie();
const pieData = pieGenerator(pieWeights); const pieData = pieGenerator(pieWeights);
pieData.forEach((pie) => { (pieData as CirclePie[]).forEach((pie) => {
const thisLearningSequence = circle.learningSequences[parseInt(pie.index)]; const thisLearningSequence = circle.learningSequences[pie.index];
pie.startAngle = pie.startAngle + Math.PI; pie.startAngle = pie.startAngle + Math.PI;
pie.endAngle = pie.endAngle + Math.PI; pie.endAngle = pie.endAngle + Math.PI;
pie.done = circle.someFinishedInLearningSequence( pie.done = circle.someFinishedInLearningSequence(
@ -69,47 +88,43 @@ export default {
pie.someFinished = someFinished(circle, thisLearningSequence); pie.someFinished = someFinished(circle, thisLearningSequence);
pie.allFinished = allFinished(circle, thisLearningSequence); pie.allFinished = allFinished(circle, thisLearningSequence);
}); });
const newCircle = {}; internalCircles.push({
newCircle.pieData = pieData.reverse(); pieData: pieData.reverse() as CirclePie[],
newCircle.title = circle.title; title: circle.title,
newCircle.frontend_url = circle.frontend_url; frontend_url: circle.frontend_url,
newCircle.id = circle.id; id: circle.id,
newCircle.slug = _.kebabCase(circle.title); slug: _.kebabCase(circle.title),
internalCircles.push(newCircle); });
}); });
return internalCircles; return internalCircles;
} }
return []; return [];
}, });
svg() {
const result = d3.select("#" + this.svgId);
result.selectAll("*").remove();
return result;
},
},
mounted() {
log.debug("LearningPathDiagram mounted");
function render() {
// clean old svg // clean old svg
d3.select("#" + this.svgId) d3.select("#" + svgId.value)
.selectAll("*") .selectAll("*")
.remove(); .remove();
const svgElement = d3.select("#" + svgId.value);
// Clean svg before adding new stuff.
svgElement.selectAll("*").remove();
let circleWidth = 200; let circleWidth = 200;
if (this.diagramType === "vertical") { if (props.diagramType === "vertical") {
circleWidth = 60; circleWidth = 60;
} }
const radius = (circleWidth * 0.8) / 2; const radius = (circleWidth * 0.8) / 2;
if (this.diagramType === "vertical") { if (props.diagramType === "vertical") {
this.width = Math.min(960, window.innerWidth - 32); state.width = Math.min(960, window.innerWidth - 32);
this.height = 860; state.height = 860;
} else { } else {
this.width = circleWidth * this.circles.length; state.width = circleWidth * circles.value.length;
} }
function getColor(d) { function getColor(d: CirclePie) {
let color = colors.gray[300]; let color = colors.gray[300];
if (d.someFinished) { if (d.someFinished) {
color = colors.sky[500]; color = colors.sky[500];
@ -120,7 +135,7 @@ export default {
return color; return color;
} }
function getHoverColor(d) { function getHoverColor(d: CirclePie) {
let color = colors.gray[200]; let color = colors.gray[200];
if (d.someFinished) { if (d.someFinished) {
color = colors.sky[400]; color = colors.sky[400];
@ -131,38 +146,36 @@ export default {
return color; return color;
} }
const vueRouter = this.$router;
// Create append pie charts to the main svg // Create append pie charts to the main svg
const circle_groups = this.svg const circle_groups = svgElement
.selectAll(".circle") .selectAll(".circle")
.data(this.circles) .data(circles.value)
.enter() .enter()
.append("g") .append("g")
.attr("class", "circle") .attr("class", "circle")
.attr("data-cy", (d) => { .attr("data-cy", (d) => {
if (this.diagramType === "vertical") { if (props.diagramType === "vertical") {
return `circle-${d.slug}-vertical`; return `circle-${d.slug}-vertical`;
} else { } else {
return `circle-${d.slug}`; return `circle-${d.slug}`;
} }
}) })
.on("mouseover", function (d, i) { .on("mouseover", function () {
d3.select(this) d3.select(this)
.selectAll(".learningSegmentArc") .selectAll(".learningSegmentArc")
.transition() .transition()
.duration(200) .duration(200)
.attr("fill", (d) => { .attr("fill", (d) => {
return getHoverColor(d); return getHoverColor(d as CirclePie);
}); });
}) })
.on("mouseout", function (d, i) { .on("mouseout", function () {
d3.select(this) d3.select(this)
.selectAll(".learningSegmentArc") .selectAll(".learningSegmentArc")
.transition() .transition()
.duration(200) .duration(200)
.attr("fill", (d) => { .attr("fill", (d) => {
return getColor(d); return getColor(d as CirclePie);
}); });
}) })
.on("click", (d, i) => { .on("click", (d, i) => {
@ -178,11 +191,11 @@ export default {
.outerRadius(radius); .outerRadius(radius);
//Generate groups //Generate groups
const arcs = this.svg const arcs = svgElement
.selectAll("g") .selectAll("g")
.selectAll(".learningSegmentArc") .selectAll(".learningSegmentArc")
.data((d) => { .data((d) => {
return d.pieData; return (d as InternalCircle).pieData;
}) })
.enter() .enter()
.append("g") .append("g")
@ -197,6 +210,7 @@ export default {
}); });
//Draw arc paths //Draw arc paths
// @ts-ignore
arcs.append("path").attr("d", arcGenerator); arcs.append("path").attr("d", arcGenerator);
const circlesText = circle_groups const circlesText = circle_groups
@ -205,7 +219,7 @@ export default {
.style("font-size", "18px") .style("font-size", "18px")
.style("overflow-wrap", "break-word") .style("overflow-wrap", "break-word")
.text((d) => { .text((d) => {
if (this.diagramType === "horizontal") { if (props.diagramType === "horizontal") {
return d.title.replace("Prüfungsvorbereitung", "Prüfungs- vorbereitung"); return d.title.replace("Prüfungsvorbereitung", "Prüfungs- vorbereitung");
} }
return d.title; return d.title;
@ -215,7 +229,7 @@ export default {
const topicHeight = 50; const topicHeight = 50;
const circleHeigth = circleWidth + 20; const circleHeigth = circleWidth + 20;
function getTopicHorizontalPosition(i, d, topics) { function getTopicHorizontalPosition(i: number, _d: unknown, topics: Topic[]) {
let x = 0; let x = 0;
for (let index = 0; index < i; index++) { for (let index = 0; index < i; index++) {
x += circleWidth * topics[index].circles.length; x += circleWidth * topics[index].circles.length;
@ -223,7 +237,7 @@ export default {
return x + 10; return x + 10;
} }
function getTopicVerticalPosition(i, d, topics) { function getTopicVerticalPosition(i: number, _d: unknown, topics: Topic[]) {
let pos = topicHeightOffset; let pos = topicHeightOffset;
for (let index = 0; index < i; index++) { for (let index = 0; index < i; index++) {
@ -236,18 +250,14 @@ export default {
return pos + topicHeightOffset; return pos + topicHeightOffset;
} }
function getCircleVerticalPostion(i, d, topics) { function getCircleVerticalPostion(i: number, d: InternalCircle, topics: Topic[]) {
let y = circleHeigth / 2 + topicHeightOffset + 10; let y = circleHeigth / 2 + topicHeightOffset + 10;
for (let topic_index = 0; topic_index < topics.length; topic_index++) { for (let topic_index = 0; topic_index < topics.length; topic_index++) {
const topic = topics[topic_index]; const topic = topics[topic_index];
if (topic.is_visible) { if (topic.is_visible) {
y += topicHeight; y += topicHeight;
} }
for ( for (let circle_index = 0; circle_index < topic.circles.length; circle_index++) {
let circle_index = 0;
circle_index < topic.circles.length;
circle_index++
) {
const circle = topic.circles[circle_index]; const circle = topic.circles[circle_index];
if (circle.id === d.id) { if (circle.id === d.id) {
return y; return y;
@ -257,9 +267,9 @@ export default {
} }
} }
const topicGroups = this.svg const topicGroups = svgElement
.selectAll(".topic") .selectAll(".topic")
.data(this.learningPath.topics) .data(props.learningPath.topics)
.enter() .enter()
.append("g"); .append("g");
@ -276,7 +286,7 @@ export default {
// Calculate positions of objects // Calculate positions of objects
if (this.diagramType === "vertical") { if (props.diagramType === "vertical") {
const Circles_X = radius; const Circles_X = radius;
const Topics_X = Circles_X - 20; const Topics_X = Circles_X - 20;
@ -285,7 +295,7 @@ export default {
"translate(" + "translate(" +
Circles_X + Circles_X +
"," + "," +
getCircleVerticalPostion(i, d, this.learningPath.topics) + getCircleVerticalPostion(i, d, props.learningPath.topics) +
")" ")"
); );
}); });
@ -301,7 +311,7 @@ export default {
"translate(" + "translate(" +
Topics_X + Topics_X +
", " + ", " +
getTopicVerticalPosition(i, d, this.learningPath.topics) + getTopicVerticalPosition(i, d, props.learningPath.topics) +
")" ")"
); );
}) })
@ -309,7 +319,7 @@ export default {
return "topic ".concat(d.is_visible ? "block" : "hidden"); return "topic ".concat(d.is_visible ? "block" : "hidden");
}); });
topicLines.transition().duration("1000").attr("x2", this.width); topicLines.transition().duration(1000).attr("x2", state.width);
topicTitles.attr("y", 30); topicTitles.attr("y", 30);
} else { } else {
@ -324,7 +334,7 @@ export default {
.call(wrap, circleWidth - 20) .call(wrap, circleWidth - 20)
.attr("class", () => { .attr("class", () => {
let classes = "circlesText text-xl font-bold hidden"; let classes = "circlesText text-xl font-bold hidden";
if (this.diagramType === "horizontal") { if (props.diagramType === "horizontal") {
classes += " lg:block"; classes += " lg:block";
} }
return classes; return classes;
@ -334,13 +344,13 @@ export default {
.attr("transform", (d, i) => { .attr("transform", (d, i) => {
return ( return (
"translate(" + "translate(" +
getTopicHorizontalPosition(i, d, this.learningPath.topics) + getTopicHorizontalPosition(i, d, props.learningPath.topics) +
",0)" ",0)"
); );
}) })
.attr("class", (d) => { .attr("class", (d) => {
let classes = "topic hidden"; let classes = "topic hidden";
if (this.diagramType === "horizontal" && d.is_visible) { if (props.diagramType === "horizontal" && d.is_visible) {
classes += " lg:block"; classes += " lg:block";
} }
return classes; return classes;
@ -352,7 +362,7 @@ export default {
.attr("x2", -10) .attr("x2", -10)
.attr("y2", 0) .attr("y2", 0)
.transition() .transition()
.duration("1000") .duration(1000)
.attr("y2", 350); .attr("y2", 350);
topicTitles topicTitles
@ -362,12 +372,14 @@ export default {
.attr("class", "topic-title font-bold"); .attr("class", "topic-title font-bold");
} }
function wrap(text, width) { // @ts-ignore
text.each(function () { function wrap(texts, width: number) {
texts.each(function () {
// @ts-ignore
let text = d3.select(this), let text = d3.select(this),
words = text.text().split(/\s+/).reverse(), words = text.text().split(/\s+/).reverse(),
word, word,
line = [], lines: string[] = [],
lineNumber = 0, lineNumber = 0,
lineHeight = 1.1, // ems lineHeight = 1.1, // ems
y = text.attr("y"), y = text.attr("y"),
@ -379,12 +391,13 @@ export default {
.attr("y", y) .attr("y", y)
.attr("dy", dy + "em"); .attr("dy", dy + "em");
while ((word = words.pop())) { while ((word = words.pop())) {
line.push(word); lines.push(word);
tspan.text(line.join(" ")); tspan.text(lines.join(" "));
// @ts-ignore
if (tspan.node().getComputedTextLength() > width) { if (tspan.node().getComputedTextLength() > width) {
line.pop(); lines.pop();
tspan.text(line.join(" ")); tspan.text(lines.join(" "));
line = [word]; lines = [word];
tspan = text tspan = text
.append("tspan") .append("tspan")
@ -396,8 +409,7 @@ export default {
} }
}); });
} }
}, }
};
</script> </script>
<template> <template>