Merged in bugfix/VBV-308-bereinigung-altes-lernpfad-diagramm (pull request #74)

Cleanup old learn path diagrams

* Fix Safari mobile bug

* Initial cleanup


Approved-by: Daniel Egger
This commit is contained in:
Elia Bieri 2023-05-11 07:50:20 +00:00
parent 6799e6bdda
commit 2e974dc323
6 changed files with 41 additions and 504 deletions

View File

@ -1,484 +1,56 @@
<script setup lang="ts">
import * as d3 from "d3";
import kebabCase from "lodash/kebabCase";
import * as log from "loglevel";
// @ts-ignore
import colors from "@/colors.json";
import type { Circle } from "@/services/circle";
import LearningPathCircle from "@/pages/learningPath/learningPathPage/LearningPathCircle.vue";
import { calculateCircleSectorData } from "@/pages/learningPath/learningPathPage/utils";
import type { LearningPath } from "@/services/learningPath";
import type { LearningSequence, Topic } from "@/types";
import { computed, onMounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { computed } from "vue";
export type DiagramType = "horizontal" | "vertical" | "horizontalSmall" | "singleSmall";
export type DiagramType = "horizontal" | "horizontalSmall" | "singleSmall";
export interface Props {
diagramType?: DiagramType;
postfix?: string;
profileUserId?: string;
learningPath: LearningPath;
// set to undefined (default) to show all circles
showCircleTranslationKeys: string[];
pullUp?: boolean;
showCircleTranslationKeys?: string[];
}
const props = withDefaults(defineProps<Props>(), {
diagramType: "horizontal",
postfix: "",
profileUserId: "",
showCircleTranslationKeys: undefined,
pullUp: true,
});
log.debug(
"LearningPathDiagram created",
props.postfix,
props.profileUserId,
props.showCircleTranslationKeys
const circles = computed(() =>
props.learningPath.circles.filter(
(c) => props.showCircleTranslationKeys?.includes(c.translation_key) ?? true
)
);
const state = reactive({ width: 1640, height: 384, startY: 0 });
const svgId = computed(() => {
return `learningpath-diagram-${props.learningPath?.slug}-${props.diagramType}${props.postfix}`;
});
const viewBox = computed(() => {
return `0 ${state.startY} ${state.width} ${state.height}`;
});
const vueRouter = useRouter();
onMounted(async () => {
log.debug("LearningPathDiagram mounted", props.postfix, props.profileUserId);
render();
});
watch(
() => props.showCircleTranslationKeys,
(newCircleIds, oldCircleIds) => {
log.debug("LearningPathDiagram showCircleIds changed", newCircleIds, oldCircleIds);
render();
},
{ deep: true }
);
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;
}
function circleUrl(circle: InternalCircle) {
let circleUrl = circle.frontend_url;
if (props.profileUserId) {
circleUrl = `/course/${props.learningPath.course.slug}/cockpit/profile/${props.profileUserId}/${circle.slug}`;
}
return circleUrl;
}
interface CirclePie extends d3.PieArcDatum<number> {
someFinished: boolean;
allFinished: boolean;
done: boolean;
}
interface InternalCircle {
id: number;
translation_key: string;
title: string;
frontend_url: string;
slug: string;
pieData: CirclePie[];
}
function isCircleVisible(circleTranslationKey: string) {
if (props.showCircleTranslationKeys) {
return props.showCircleTranslationKeys.includes(circleTranslationKey);
}
return true;
}
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);
});
if (isCircleVisible(circle.translation_key)) {
internalCircles.push({
pieData: pieData.reverse() as CirclePie[],
title: circle.title,
frontend_url: circle.frontend_url,
id: circle.id,
translation_key: circle.translation_key,
slug: kebabCase(circle.title),
});
}
});
return internalCircles;
}
return [];
});
function render() {
log.debug("LearningPathDiagram 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;
const wrapperClasses = computed(() => {
let classes = "flex my-5";
if (props.diagramType === "horizontal") {
classes += " flex-row h-8";
} else if (props.diagramType === "horizontalSmall") {
classes += " flex-row h-5";
} else if (props.diagramType === "singleSmall") {
state.height = 260;
state.startY = 60;
state.width = circleWidth * circles.value.length;
} else {
state.width = circleWidth * circles.value.length;
classes += " h-8";
}
return classes;
});
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;
const circleClasses = computed(() => {
if (props.diagramType === "horizontal" || props.diagramType === "horizontalSmall") {
return "pl-1";
}
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", (internalCircle) => {
let result = "circle";
if (!isCircleVisible(internalCircle.translation_key)) {
result += " hidden";
}
return result;
})
.attr("data-cy", (d) => {
if (props.diagramType === "vertical") {
return `circle-${d.slug}-vertical`;
} else {
return `circle-${d.slug}`;
}
})
.on("mouseover", function () {
d3.select(this)
.selectAll(".learningSegmentArc")
.transition()
.duration(200)
.attr("fill", (d) => {
return getHoverColor(d as CirclePie);
});
})
.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(circleUrl(i));
})
.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 d.title;
});
const topicHeightOffset = 20;
const topicHeight = 50;
const circleHeigth = circleWidth + 20;
function getTopicHorizontalPosition(i: number, _d: unknown, topics: Topic[]) {
let x = 0;
for (let index = 0; index < i; index++) {
x += circleWidth * topics[index].circles.length;
}
return x + 10;
}
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 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;
}
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 = 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 topicTitles = topicGroups
.append("text")
.attr("fill", colors.blue[900])
.style("font-size", "16px")
.text((d) => d.title);
// Calculate positions of objects
if (props.diagramType === "vertical") {
const Circles_X = radius;
const Topics_X = Circles_X - 20;
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(" +
Topics_X +
", " +
getTopicVerticalPosition(i, d, props.learningPath.topics) +
")"
);
})
.attr("class", (d) => {
return "topic ".concat(d.is_visible ? "block" : "hidden");
});
topicLines.transition().duration(1000).attr("x2", state.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;
});
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;
});
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");
}
// @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];
tspan = text
.append("tspan")
.attr("x", 0)
.attr("y", y)
.attr("dy", ++lineNumber * lineHeight + dy + "em")
.text(word);
}
}
});
}
}
return "";
});
</script>
<template>
<div class="svg-container h-full content-start">
<svg
:id="svgId"
class="learning-path-visualization mx-auto h-full lg:mt-0"
:class="{
'max-h-[90px]': ['horizontalSmall', 'singleSmall'].includes(diagramType),
'max-h-[90px] lg:max-h-[380px]': ['horizontal'].includes(diagramType),
'-mt-6': pullUp,
}"
:viewBox="viewBox"
></svg>
<div :class="wrapperClasses">
<LearningPathCircle
v-for="circle in circles"
:key="circle.id"
:class="circleClasses"
:sectors="calculateCircleSectorData(circle)"
></LearningPathCircle>
</div>
</template>

View File

@ -1,34 +0,0 @@
<script setup lang="ts">
import * as log from "loglevel";
import LearningPathDiagram from "@/components/learningPath/LearningPathDiagram.vue";
import ItFullScreenModal from "@/components/ui/ItFullScreenModal.vue";
import type { LearningPath } from "@/services/learningPath";
log.debug("LearningPathView created");
const props = defineProps<{
learningPath: LearningPath | undefined;
show: boolean;
}>();
const emits = defineEmits(["closemodal"]);
</script>
<template>
<ItFullScreenModal :show="show" @closemodal="$emit('closemodal')">
<div v-if="learningPath" class="container-medium">
<h1>{{ learningPath.title }}</h1>
<div class="learningpath flex flex-col">
<div class="flex h-max flex-col">
<LearningPathDiagram
v-if="learningPath"
class="w-full"
:learning-path="learningPath"
diagram-type="vertical"
></LearningPathDiagram>
</div>
</div>
</div>
</ItFullScreenModal>
</template>
<style scoped></style>

View File

@ -6,7 +6,7 @@ import * as log from "loglevel";
import { computed, onMounted } from "vue";
import CompetenceDetail from "@/components/competences/CompetenceDetail.vue";
import LearningPathDiagram from "@/components/learningPath/LearningPathDiagram.vue";
import LearningPathPathView from "@/pages/learningPath/learningPathPage/LearningPathPathView.vue";
const props = defineProps<{
userId: string;
@ -61,14 +61,13 @@ function setActiveClasses(isActive: boolean) {
</div>
</header>
<main>
<div v-if="learningPath" class="mb-8 w-full bg-white pb-4 pt-8">
<LearningPathDiagram
class="mx-auto max-h-[90px] w-full max-w-[1920px] px-4 lg:max-h-[380px]"
diagram-type="horizontal"
<div v-if="learningPath" class="mb-8 w-full bg-white pb-1 pt-2">
<!-- TODO: rework this section with next redesign -->
<LearningPathPathView
:use-mobile-layout="false"
:hide-buttons="true"
:learning-path="learningPath"
:postfix="userId"
:profile-user-id="userId"
></LearningPathDiagram>
></LearningPathPathView>
</div>
<ul class="mb-5 flex flex-row border-b-2">
<li class="relative top-px mr-12 pb-3" :class="setActiveClasses(true)">

View File

@ -135,7 +135,7 @@ function render() {
<div class="svg-container content-center">
<pre hidden>{{ pieData }}</pre>
<pre hidden>{{ render() }}</pre>
<svg :id="svgId" class="h-full">
<svg :id="svgId" class="h-full min-w-[20px]">
<circle :cx="width / 2" :cy="height / 2" :r="radius" :color="colors.gray[300]" />
<circle :cx="width / 2" :cy="height / 2" :r="radius / 2.5" color="white" />
</svg>

View File

@ -10,6 +10,7 @@ import { ref } from "vue";
const props = defineProps<{
learningPath: LearningPath | undefined;
useMobileLayout: boolean;
hideButtons?: boolean;
}>();
const scrollIncrement = 600;
@ -71,7 +72,7 @@ const scrollLearnPathDiagram = (offset: number) => {
:is-last-circle="
isLastCircle(topicIndex, circleIndex, topic.circles.length)
"
:is-current-circle="isCurrentCircle(circle)"
:is-current-circle="isCurrentCircle(circle) && !props.hideButtons"
></LearningPathCircleColumn>
</div>
</div>

View File

@ -5,7 +5,7 @@ import type {
import type { Circle } from "@/services/circle";
export function calculateCircleSectorData(circle: Circle): CircleSectorData[] {
const sectors = circle.learningSequences.map((ls) => {
return circle.learningSequences.map((ls) => {
let progress: CircleSectorProgress = "none";
if (circle.allFinishedInLearningSequence(ls.translation_key)) {
progress = "finished";
@ -16,5 +16,4 @@ export function calculateCircleSectorData(circle: Circle): CircleSectorData[] {
progress: progress,
};
});
return sectors;
}