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>
import colors from "@/colors.json";
<script setup lang="ts">
import * as d3 from "d3";
import * as _ from "lodash";
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 {
props: {
diagramType: {
type: String,
default: "horizontal",
},
postfix: {
type: String,
default: "",
},
learningPath: {
required: true,
type: Object,
},
},
data() {
return {
width: 1640,
height: 384,
};
},
computed: {
svgId() {
return `learningpath-diagram-${this.learningPath.slug}-${this.diagramType}${this.postfix}`;
},
viewBox() {
return `0 0 ${this.width} ${this.height}`;
},
circles() {
function someFinished(circle, learningSequence) {
if (circle) {
return circle.someFinishedInLearningSequence(
learningSequence.translation_key
);
}
return false;
type DiagramType = "horizontal" | "vertical" | "horizontalSmall";
export interface Props {
diagramType?: DiagramType;
postfix?: string;
learningPath: LearningPath;
}
const props = withDefaults(defineProps<Props>(), {
diagramType: "horizontal",
postfix: "",
});
const state = reactive({ width: 1640, height: 384 });
const svgId = computed(() => {
return `learningpath-diagram-${props.learningPath?.slug}-${props.diagramType}${props.postfix}`;
});
const viewBox = computed(() => {
return `0 0 ${state.width} ${state.height}`;
});
const vueRouter = useRouter();
onMounted(async () => {
log.debug("CircleDiagram mounted");
render();
});
function someFinished(circle: Circle, learningSequence: LearningSequence) {
if (circle) {
return circle.someFinishedInLearningSequence(learningSequence.translation_key);
}
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) {
if (circle) {
return circle.allFinishedInLearningSequence(learningSequence.translation_key);
}
return false;
}
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);
})
.on("mouseover", function () {
d3.select(this)
.selectAll(".learningSegmentArc")
.transition()
.duration(200)
.attr("fill", (d) => {
return getHoverColor(d as CirclePie);
});
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 [];
},
svg() {
const result = d3.select("#" + this.svgId);
result.selectAll("*").remove();
return result;
},
},
return d.title;
});
mounted() {
log.debug("LearningPathDiagram mounted");
const topicHeightOffset = 20;
const topicHeight = 50;
const circleHeigth = circleWidth + 20;
// clean old svg
d3.select("#" + this.svgId)
.selectAll("*")
.remove();
let circleWidth = 200;
if (this.diagramType === "vertical") {
circleWidth = 60;
function getTopicHorizontalPosition(i: number, _d: unknown, topics: Topic[]) {
let x = 0;
for (let index = 0; index < i; index++) {
x += circleWidth * topics[index].circles.length;
}
const radius = (circleWidth * 0.8) / 2;
return x + 10;
}
if (this.diagramType === "vertical") {
this.width = Math.min(960, window.innerWidth - 32);
this.height = 860;
} else {
this.width = circleWidth * this.circles.length;
function getTopicVerticalPosition(i: number, _d: unknown, topics: Topic[]) {
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 getColor(d) {
let color = colors.gray[300];
if (d.someFinished) {
color = colors.sky[500];
function getCircleVerticalPostion(i: number, d: InternalCircle, topics: Topic[]) {
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;
}
if (d.allFinished) {
color = colors.green[500];
}
return color;
}
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;
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;
}
}
}
const topicGroups = this.svg
.selectAll(".topic")
.data(this.learningPath.topics)
.enter()
.append("g");
const topicGroups = svgElement
.selectAll(".topic")
.data(props.learningPath.topics)
.enter()
.append("g");
const topicLines = topicGroups
.append("line")
.attr("class", "stroke-gray-500")
.attr("stroke-width", 1);
const topicLines = topicGroups
.append("line")
.attr("class", "stroke-gray-500")
.attr("stroke-width", 1);
const topicTitles = topicGroups
.append("text")
.attr("fill", colors.blue[900])
.style("font-size", "16px")
.text((d) => d.title);
const topicTitles = topicGroups
.append("text")
.attr("fill", colors.blue[900])
.style("font-size", "16px")
.text((d) => d.title);
// Calculate positions of objects
// Calculate positions of objects
if (this.diagramType === "vertical") {
const Circles_X = radius;
const Topics_X = Circles_X - 20;
if (props.diagramType === "vertical") {
const Circles_X = radius;
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 (
"translate(" +
Circles_X +
"," +
getCircleVerticalPostion(i, d, this.learningPath.topics) +
Topics_X +
", " +
getTopicVerticalPosition(i, d, props.learningPath.topics) +
")"
);
})
.attr("class", (d) => {
return "topic ".concat(d.is_visible ? "block" : "hidden");
});
circlesText
.attr("y", 7)
.attr("x", radius + 40)
.attr("class", "circlesText text-xl font-bold block");
topicLines.transition().duration(1000).attr("x2", state.width);
topicGroups
.attr("transform", (d, i) => {
return (
"translate(" +
Topics_X +
", " +
getTopicVerticalPosition(i, d, this.learningPath.topics) +
")"
);
})
.attr("class", (d) => {
return "topic ".concat(d.is_visible ? "block" : "hidden");
});
topicTitles.attr("y", 30);
} else {
circle_groups.attr("transform", (d, i) => {
const x_coord = (i + 1) * circleWidth - circleWidth / 2;
return "translate(" + x_coord + ", 200)";
});
topicLines.transition().duration("1000").attr("x2", this.width);
topicTitles.attr("y", 30);
} else {
circle_groups.attr("transform", (d, i) => {
const x_coord = (i + 1) * circleWidth - circleWidth / 2;
return "translate(" + x_coord + ", 200)";
circlesText
.attr("y", radius + 30)
.style("text-anchor", "middle")
.call(wrap, circleWidth - 20)
.attr("class", () => {
let classes = "circlesText text-xl font-bold hidden";
if (props.diagramType === "horizontal") {
classes += " lg:block";
}
return classes;
});
circlesText
.attr("y", radius + 30)
.style("text-anchor", "middle")
.call(wrap, circleWidth - 20)
.attr("class", () => {
let classes = "circlesText text-xl font-bold hidden";
if (this.diagramType === "horizontal") {
classes += " lg:block";
}
return classes;
});
topicGroups
.attr("transform", (d, i) => {
return (
"translate(" +
getTopicHorizontalPosition(i, d, props.learningPath.topics) +
",0)"
);
})
.attr("class", (d) => {
let classes = "topic hidden";
if (props.diagramType === "horizontal" && d.is_visible) {
classes += " lg:block";
}
return classes;
});
topicGroups
.attr("transform", (d, i) => {
return (
"translate(" +
getTopicHorizontalPosition(i, d, this.learningPath.topics) +
",0)"
);
})
.attr("class", (d) => {
let classes = "topic hidden";
if (this.diagramType === "horizontal" && d.is_visible) {
classes += " lg:block";
}
return classes;
});
topicLines
.attr("x1", -10)
.attr("y1", 0)
.attr("x2", -10)
.attr("y2", 0)
.transition()
.duration(1000)
.attr("y2", 350);
topicLines
.attr("x1", -10)
.attr("y1", 0)
.attr("x2", -10)
.attr("y2", 0)
.transition()
.duration("1000")
.attr("y2", 350);
topicTitles
.attr("y", 20)
.style("font-size", "18px")
.call(wrap, circleWidth * 0.8)
.attr("class", "topic-title font-bold");
}
topicTitles
.attr("y", 20)
.style("font-size", "18px")
.call(wrap, circleWidth * 0.8)
.attr("class", "topic-title font-bold");
}
// @ts-ignore
function wrap(texts, width: number) {
texts.each(function () {
// @ts-ignore
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
.text(null)
.append("tspan")
.attr("x", 0)
.attr("y", y)
.attr("dy", dy + "em");
while ((word = words.pop())) {
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);
}
.attr("dy", ++lineNumber * lineHeight + dy + "em")
.text(word);
}
});
}
},
};
}
});
}
}
</script>
<template>