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,403 +1,415 @@
<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) {
if (circle) { function someFinished(circle: Circle, learningSequence: LearningSequence) {
return circle.someFinishedInLearningSequence( if (circle) {
learningSequence.translation_key return circle.someFinishedInLearningSequence(learningSequence.translation_key);
); }
} return false;
return false; }
function allFinished(circle: Circle, learningSequence: LearningSequence) {
if (circle) {
return circle.allFinishedInLearningSequence(learningSequence.translation_key);
}
return false;
}
interface CirclePie extends d3.PieArcDatum<number> {
someFinished: boolean;
allFinished: boolean;
done: boolean;
}
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 pieData = pieGenerator(pieWeights);
(pieData as CirclePie[]).forEach((pie) => {
const thisLearningSequence = circle.learningSequences[pie.index];
pie.startAngle = pie.startAngle + Math.PI;
pie.endAngle = pie.endAngle + Math.PI;
pie.done = circle.someFinishedInLearningSequence(
thisLearningSequence.translation_key
);
pie.someFinished = someFinished(circle, thisLearningSequence);
pie.allFinished = allFinished(circle, thisLearningSequence);
});
internalCircles.push({
pieData: pieData.reverse() as CirclePie[],
title: circle.title,
frontend_url: circle.frontend_url,
id: circle.id,
slug: _.kebabCase(circle.title),
});
});
return internalCircles;
}
return [];
});
function render() {
// clean old svg
d3.select("#" + svgId.value)
.selectAll("*")
.remove();
const svgElement = d3.select("#" + svgId.value);
// Clean svg before adding new stuff.
svgElement.selectAll("*").remove();
let circleWidth = 200;
if (props.diagramType === "vertical") {
circleWidth = 60;
}
const radius = (circleWidth * 0.8) / 2;
if (props.diagramType === "vertical") {
state.width = Math.min(960, window.innerWidth - 32);
state.height = 860;
} else {
state.width = circleWidth * circles.value.length;
}
function getColor(d: CirclePie) {
let color = colors.gray[300];
if (d.someFinished) {
color = colors.sky[500];
}
if (d.allFinished) {
color = colors.green[500];
}
return color;
}
function getHoverColor(d: CirclePie) {
let color = colors.gray[200];
if (d.someFinished) {
color = colors.sky[400];
}
if (d.allFinished) {
color = colors.green[400];
}
return color;
}
// Create append pie charts to the main svg
const circle_groups = svgElement
.selectAll(".circle")
.data(circles.value)
.enter()
.append("g")
.attr("class", "circle")
.attr("data-cy", (d) => {
if (props.diagramType === "vertical") {
return `circle-${d.slug}-vertical`;
} else {
return `circle-${d.slug}`;
} }
})
function allFinished(circle, learningSequence) { .on("mouseover", function () {
if (circle) { d3.select(this)
return circle.allFinishedInLearningSequence(learningSequence.translation_key); .selectAll(".learningSegmentArc")
} .transition()
return false; .duration(200)
} .attr("fill", (d) => {
return getHoverColor(d as CirclePie);
if (this.learningPath) {
const internalCircles = [];
this.learningPath.circles.forEach((circle) => {
const pieWeights = new Array(
Math.max(circle.learningSequences.length, 1)
).fill(1);
const pieGenerator = d3.pie();
const pieData = pieGenerator(pieWeights);
pieData.forEach((pie) => {
const thisLearningSequence = circle.learningSequences[parseInt(pie.index)];
pie.startAngle = pie.startAngle + Math.PI;
pie.endAngle = pie.endAngle + Math.PI;
pie.done = circle.someFinishedInLearningSequence(
thisLearningSequence.translation_key
);
pie.someFinished = someFinished(circle, thisLearningSequence);
pie.allFinished = allFinished(circle, thisLearningSequence);
});
const newCircle = {};
newCircle.pieData = pieData.reverse();
newCircle.title = circle.title;
newCircle.frontend_url = circle.frontend_url;
newCircle.id = circle.id;
newCircle.slug = _.kebabCase(circle.title);
internalCircles.push(newCircle);
}); });
return internalCircles; })
.on("mouseout", function () {
d3.select(this)
.selectAll(".learningSegmentArc")
.transition()
.duration(200)
.attr("fill", (d) => {
return getColor(d as CirclePie);
});
})
.on("click", (d, i) => {
vueRouter.push(i.frontend_url);
})
.attr("role", "button");
const arcGenerator = d3
.arc()
.innerRadius(radius / 2)
.padAngle(12 / 360)
.outerRadius(radius);
//Generate groups
const arcs = svgElement
.selectAll("g")
.selectAll(".learningSegmentArc")
.data((d) => {
return (d as InternalCircle).pieData;
})
.enter()
.append("g")
.attr("class", "learningSegmentArc")
.attr("fill", colors.gray[300]);
arcs
.transition()
.duration(1000)
.attr("fill", (d) => {
return getColor(d);
});
//Draw arc paths
// @ts-ignore
arcs.append("path").attr("d", arcGenerator);
const circlesText = circle_groups
.append("text")
.attr("fill", colors.blue[900])
.style("font-size", "18px")
.style("overflow-wrap", "break-word")
.text((d) => {
if (props.diagramType === "horizontal") {
return d.title.replace("Prüfungsvorbereitung", "Prüfungs- vorbereitung");
} }
return []; return d.title;
}, });
svg() {
const result = d3.select("#" + this.svgId);
result.selectAll("*").remove();
return result;
},
},
mounted() { const topicHeightOffset = 20;
log.debug("LearningPathDiagram mounted"); const topicHeight = 50;
const circleHeigth = circleWidth + 20;
// clean old svg function getTopicHorizontalPosition(i: number, _d: unknown, topics: Topic[]) {
d3.select("#" + this.svgId) let x = 0;
.selectAll("*") for (let index = 0; index < i; index++) {
.remove(); x += circleWidth * topics[index].circles.length;
let circleWidth = 200;
if (this.diagramType === "vertical") {
circleWidth = 60;
} }
const radius = (circleWidth * 0.8) / 2; return x + 10;
}
if (this.diagramType === "vertical") { function getTopicVerticalPosition(i: number, _d: unknown, topics: Topic[]) {
this.width = Math.min(960, window.innerWidth - 32); let pos = topicHeightOffset;
this.height = 860;
} else { for (let index = 0; index < i; index++) {
this.width = circleWidth * this.circles.length; const topic = topics[index];
if (topic.is_visible) {
pos += topicHeight;
}
pos += circleHeigth * topic.circles.length;
} }
return pos + topicHeightOffset;
}
function getColor(d) { function getCircleVerticalPostion(i: number, d: InternalCircle, topics: Topic[]) {
let color = colors.gray[300]; let y = circleHeigth / 2 + topicHeightOffset + 10;
if (d.someFinished) { for (let topic_index = 0; topic_index < topics.length; topic_index++) {
color = colors.sky[500]; const topic = topics[topic_index];
if (topic.is_visible) {
y += topicHeight;
} }
if (d.allFinished) { for (let circle_index = 0; circle_index < topic.circles.length; circle_index++) {
color = colors.green[500]; const circle = topic.circles[circle_index];
} if (circle.id === d.id) {
return color; return y;
}
function getHoverColor(d) {
let color = colors.gray[200];
if (d.someFinished) {
color = colors.sky[400];
}
if (d.allFinished) {
color = colors.green[400];
}
return color;
}
const vueRouter = this.$router;
// Create append pie charts to the main svg
const circle_groups = this.svg
.selectAll(".circle")
.data(this.circles)
.enter()
.append("g")
.attr("class", "circle")
.attr("data-cy", (d) => {
if (this.diagramType === "vertical") {
return `circle-${d.slug}-vertical`;
} else {
return `circle-${d.slug}`;
}
})
.on("mouseover", function (d, i) {
d3.select(this)
.selectAll(".learningSegmentArc")
.transition()
.duration(200)
.attr("fill", (d) => {
return getHoverColor(d);
});
})
.on("mouseout", function (d, i) {
d3.select(this)
.selectAll(".learningSegmentArc")
.transition()
.duration(200)
.attr("fill", (d) => {
return getColor(d);
});
})
.on("click", (d, i) => {
vueRouter.push(i.frontend_url);
})
.attr("role", "button");
const arcGenerator = d3
.arc()
.innerRadius(radius / 2)
.padAngle(12 / 360)
.outerRadius(radius);
//Generate groups
const arcs = this.svg
.selectAll("g")
.selectAll(".learningSegmentArc")
.data((d) => {
return d.pieData;
})
.enter()
.append("g")
.attr("class", "learningSegmentArc")
.attr("fill", colors.gray[300]);
arcs
.transition()
.duration(1000)
.attr("fill", (d) => {
return getColor(d);
});
//Draw arc paths
arcs.append("path").attr("d", arcGenerator);
const circlesText = circle_groups
.append("text")
.attr("fill", colors.blue[900])
.style("font-size", "18px")
.style("overflow-wrap", "break-word")
.text((d) => {
if (this.diagramType === "horizontal") {
return d.title.replace("Prüfungsvorbereitung", "Prüfungs- vorbereitung");
}
return d.title;
});
const topicHeightOffset = 20;
const topicHeight = 50;
const circleHeigth = circleWidth + 20;
function getTopicHorizontalPosition(i, d, topics) {
let x = 0;
for (let index = 0; index < i; index++) {
x += circleWidth * topics[index].circles.length;
}
return x + 10;
}
function getTopicVerticalPosition(i, d, topics) {
let pos = topicHeightOffset;
for (let index = 0; index < i; index++) {
const topic = topics[index];
if (topic.is_visible) {
pos += topicHeight;
}
pos += circleHeigth * topic.circles.length;
}
return pos + topicHeightOffset;
}
function getCircleVerticalPostion(i, d, topics) {
let y = circleHeigth / 2 + topicHeightOffset + 10;
for (let topic_index = 0; topic_index < topics.length; topic_index++) {
const topic = topics[topic_index];
if (topic.is_visible) {
y += topicHeight;
}
for (
let circle_index = 0;
circle_index < topic.circles.length;
circle_index++
) {
const circle = topic.circles[circle_index];
if (circle.id === d.id) {
return y;
}
y += circleHeigth;
} }
y += circleHeigth;
} }
} }
}
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");
const topicLines = topicGroups const topicLines = topicGroups
.append("line") .append("line")
.attr("class", "stroke-gray-500") .attr("class", "stroke-gray-500")
.attr("stroke-width", 1); .attr("stroke-width", 1);
const topicTitles = topicGroups const topicTitles = topicGroups
.append("text") .append("text")
.attr("fill", colors.blue[900]) .attr("fill", colors.blue[900])
.style("font-size", "16px") .style("font-size", "16px")
.text((d) => d.title); .text((d) => d.title);
// 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;
circle_groups.attr("transform", (d, i) => { circle_groups.attr("transform", (d, i) => {
return (
"translate(" +
Circles_X +
"," +
getCircleVerticalPostion(i, d, props.learningPath.topics) +
")"
);
});
circlesText
.attr("y", 7)
.attr("x", radius + 40)
.attr("class", "circlesText text-xl font-bold block");
topicGroups
.attr("transform", (d, i) => {
return ( return (
"translate(" + "translate(" +
Circles_X + Topics_X +
"," + ", " +
getCircleVerticalPostion(i, d, this.learningPath.topics) + getTopicVerticalPosition(i, d, props.learningPath.topics) +
")" ")"
); );
})
.attr("class", (d) => {
return "topic ".concat(d.is_visible ? "block" : "hidden");
}); });
circlesText topicLines.transition().duration(1000).attr("x2", state.width);
.attr("y", 7)
.attr("x", radius + 40)
.attr("class", "circlesText text-xl font-bold block");
topicGroups topicTitles.attr("y", 30);
.attr("transform", (d, i) => { } else {
return ( circle_groups.attr("transform", (d, i) => {
"translate(" + const x_coord = (i + 1) * circleWidth - circleWidth / 2;
Topics_X + return "translate(" + x_coord + ", 200)";
", " + });
getTopicVerticalPosition(i, d, this.learningPath.topics) +
")"
);
})
.attr("class", (d) => {
return "topic ".concat(d.is_visible ? "block" : "hidden");
});
topicLines.transition().duration("1000").attr("x2", this.width); circlesText
.attr("y", radius + 30)
topicTitles.attr("y", 30); .style("text-anchor", "middle")
} else { .call(wrap, circleWidth - 20)
circle_groups.attr("transform", (d, i) => { .attr("class", () => {
const x_coord = (i + 1) * circleWidth - circleWidth / 2; let classes = "circlesText text-xl font-bold hidden";
return "translate(" + x_coord + ", 200)"; if (props.diagramType === "horizontal") {
classes += " lg:block";
}
return classes;
}); });
circlesText topicGroups
.attr("y", radius + 30) .attr("transform", (d, i) => {
.style("text-anchor", "middle") return (
.call(wrap, circleWidth - 20) "translate(" +
.attr("class", () => { getTopicHorizontalPosition(i, d, props.learningPath.topics) +
let classes = "circlesText text-xl font-bold hidden"; ",0)"
if (this.diagramType === "horizontal") { );
classes += " lg:block"; })
} .attr("class", (d) => {
return classes; let classes = "topic hidden";
}); if (props.diagramType === "horizontal" && d.is_visible) {
classes += " lg:block";
}
return classes;
});
topicGroups topicLines
.attr("transform", (d, i) => { .attr("x1", -10)
return ( .attr("y1", 0)
"translate(" + .attr("x2", -10)
getTopicHorizontalPosition(i, d, this.learningPath.topics) + .attr("y2", 0)
",0)" .transition()
); .duration(1000)
}) .attr("y2", 350);
.attr("class", (d) => {
let classes = "topic hidden";
if (this.diagramType === "horizontal" && d.is_visible) {
classes += " lg:block";
}
return classes;
});
topicLines topicTitles
.attr("x1", -10) .attr("y", 20)
.attr("y1", 0) .style("font-size", "18px")
.attr("x2", -10) .call(wrap, circleWidth * 0.8)
.attr("y2", 0) .attr("class", "topic-title font-bold");
.transition() }
.duration("1000")
.attr("y2", 350);
topicTitles // @ts-ignore
.attr("y", 20) function wrap(texts, width: number) {
.style("font-size", "18px") texts.each(function () {
.call(wrap, circleWidth * 0.8) // @ts-ignore
.attr("class", "topic-title font-bold"); let text = d3.select(this),
} words = text.text().split(/\s+/).reverse(),
word,
lines: string[] = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = 0, //parseFloat(text.attr('dy')),
tspan = text
.text(null)
.append("tspan")
.attr("x", 0)
.attr("y", y)
.attr("dy", dy + "em");
while ((word = words.pop())) {
lines.push(word);
tspan.text(lines.join(" "));
// @ts-ignore
if (tspan.node().getComputedTextLength() > width) {
lines.pop();
tspan.text(lines.join(" "));
lines = [word];
function wrap(text, width) {
text.each(function () {
let text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = 0, //parseFloat(text.attr('dy')),
tspan = text tspan = text
.text(null)
.append("tspan") .append("tspan")
.attr("x", 0) .attr("x", 0)
.attr("y", y) .attr("y", y)
.attr("dy", dy + "em"); .attr("dy", ++lineNumber * lineHeight + dy + "em")
while ((word = words.pop())) { .text(word);
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text
.append("tspan")
.attr("x", 0)
.attr("y", y)
.attr("dy", ++lineNumber * lineHeight + dy + "em")
.text(word);
}
} }
}); }
} });
}, }
}; }
</script> </script>
<template> <template>