From 2d083f5c0a573a8463f99c9edb7c51708f33e28f Mon Sep 17 00:00:00 2001 From: marwin Date: Tue, 6 May 2025 20:52:51 +0100 Subject: [PATCH 01/16] =?UTF-8?q?=E2=9C=A8=20feat:=20update=20mindmap=20te?= =?UTF-8?q?mplate=20for=20improved=20layout=20and=20usability?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- templates/mindmap.html | 682 +++++++++++++++++++++++------------------ 1 file changed, 383 insertions(+), 299 deletions(-) diff --git a/templates/mindmap.html b/templates/mindmap.html index 99f2600..3bfc794 100644 --- a/templates/mindmap.html +++ b/templates/mindmap.html @@ -4,18 +4,34 @@ {% block extra_css %} {% endblock %} {% block content %} -
-
- -
- -
-

- Wissenslandkarte -

-

- Visualisiere die Verbindungen zwischen Gedanken und Konzepten -

-
+ +
+ +
+

+ Wissenslandkarte +

+

+ Visualisiere die Verbindungen zwischen Gedanken und Konzepten +

+
- -
- -
- - - - - - -
- - -
- - -
-

Knoteninfo

-

Wählen Sie einen Knoten aus...

- -
-
Verknüpfte Knoten
- -
-
-
+ +
+ +
+ + + + + +
- -
- -
-

- Über die Mindmap -

-
-

Die interaktive Wissenslandkarte zeigt Verbindungen zwischen verschiedenen Gedanken und Konzepten.

-

Sie können:

-
    -
  • Knoten auswählen, um Details zu sehen
  • -
  • Zoomen (Mausrad oder Pinch-Geste)
  • -
  • Die Karte verschieben (Drag & Drop)
  • -
  • Die Toolbar nutzen für weitere Aktionen
  • -
-
-
+ +
- -
-

- Kategorien -

-
- -
Philosophie
-
Wissenschaft
-
Technologie
-
Künste
-
Psychologie
-
-
+ +
+

Knoteninfo

+

Wählen Sie einen Knoten aus...

- - + + +
+ + +
+
+
+
+

© 2023 Systades. Alle Rechte vorbehalten.

+
+ +
+
+
{% endblock %} {% block extra_js %} @@ -399,4 +412,75 @@ + + + {% endblock %} \ No newline at end of file From 903e095b669d85873c32829a8e6de7c5277edfad Mon Sep 17 00:00:00 2001 From: marwin Date: Tue, 6 May 2025 21:23:29 +0100 Subject: [PATCH 02/16] =?UTF-8?q?=E2=9C=A8=20feat:=20enhance=20mindmap=20f?= =?UTF-8?q?unctionality=20and=20improve=20user=20interaction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- static/js/mindmap-init.js | 1377 +++++++++--------------------- static/js/mindmap-interaction.js | 724 ++++++++++------ static/js/update_mindmap.js | 294 ++++++- templates/mindmap.html | 622 ++++---------- 4 files changed, 1297 insertions(+), 1720 deletions(-) diff --git a/static/js/mindmap-init.js b/static/js/mindmap-init.js index 4dcccdc..0d09df8 100644 --- a/static/js/mindmap-init.js +++ b/static/js/mindmap-init.js @@ -40,42 +40,51 @@ function loadScript(src, callback) { */ function initMindmap() { const cyContainer = document.getElementById('cy'); - const fitBtn = document.getElementById('fit-btn'); - const resetBtn = document.getElementById('reset-btn'); - const toggleLabelsBtn = document.getElementById('toggle-labels-btn'); - const nodeInfoPanel = document.getElementById('node-info-panel'); - const nodeDescription = document.getElementById('node-description'); - const connectedNodes = document.getElementById('connected-nodes'); - - let labelsVisible = true; - let selectedNode = null; // Erstelle Cytoscape-Instanz const cy = cytoscape({ container: cyContainer, - style: getDefaultStyles(), + style: getNeuralNetworkStyles(), layout: { name: 'cose', animate: true, - animationDuration: 800, + animationDuration: 1500, nodeDimensionsIncludeLabels: true, - padding: 50, - spacingFactor: 1.2, + padding: 100, + spacingFactor: 1.5, randomize: true, componentSpacing: 100, nodeRepulsion: 8000, edgeElasticity: 100, nestingFactor: 1.2, - gravity: 80 + gravity: 80, + idealEdgeLength: 150 }, - wheelSensitivity: 0.3, + wheelSensitivity: 0.1, // Sanfterer Zoom + minZoom: 0.3, + maxZoom: 2.5, }); // Daten vom Server laden loadMindmapData(cy); // Event-Handler zuweisen - setupEventListeners(cy, fitBtn, resetBtn, toggleLabelsBtn, nodeInfoPanel, nodeDescription, connectedNodes); + setupEventListeners(cy); + + // Globale Referenz für Externe Zugriffe + window.cy = cy; + window.mindmapInstance = { + cy: cy, + selectedNode: null, + centerNodeInView: function(node) { + cy.animate({ + center: { eles: node }, + zoom: 1.2, + duration: 800, + easing: 'ease-in-out-cubic' + }); + } + }; } /** @@ -123,8 +132,12 @@ function loadMindmapData(cy) { data.nodes.unshift(rootNode); } - // Knoten hinzufügen + // Knoten hinzufügen mit zufälligen Werten für neuronales Netzwerk data.nodes.forEach(node => { + // Neuronenzell-Größe und Aktivität + const neuronSize = Math.floor(Math.random() * 8) + 3; + const neuronActivity = Math.random() * 0.7 + 0.3; // Aktivitätslevel zwischen 0.3 und 1.0 + elements.push({ group: 'nodes', data: { @@ -132,7 +145,9 @@ function loadMindmapData(cy) { name: node.name, description: node.description || '', color: node.color_code || '#8B5CF6', - isRoot: node.name === 'Wissen' + isRoot: node.name === 'Wissen', + neuronSize: neuronSize, + neuronActivity: neuronActivity } }); }); @@ -145,7 +160,8 @@ function loadMindmapData(cy) { data: { id: `${edge.source}-${edge.target}`, source: edge.source.toString(), - target: edge.target.toString() + target: edge.target.toString(), + strength: Math.random() * 0.6 + 0.2 // Zufällige Verbindungsstärke zwischen 0.2 und 0.8 } }); }); @@ -160,7 +176,8 @@ function loadMindmapData(cy) { data: { id: `${rootId}-${node.id}`, source: rootId, - target: node.id.toString() + target: node.id.toString(), + strength: Math.random() * 0.6 + 0.2 } }); } @@ -175,14 +192,22 @@ function loadMindmapData(cy) { cy.layout({ name: 'cose', animate: true, - animationDuration: 800, + animationDuration: 1800, nodeDimensionsIncludeLabels: true, - padding: 50, - spacingFactor: 1.5, + padding: 100, + spacingFactor: 1.8, randomize: false, - fit: true + fit: true, + componentSpacing: 100, + nodeRepulsion: 8000, + edgeElasticity: 100 }).run(); + // Neuronale Netzwerk-Effekte hinzufügen + setTimeout(() => { + addNeuralNetworkEffects(cy); + }, 2000); + // Nach dem Laden Event auslösen document.dispatchEvent(new CustomEvent('mindmap-loaded')); }) @@ -208,8 +233,11 @@ function loadMindmapData(cy) { const fallbackElements = []; - // Knoten hinzufügen + // Knoten hinzufügen mit Neuronen-Eigenschaften fallbackData.nodes.forEach(node => { + const neuronSize = Math.floor(Math.random() * 8) + 3; + const neuronActivity = Math.random() * 0.7 + 0.3; + fallbackElements.push({ group: 'nodes', data: { @@ -217,7 +245,9 @@ function loadMindmapData(cy) { name: node.name, description: node.description || '', color: node.color_code || '#8B5CF6', - isRoot: node.name === 'Wissen' + isRoot: node.name === 'Wissen', + neuronSize: neuronSize, + neuronActivity: neuronActivity } }); }); @@ -229,7 +259,8 @@ function loadMindmapData(cy) { data: { id: `${edge.source}-${edge.target}`, source: edge.source.toString(), - target: edge.target.toString() + target: edge.target.toString(), + strength: Math.random() * 0.6 + 0.2 } }); }); @@ -239,1011 +270,379 @@ function loadMindmapData(cy) { cy.add(fallbackElements); // Layout anwenden - cy.layout({ name: 'cose', animate: true }).run(); + cy.layout({ + name: 'cose', + animate: true, + animationDuration: 1800, + nodeDimensionsIncludeLabels: true, + fit: true + }).run(); + + // Neuronale Netzwerk-Effekte hinzufügen + setTimeout(() => { + addNeuralNetworkEffects(cy); + }, 2000); + + // Nach dem Laden Event auslösen + document.dispatchEvent(new CustomEvent('mindmap-loaded')); }); } +// Neuronales Netzwerk-Effekte hinzufügen +function addNeuralNetworkEffects(cy) { + cy.nodes().forEach(node => { + const originalPos = node.position(); + const activity = node.data('neuronActivity') || 0.5; + + // Subtile Pulsierende Bewegung für Neuronen + setInterval(() => { + const randomFactor = Math.random() * 0.5 + 0.5; // Zufälliger Faktor zwischen 0.5 und 1 + const offset = (Math.random() - 0.5) * activity; + const pulseIntensity = 0.7 + (Math.sin(Date.now() / 2000) * 0.3 * activity * randomFactor); + + // Leichtes Pulsieren und Bewegung basierend auf "Neuronenaktivität" + node.animate({ + position: { + x: originalPos.x + offset, + y: originalPos.y + offset + }, + style: { + 'background-opacity': Math.max(0.7, pulseIntensity), + 'shadow-opacity': Math.max(0.5, pulseIntensity * 0.8) + }, + duration: 3000 + (Math.random() * 2000), + easing: 'ease-in-out-cubic', + complete: function() { + node.animate({ + position: { x: originalPos.x, y: originalPos.y }, + style: { + 'background-opacity': 0.9, + 'shadow-opacity': 0.6 + }, + duration: 3000 + (Math.random() * 2000), + easing: 'ease-in-out-cubic' + }); + } + }); + }, 6000 + Math.random() * 4000); // Leicht zufällige Intervalle für organischeres Aussehen + + // Zusätzliche "synaptische" Effekte für Kanten + node.connectedEdges().forEach(edge => { + const strength = edge.data('strength') || 0.5; + + // Pulsierende Aktivität entlang der Kanten + setInterval(() => { + const pulseIntensity = 0.5 + (Math.sin(Date.now() / 1500) * 0.5 * strength); + + edge.animate({ + style: { + 'line-opacity': Math.max(0.3, pulseIntensity), + 'width': 1 + (pulseIntensity * 0.6) + }, + duration: 1200, + easing: 'ease-in-out' + }); + }, 3000 + (Math.random() * 2000)); + }); + }); +} + /** * Richtet Event-Listener für die Mindmap ein * @param {Object} cy - Cytoscape-Instanz - * @param {HTMLElement} fitBtn - Fit-Button - * @param {HTMLElement} resetBtn - Reset-Button - * @param {HTMLElement} toggleLabelsBtn - Toggle-Labels-Button - * @param {HTMLElement} nodeInfoPanel - Node-Info-Panel - * @param {HTMLElement} nodeDescription - Node-Description - * @param {HTMLElement} connectedNodes - Connected-Nodes-Container */ -function setupEventListeners(cy, fitBtn, resetBtn, toggleLabelsBtn, nodeInfoPanel, nodeDescription, connectedNodes) { - let labelsVisible = true; - - // Fit-Button - if (fitBtn) { - fitBtn.addEventListener('click', function() { - cy.fit(); - }); - } - - // Reset-Button - if (resetBtn) { - resetBtn.addEventListener('click', function() { - cy.layout({ name: 'cose', animate: true }).run(); - }); - } - - // Toggle-Labels-Button - if (toggleLabelsBtn) { - toggleLabelsBtn.addEventListener('click', function() { - labelsVisible = !labelsVisible; - cy.style() - .selector('node') - .style({ - 'text-opacity': labelsVisible ? 1 : 0 - }) - .update(); - }); - } - - // Knoten-Klick +function setupEventListeners(cy) { + // Klick auf Knoten cy.on('tap', 'node', function(evt) { const node = evt.target; - // Zuvor ausgewählten Knoten zurücksetzen - cy.nodes().removeClass('selected'); + // Alle vorherigen Hervorhebungen zurücksetzen + cy.nodes().forEach(n => { + n.removeStyle(); + n.connectedEdges().removeStyle(); + }); - // Neuen Knoten auswählen - node.addClass('selected'); + // Speichere ausgewählten Knoten + window.mindmapInstance.selectedNode = node; - if (nodeInfoPanel && nodeDescription && connectedNodes) { - // Info-Panel aktualisieren - nodeDescription.textContent = node.data('description') || 'Keine Beschreibung verfügbar.'; - - // Verbundene Knoten anzeigen - connectedNodes.innerHTML = ''; - - // Verbundene Knoten sammeln - const connectedNodesList = node.neighborhood('node'); - - if (connectedNodesList.length > 0) { - connectedNodesList.forEach(connectedNode => { - // Nicht den ausgewählten Knoten selbst anzeigen - if (connectedNode.id() !== node.id()) { - const nodeLink = document.createElement('span'); - nodeLink.className = 'node-link'; - nodeLink.textContent = connectedNode.data('name'); - nodeLink.style.backgroundColor = connectedNode.data('color'); - - // Klick-Ereignis, um zu diesem Knoten zu wechseln - nodeLink.addEventListener('click', function() { - connectedNode.select(); - cy.animate({ - center: { eles: connectedNode }, - duration: 500, - easing: 'ease-in-out-cubic' - }); - }); - - connectedNodes.appendChild(nodeLink); - } - }); - } else { - connectedNodes.innerHTML = 'Keine verbundenen Knoten'; - } - - // Panel anzeigen - nodeInfoPanel.classList.add('visible'); - } + // Aktiviere leuchtenden Effekt statt Umkreisung + node.style({ + 'background-opacity': 1, + 'background-color': node.data('color'), + 'shadow-color': node.data('color'), + 'shadow-opacity': 1, + 'shadow-blur': 15, + 'shadow-offset-x': 0, + 'shadow-offset-y': 0 + }); + + // Verbundene Kanten und Knoten hervorheben + const connectedEdges = node.connectedEdges(); + const connectedNodes = node.neighborhood('node'); + + connectedEdges.style({ + 'line-color': '#a78bfa', + 'target-arrow-color': '#a78bfa', + 'source-arrow-color': '#a78bfa', + 'line-opacity': 0.8, + 'width': 2 + }); + + connectedNodes.style({ + 'shadow-opacity': 0.7, + 'shadow-blur': 10, + 'shadow-color': '#a78bfa' + }); + + // Info-Panel aktualisieren + updateInfoPanel(node); + + // Seitenleiste aktualisieren + updateSidebar(node); }); - // Hintergrund-Klick + // Klick auf Hintergrund - Auswahl zurücksetzen cy.on('tap', function(evt) { if (evt.target === cy) { - // Klick auf den Hintergrund - cy.nodes().removeClass('selected'); - - // Info-Panel verstecken - if (nodeInfoPanel) { - nodeInfoPanel.classList.remove('visible'); - } + resetSelection(cy); } }); - // Dark Mode-Änderungen - document.addEventListener('darkModeToggled', function(event) { - const isDark = event.detail.isDark; - cy.style(getDefaultStyles(isDark)); + // Smooth Zoom mit Mouse Wheel + cy.on('mousewheel', function(evt) { + const delta = evt.originalEvent.deltaY; + const factor = delta > 0 ? 0.95 : 1.05; + + cy.animate({ + zoom: cy.zoom() * factor, + duration: 100 + }); + }); +} + +// Aktualisiert das Info-Panel mit Daten des ausgewählten Knotens +function updateInfoPanel(node) { + const nodeInfoPanel = document.getElementById('node-info-panel'); + const nodeDescription = document.getElementById('node-description'); + const connectedNodes = document.getElementById('connected-nodes'); + const panelTitle = nodeInfoPanel.querySelector('.info-panel-title'); + + if (!nodeInfoPanel || !nodeDescription || !connectedNodes) return; + + // Titel und Beschreibung aktualisieren + panelTitle.textContent = node.data('name'); + nodeDescription.textContent = node.data('description') || 'Keine Beschreibung verfügbar.'; + + // Verbundene Knoten anzeigen + connectedNodes.innerHTML = ''; + + // Verbundene Knoten sammeln (direktes Neighborhood) + const connectedNodesList = []; + node.neighborhood('node').forEach(n => { + if (!connectedNodesList.includes(n) && n.id() !== node.id()) { + connectedNodesList.push(n); + } + }); + + // Verbundene Knoten im Panel anzeigen + if (connectedNodesList.length > 0) { + connectedNodesList.forEach(connectedNode => { + const nodeLink = document.createElement('span'); + nodeLink.className = 'inline-block px-2 py-1 text-xs rounded-md m-1 cursor-pointer'; + nodeLink.style.backgroundColor = connectedNode.data('color'); + nodeLink.textContent = connectedNode.data('name'); + + // Beim Klick auf den verbundenen Knoten zu diesem wechseln + nodeLink.addEventListener('click', function() { + resetSelection(cy); + + // Verzögerung vor der neuen Auswahl für besseren visuellen Übergang + setTimeout(() => { + connectedNode.trigger('tap'); + }, 50); + }); + + connectedNodes.appendChild(nodeLink); + }); + } else { + connectedNodes.innerHTML = 'Keine verbundenen Knoten'; + } + + // Panel anzeigen mit Animation + nodeInfoPanel.style.transition = 'all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1)'; + nodeInfoPanel.classList.add('visible'); +} + +// Aktualisiert die Seitenleiste +function updateSidebar(node) { + // Alle standard Panels ausblenden + document.querySelectorAll('[data-sidebar]').forEach(panel => { + if (panel.getAttribute('data-sidebar') === 'node-description') { + // Beschreibungs-Panel anzeigen + panel.classList.remove('hidden'); + + // Titel und Beschreibung aktualisieren + const titleElement = panel.querySelector('[data-node-title]'); + const descriptionElement = panel.querySelector('[data-node-description]'); + + if (titleElement) { + titleElement.textContent = node.data('name'); + } + + if (descriptionElement) { + descriptionElement.innerHTML = formatDescription(node.data('description') || 'Keine Beschreibung verfügbar.'); + } + } else { + // Andere Panels ausblenden + panel.classList.add('hidden'); + } + }); +} + +// Formatiert die Beschreibung mit etwas HTML-Markup +function formatDescription(text) { + return text + .replace(/\n/g, '
') + .replace(/\*\*(.*?)\*\*/g, '$1') + .replace(/\*(.*?)\*/g, '$1') + .replace(/`(.*?)`/g, '$1'); +} + +// Setzt die Auswahl zurück +function resetSelection(cy) { + // Alle Stile zurücksetzen + cy.nodes().forEach(n => { + n.removeStyle(); + }); + + cy.edges().forEach(e => { + e.removeStyle(); + }); + + // Kein Knoten ausgewählt + window.mindmapInstance.selectedNode = null; + + // Info-Panel ausblenden + const nodeInfoPanel = document.getElementById('node-info-panel'); + if (nodeInfoPanel) { + nodeInfoPanel.classList.remove('visible'); + } + + // Standard-Seitenleisten-Panels anzeigen + document.querySelectorAll('[data-sidebar]').forEach(panel => { + if (panel.getAttribute('data-sidebar') === 'node-description') { + panel.classList.add('hidden'); + } else { + panel.classList.remove('hidden'); + } }); } /** - * Liefert die Standard-Stile für die Mindmap - * @param {boolean} darkMode - Ob der Dark Mode aktiv ist - * @returns {Array} Array von Cytoscape-Stilen + * Gibt die Stile für das neuronale Netzwerk-Design zurück + * @returns {Array} Stildefinitionen für Cytoscape */ -function getDefaultStyles(darkMode = document.documentElement.classList.contains('dark')) { +function getNeuralNetworkStyles() { return [ + // Neuronen (Knoten) { selector: 'node', style: { - 'background-color': 'data(color)', 'label': 'data(name)', - 'width': 40, - 'height': 40, - 'font-size': 12, 'text-valign': 'bottom', 'text-halign': 'center', - 'text-margin-y': 8, - 'color': darkMode ? '#f1f5f9' : '#334155', - 'text-background-color': darkMode ? 'rgba(30, 41, 59, 0.8)' : 'rgba(241, 245, 249, 0.8)', - 'text-background-opacity': 0.8, - 'text-background-padding': '2px', - 'text-background-shape': 'roundrectangle', - 'text-wrap': 'ellipsis', - 'text-max-width': '100px' - } - }, - { - selector: 'node[?isRoot]', - style: { - 'width': 60, - 'height': 60, - 'font-size': 14, - 'font-weight': 'bold', - 'text-background-opacity': 0.9, - 'text-background-color': '#4299E1' + 'color': '#ffffff', + 'text-outline-width': 2, + 'text-outline-color': '#0a0e19', + 'text-outline-opacity': 0.9, + 'font-size': 10, + 'text-margin-y': 6, + 'width': 'mapData(neuronSize, 3, 10, 15, 40)', + 'height': 'mapData(neuronSize, 3, 10, 15, 40)', + 'background-color': 'data(color)', + 'background-opacity': 0.9, + 'border-width': 0, + 'shape': 'ellipse', + 'shadow-blur': 'mapData(neuronActivity, 0.3, 1, 5, 15)', + 'shadow-color': 'data(color)', + 'shadow-opacity': 0.6, + 'shadow-offset-x': 0, + 'shadow-offset-y': 0, + 'text-wrap': 'wrap', + 'text-max-width': 100, + 'transition-property': 'background-color, shadow-color, shadow-opacity, shadow-blur', + 'transition-duration': '0.3s' } }, + // Synapsen (Kanten) { selector: 'edge', style: { - 'width': 2, - 'line-color': darkMode ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)', - 'target-arrow-color': darkMode ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)', 'curve-style': 'bezier', - 'target-arrow-shape': 'triangle' + 'line-color': '#8a8aaa', + 'width': 'mapData(strength, 0.2, 0.8, 0.8, 2)', + 'line-opacity': 'mapData(strength, 0.2, 0.8, 0.4, 0.7)', + 'target-arrow-shape': 'none', // Keine Pfeilspitzen bei Neuronen + 'target-arrow-color': '#8a8aaa', + 'arrow-scale': 0.6, + 'transition-property': 'line-color, line-opacity, width', + 'transition-duration': '0.3s' } }, + // Schwache Verbindungen { - selector: 'node.selected', + selector: 'edge[strength <= 0.4]', style: { - 'background-color': 'data(color)', - 'border-width': 3, - 'border-color': '#8b5cf6', + 'line-style': 'dotted' + } + }, + // Mittlere Verbindungen + { + selector: 'edge[strength > 0.4][strength <= 0.6]', + style: { + 'line-style': 'dashed' + } + }, + // Starke Verbindungen + { + selector: 'edge[strength > 0.6]', + style: { + 'line-style': 'solid' + } + }, + // Wurzelknoten (speziell gestaltet) + { + selector: 'node[isRoot]', + style: { + 'font-size': 12, + 'font-weight': 'bold', 'width': 50, 'height': 50, - 'font-size': 14, - 'font-weight': 'bold', - 'text-background-color': '#8b5cf6', - 'text-background-opacity': 0.9 + 'background-color': '#6366f1', + 'shadow-blur': 20, + 'shadow-color': '#6366f1', + 'shadow-opacity': 0.8, + 'text-margin-y': 8 + } + }, + // Hover-Effekt für Knoten + { + selector: 'node:hover', + style: { + 'shadow-blur': 20, + 'shadow-opacity': 0.9, + 'transition-property': 'shadow-opacity, shadow-blur', + 'transition-duration': '0.2s' + } + }, + // Hover-Effekt für Kanten + { + selector: 'edge:hover', + style: { + 'line-color': '#a78bfa', + 'line-opacity': 0.8, + 'width': 2 } } ]; -} - -class MindMap { - constructor(selector, options = {}) { - // Standardoptionen festlegen - this.options = Object.assign({ - // Standard-Basisoptionen - editable: false, // Ist die Mindmap editierbar? - isUserLoggedIn: false, // Ist der Benutzer angemeldet? - isPublicMap: true, // Handelt es sich um die öffentliche Mindmap? - initialZoom: 1, // Anfängliche Zoom-Stufe - fitViewOnInit: true, // Passt die Ansicht automatisch an - minZoom: 0.2, // Minimale Zoom-Stufe - maxZoom: 3, // Maximale Zoom-Stufe - // Farbpalette für verschiedene Elemente - colorPalette: { - node: { - default: '#8b5cf6', // Standard-Knotenfarbe - selected: '#7c3aed', // Farbe für ausgewählte Knoten - hover: '#6d28d9' // Farbe für Hover-Effekt - }, - edge: { - default: '#8b5cf6', // Standard-Kantenfarbe - selected: '#7c3aed', // Farbe für ausgewählte Kanten - hover: '#6d28d9' // Farbe für Hover-Effekt - }, - text: { - default: '#f3f4f6', // Standard-Textfarbe - dark: '#1f2937', // Dunkle Textfarbe (für helle Hintergründe) - light: '#f9fafb' // Helle Textfarbe (für dunkle Hintergründe) - }, - background: { - dark: '#111827', // Dunkler Hintergrund - light: '#f9fafb' // Heller Hintergrund - } - }, - // Anpassbare Funktionen - callbacks: { - onNodeClick: null, // Callback für Knotenklick - onEdgeClick: null, // Callback für Kantenklick - onViewportChange: null, // Callback für Änderung der Ansicht - onSelectionChange: null, // Callback für Änderung der Auswahl - onLoad: null // Callback nach dem Laden der Mindmap - } - }, options); - - // Container-Element - this.container = document.querySelector(selector); - if (!this.container) { - console.error(`Container mit Selektor '${selector}' nicht gefunden`); - return; - } - - // Prüfen, ob der Benutzer angemeldet ist - this.isUserLoggedIn = document.body.classList.contains('user-logged-in') || this.options.isUserLoggedIn; - - // Wenn der Benutzer angemeldet ist und es sich um die öffentliche Mindmap handelt, - // wird die Editierbarkeit aktiviert - if (this.isUserLoggedIn && this.options.isPublicMap) { - this.options.editable = true; - } - - // Initialisiere Cytoscape - this.initCytoscape(); - - // Füge Bearbeiten-Funktionalität hinzu, wenn editierbar - if (this.options.editable) { - this.initEditableMode(); - } - - // Lade Daten basierend auf dem Typ der Mindmap - if (this.options.isPublicMap) { - this.loadPublicMindmap(); - } else if (this.options.userMindmapId) { - this.loadUserMindmap(this.options.userMindmapId); - } - - // Initialisiere UI-Elemente - this.initUI(); - - // Event-Listener-Initialisierung - this.initEventListeners(); - - // Flash-Message-System - this.flashContainer = null; - this.initFlashMessages(); - } - - // ... existing code ... - - // Initialisiert die Bearbeitungsmodi für die Mindmap - initEditableMode() { - // Toolbar für Bearbeitungsmodus hinzufügen - this.addEditToolbar(); - - // Kontextmenü-Funktionalität für Knoten - this.cy.on('cxttap', 'node', (evt) => { - const node = evt.target; - const position = evt.renderedPosition; - - // Zeige Kontextmenü - this.showNodeContextMenu(node, position); - }); - - // Doppelklick-Funktion für das Hinzufügen neuer Knoten - this.cy.on('dblclick', (evt) => { - // Nur auf Hintergrund reagieren, nicht auf Knoten - if (evt.target === this.cy) { - const position = evt.position; - this.showAddNodeDialog(position); - } - }); - - // Kontextmenü-Schließen bei Klick außerhalb - document.addEventListener('click', (e) => { - const contextMenu = document.getElementById('context-menu'); - if (contextMenu && !contextMenu.contains(e.target)) { - contextMenu.remove(); - } - }); - } - - // Zeigt ein Kontextmenü für einen Knoten an - showNodeContextMenu(node, position) { - // Entferne vorhandenes Kontextmenü - const existingMenu = document.getElementById('context-menu'); - if (existingMenu) existingMenu.remove(); - - // Erstelle neues Kontextmenü - const contextMenu = document.createElement('div'); - contextMenu.id = 'context-menu'; - contextMenu.style.position = 'absolute'; - contextMenu.style.left = `${position.x}px`; - contextMenu.style.top = `${position.y}px`; - contextMenu.style.zIndex = '1000'; - - // Menü-Elemente - const menuItems = [ - { label: 'Gedanken anzeigen', icon: 'fas fa-brain', action: () => this.showThoughtsForNode(node) }, - { label: 'Neuen Gedanken erstellen', icon: 'fas fa-plus-circle', action: () => this.createThoughtForNode(node) }, - { label: 'Notiz hinzufügen', icon: 'fas fa-sticky-note', action: () => this.addNoteToNode(node) }, - { label: 'Knoten bearbeiten', icon: 'fas fa-edit', action: () => this.editNode(node) }, - { label: 'Verbindung erstellen', icon: 'fas fa-link', action: () => this.startEdgeCreation(node) }, - { label: 'Aus Mindmap entfernen', icon: 'fas fa-trash-alt', action: () => this.removeNodeFromMap(node) } - ]; - - // Menü erstellen - menuItems.forEach(item => { - const menuItem = document.createElement('div'); - menuItem.className = 'menu-item'; - menuItem.innerHTML = ` ${item.label}`; - menuItem.addEventListener('click', () => { - item.action(); - contextMenu.remove(); - }); - contextMenu.appendChild(menuItem); - }); - - // Anhängen an Body (außerhalb des Cytoscape-Containers) - document.body.appendChild(contextMenu); - - // Stellen Sie sicher, dass das Kontextmenü vollständig sichtbar ist - const menuRect = contextMenu.getBoundingClientRect(); - const windowWidth = window.innerWidth; - const windowHeight = window.innerHeight; - - if (menuRect.right > windowWidth) { - contextMenu.style.left = `${position.x - menuRect.width}px`; - } - - if (menuRect.bottom > windowHeight) { - contextMenu.style.top = `${position.y - menuRect.height}px`; - } - } - - // Fügt die Edit-Toolbar zur Mindmap hinzu - addEditToolbar() { - const toolbar = document.querySelector('.mindmap-toolbar'); - if (!toolbar) return; - - // Trennlinie - const separator = document.createElement('div'); - separator.className = 'border-l h-6 mx-2 opacity-20'; - toolbar.appendChild(separator); - - // Bearbeiten-Buttons - const editButtons = [ - { id: 'add-node-btn', icon: 'fa-plus', text: 'Knoten hinzufügen', action: () => this.showAddNodeDialog() }, - { id: 'save-layout-btn', icon: 'fa-save', text: 'Layout speichern', action: () => this.saveCurrentLayout() } - ]; - - editButtons.forEach(btn => { - const button = document.createElement('button'); - button.id = btn.id; - button.className = 'mindmap-action-btn edit-btn'; - button.innerHTML = `${btn.text}`; - button.addEventListener('click', btn.action); - toolbar.appendChild(button); - }); - - // Animation für die Edit-Buttons - const editBtns = document.querySelectorAll('.edit-btn'); - editBtns.forEach(btn => { - btn.style.opacity = '0'; - btn.style.transform = 'translateY(10px)'; - - setTimeout(() => { - btn.style.transition = 'all 0.3s ease'; - btn.style.opacity = '1'; - btn.style.transform = 'translateY(0)'; - }, 100); - }); - } - - // Zeigt den Dialog zum Hinzufügen eines neuen Knotens - showAddNodeDialog(position = null) { - // Entferne bestehende Dialoge - const existingDialog = document.getElementById('add-node-dialog'); - if (existingDialog) existingDialog.remove(); - - // Erstelle Dialog - const dialog = document.createElement('div'); - dialog.id = 'add-node-dialog'; - dialog.className = 'fixed inset-0 flex items-center justify-center z-50'; - dialog.innerHTML = ` -
-
-

Neuen Knoten hinzufügen

-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- `; - - // Füge Dialog zum Body hinzu - document.body.appendChild(dialog); - - // Animation für den Dialog - const dialogContent = dialog.querySelector('.bg-slate-800'); - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => { - dialogContent.style.transition = 'all 0.3s ease'; - dialogContent.style.opacity = '1'; - dialogContent.style.transform = 'scale(1)'; - }, 10); - - // Event-Listener für Abbrechen - document.getElementById('cancel-add-node').addEventListener('click', () => { - // Animation für das Schließen - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => dialog.remove(), 300); - }); - - // Event-Listener für Overlay-Klick - dialog.querySelector('.fixed.inset-0.bg-black').addEventListener('click', () => { - // Animation für das Schließen - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => dialog.remove(), 300); - }); - - // Event-Listener für Formular - document.getElementById('add-node-form').addEventListener('submit', (e) => { - e.preventDefault(); - - const name = document.getElementById('node-name').value; - const description = document.getElementById('node-description').value; - const color = document.getElementById('node-color').value; - - if (!name.trim()) { - this.showFlash('Bitte geben Sie einen Namen für den Knoten ein', 'error'); - return; - } - - // Knoten hinzufügen - this.addNodeToMindmap({ - name, - description, - color_code: color, - position - }); - - // Dialog schließen - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => dialog.remove(), 300); - }); - - // Fokus auf das Name-Feld - setTimeout(() => document.getElementById('node-name').focus(), 100); - } - - // Fügt einen neuen Knoten zur Mindmap hinzu - addNodeToMindmap(nodeData) { - // API-Anfrage vorbereiten - const data = { - name: nodeData.name, - description: nodeData.description || '', - color_code: nodeData.color_code || '#8b5cf6' - }; - - // Position hinzufügen, falls vorhanden - if (nodeData.position) { - data.x_position = nodeData.position.x; - data.y_position = nodeData.position.y; - } - - // API-Anfrage zum Hinzufügen des Knotens - fetch('/api/mindmap/public/add_node', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(data) - }) - .then(response => { - if (!response.ok) { - throw new Error('Netzwerkantwort war nicht ok'); - } - return response.json(); - }) - .then(data => { - if (data.success) { - // Hinzufügen des neuen Knotens zum Graphen - this.cy.add({ - group: 'nodes', - data: { - id: `node_${data.node_id}`, - name: nodeData.name, - description: nodeData.description || '', - color: nodeData.color_code - }, - position: nodeData.position || { x: 0, y: 0 } - }); - - // Flash-Nachricht anzeigen - this.showFlash('Knoten erfolgreich hinzugefügt', 'success'); - - // Ansicht anpassen - this.cy.fit(); - } else { - this.showFlash('Fehler beim Hinzufügen des Knotens: ' + (data.error || 'Unbekannter Fehler'), 'error'); - } - }) - .catch(error => { - console.error('Fehler beim Hinzufügen des Knotens:', error); - this.showFlash('Fehler beim Hinzufügen des Knotens', 'error'); - }); - } - - // Entfernt einen Knoten aus der Mindmap - removeNodeFromMap(node) { - if (!confirm('Möchten Sie diesen Knoten wirklich aus der Mindmap entfernen?')) { - return; - } - - const nodeId = node.id().split('_')[1]; // "node_123" => "123" - - // API-Anfrage zum Entfernen des Knotens - fetch(`/api/mindmap/public/remove_node/${nodeId}`, { - method: 'DELETE' - }) - .then(response => { - if (!response.ok) { - throw new Error('Netzwerkantwort war nicht ok'); - } - return response.json(); - }) - .then(data => { - if (data.success) { - // Knoten aus dem Graphen entfernen - this.cy.remove(node); - - // Flash-Nachricht anzeigen - this.showFlash('Knoten erfolgreich entfernt', 'success'); - } else { - this.showFlash('Fehler beim Entfernen des Knotens: ' + (data.error || 'Unbekannter Fehler'), 'error'); - } - }) - .catch(error => { - console.error('Fehler beim Entfernen des Knotens:', error); - this.showFlash('Fehler beim Entfernen des Knotens', 'error'); - }); - } - - // Speichert das aktuelle Layout der Mindmap - saveCurrentLayout() { - // Sammle alle Knotenpositionen - const nodePositions = []; - this.cy.nodes().forEach(node => { - const idParts = node.id().split('_'); - if (idParts.length === 2 && idParts[0] === 'node') { - nodePositions.push({ - node_id: parseInt(idParts[1]), - x_position: node.position('x'), - y_position: node.position('y') - }); - } - }); - - // API-Anfrage zum Speichern des Layouts - fetch('/api/mindmap/public/update_layout', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ positions: nodePositions }) - }) - .then(response => { - if (!response.ok) { - throw new Error('Netzwerkantwort war nicht ok'); - } - return response.json(); - }) - .then(data => { - if (data.success) { - this.showFlash('Layout erfolgreich gespeichert', 'success'); - } else { - this.showFlash('Fehler beim Speichern des Layouts: ' + (data.error || 'Unbekannter Fehler'), 'error'); - } - }) - .catch(error => { - console.error('Fehler beim Speichern des Layouts:', error); - this.showFlash('Fehler beim Speichern des Layouts', 'error'); - }); - } - - // Zeigt den Dialog zum Bearbeiten eines Knotens - editNode(node) { - // Entferne bestehende Dialoge - const existingDialog = document.getElementById('edit-node-dialog'); - if (existingDialog) existingDialog.remove(); - - // Knotendaten holen - const nodeData = node.data(); - - // Erstelle Dialog - const dialog = document.createElement('div'); - dialog.id = 'edit-node-dialog'; - dialog.className = 'fixed inset-0 flex items-center justify-center z-50'; - dialog.innerHTML = ` -
-
-

Knoten bearbeiten

-
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- `; - - // Füge Dialog zum Body hinzu - document.body.appendChild(dialog); - - // Animation für den Dialog - const dialogContent = dialog.querySelector('.bg-slate-800'); - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => { - dialogContent.style.transition = 'all 0.3s ease'; - dialogContent.style.opacity = '1'; - dialogContent.style.transform = 'scale(1)'; - }, 10); - - // Event-Listener für Abbrechen - document.getElementById('cancel-edit-node').addEventListener('click', () => { - // Animation für das Schließen - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => dialog.remove(), 300); - }); - - // Event-Listener für Overlay-Klick - dialog.querySelector('.fixed.inset-0.bg-black').addEventListener('click', () => { - // Animation für das Schließen - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => dialog.remove(), 300); - }); - - // Event-Listener für Formular - document.getElementById('edit-node-form').addEventListener('submit', (e) => { - e.preventDefault(); - - const name = document.getElementById('node-name').value; - const description = document.getElementById('node-description').value; - const color = document.getElementById('node-color').value; - - if (!name.trim()) { - this.showFlash('Bitte geben Sie einen Namen für den Knoten ein', 'error'); - return; - } - - // Knoten aktualisieren - this.updateNode(node, { - name, - description, - color_code: color - }); - - // Dialog schließen - dialogContent.style.opacity = '0'; - dialogContent.style.transform = 'scale(0.9)'; - setTimeout(() => dialog.remove(), 300); - }); - - // Fokus auf das Name-Feld - setTimeout(() => document.getElementById('node-name').focus(), 100); - } - - // Aktualisiert einen Knoten in der Mindmap - updateNode(node, nodeData) { - const nodeId = node.id().split('_')[1]; // "node_123" => "123" - - // API-Anfrage zum Aktualisieren des Knotens - fetch(`/api/mindmap/public/update_node/${nodeId}`, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - name: nodeData.name, - description: nodeData.description, - color_code: nodeData.color_code - }) - }) - .then(response => { - if (!response.ok) { - throw new Error('Netzwerkantwort war nicht ok'); - } - return response.json(); - }) - .then(data => { - if (data.success) { - // Aktualisiere Knotendaten im Graph - node.data('name', nodeData.name); - node.data('description', nodeData.description); - node.data('color', nodeData.color_code); - - // Aktualisiere Darstellung - this.cy.style() - .selector(`#${node.id()}`) - .style({ - 'background-color': nodeData.color_code - }) - .update(); - - // Flash-Nachricht anzeigen - this.showFlash('Knoten erfolgreich aktualisiert', 'success'); - } else { - this.showFlash('Fehler beim Aktualisieren des Knotens: ' + (data.error || 'Unbekannter Fehler'), 'error'); - } - }) - .catch(error => { - console.error('Fehler beim Aktualisieren des Knotens:', error); - this.showFlash('Fehler beim Aktualisieren des Knotens', 'error'); - }); - } - - // Fügt eine Notiz zu einem Knoten hinzu - addNoteToNode(node) { - // Implementierung für das Hinzufügen von Notizen - // Ähnlich wie bei editNode, aber mit anderen Feldern - } - - // Startet den Prozess zum Erstellen einer Verbindung - startEdgeCreation(node) { - // Implementierung für das Erstellen von Verbindungen - } - - // Zeigt Gedanken für einen Knoten an - showThoughtsForNode(node) { - const nodeId = node.id().split('_')[1]; // "node_123" => "123" - - // Wir verwenden die fetchThoughtsForNode-Methode, die wir bereits implementiert haben - this.fetchThoughtsForNode(nodeId) - .then(thoughts => { - // Nur fortfahren, wenn wir tatsächlich Gedanken haben - if (thoughts.length === 0) { - this.showFlash('Keine Gedanken für diesen Knoten gefunden', 'info'); - return; - } - - // Erstelle einen Gedanken-Viewer, wenn er nicht existiert - let thoughtsViewer = document.getElementById('thoughts-viewer'); - if (!thoughtsViewer) { - thoughtsViewer = document.createElement('div'); - thoughtsViewer.id = 'thoughts-viewer'; - thoughtsViewer.className = 'fixed inset-0 flex items-center justify-center z-50'; - thoughtsViewer.innerHTML = ` -
-
-
-

Gedanken zu:

- -
-
-
- `; - document.body.appendChild(thoughtsViewer); - - // Event-Listener für Schließen-Button - document.getElementById('close-thoughts').addEventListener('click', () => { - // Animation für das Schließen - const content = thoughtsViewer.querySelector('.thoughts-content'); - const backdrop = thoughtsViewer.querySelector('.thoughts-backdrop'); - - content.style.transform = 'scale(0.9)'; - content.style.opacity = '0'; - backdrop.style.opacity = '0'; - - setTimeout(() => thoughtsViewer.remove(), 300); - }); - - // Event-Listener für Backdrop-Klick - thoughtsViewer.querySelector('.thoughts-backdrop').addEventListener('click', () => { - document.getElementById('close-thoughts').click(); - }); - } - - // Aktualisiere den Titel mit dem Knotennamen - thoughtsViewer.querySelector('.node-name').textContent = node.data('name'); - - // Container für die Gedanken - const thoughtsContainer = thoughtsViewer.querySelector('.thoughts-container'); - thoughtsContainer.innerHTML = ''; - - // Gedanken rendern - this.renderThoughts(thoughts, thoughtsContainer); - - // Animation für das Öffnen - const content = thoughtsViewer.querySelector('.thoughts-content'); - const backdrop = thoughtsViewer.querySelector('.thoughts-backdrop'); - - content.style.transform = 'scale(0.9)'; - content.style.opacity = '0'; - backdrop.style.opacity = '0'; - - setTimeout(() => { - content.style.transition = 'all 0.3s ease'; - backdrop.style.transition = 'opacity 0.3s ease'; - content.style.transform = 'scale(1)'; - content.style.opacity = '1'; - backdrop.style.opacity = '1'; - }, 10); - }); - } - - // Rendert die Gedanken in der UI mit Animationen - renderThoughts(thoughts, container) { - if (!container) return; - - container.innerHTML = ''; - - // Animation delay counter - let delay = 0; - - thoughts.forEach(thought => { - const thoughtCard = document.createElement('div'); - thoughtCard.className = 'thought-card mb-4 bg-slate-700/50 rounded-lg overflow-hidden border border-slate-600/50 transition-all duration-300 hover:border-purple-500/30'; - thoughtCard.setAttribute('data-id', thought.id); - thoughtCard.style.opacity = '0'; - thoughtCard.style.transform = 'translateY(20px)'; - - const cardColor = thought.color_code || this.colorPalette.default; - - thoughtCard.innerHTML = ` -
-

${thought.title}

-
- ${new Date(thought.created_at).toLocaleDateString('de-DE')} - ${thought.author ? `${thought.author.username}` : ''} -
-
-
-

${thought.abstract || thought.content.substring(0, 150) + '...'}

-
- - `; - - // Animation-Effekt mit Verzögerung für jede Karte - setTimeout(() => { - thoughtCard.style.transition = 'all 0.5s ease'; - thoughtCard.style.opacity = '1'; - thoughtCard.style.transform = 'translateY(0)'; - }, delay); - delay += 100; // Jede Karte erscheint mit 100ms Verzögerung - - // Event-Listener für Klick auf Gedanken - thoughtCard.addEventListener('click', (e) => { - // Verhindern, dass der Link-Klick den Kartenklick auslöst - if (e.target.tagName === 'A' || e.target.closest('a')) return; - window.location.href = `/thoughts/${thought.id}`; - }); - - // Hover-Animation für Karten - thoughtCard.addEventListener('mouseenter', () => { - thoughtCard.style.transform = 'translateY(-5px)'; - thoughtCard.style.boxShadow = '0 10px 25px rgba(0, 0, 0, 0.2)'; - }); - - thoughtCard.addEventListener('mouseleave', () => { - thoughtCard.style.transform = 'translateY(0)'; - thoughtCard.style.boxShadow = 'none'; - }); - - container.appendChild(thoughtCard); - }); - } - - // Flash-Nachrichten mit Animationen - showFlash(message, type = 'info') { - if (!this.flashContainer) { - this.flashContainer = document.createElement('div'); - this.flashContainer.className = 'fixed top-4 right-4 z-50 flex flex-col gap-2'; - document.body.appendChild(this.flashContainer); - } - - const flash = document.createElement('div'); - flash.className = `flash-message p-3 rounded-lg shadow-lg flex items-center gap-3 max-w-xs text-white`; - - // Verschiedene Stile je nach Typ - let backgroundColor, icon; - switch (type) { - case 'success': - backgroundColor = 'bg-green-500'; - icon = 'fa-check-circle'; - break; - case 'error': - backgroundColor = 'bg-red-500'; - icon = 'fa-exclamation-circle'; - break; - case 'warning': - backgroundColor = 'bg-yellow-500'; - icon = 'fa-exclamation-triangle'; - break; - default: - backgroundColor = 'bg-blue-500'; - icon = 'fa-info-circle'; - } - - flash.classList.add(backgroundColor); - - flash.innerHTML = ` -
-
${message}
- - `; - - // Füge den Flash zum Container hinzu - this.flashContainer.appendChild(flash); - - // Einblend-Animation - flash.style.opacity = '0'; - flash.style.transform = 'translateX(20px)'; - - setTimeout(() => { - flash.style.transition = 'all 0.3s ease'; - flash.style.opacity = '1'; - flash.style.transform = 'translateX(0)'; - }, 10); - - // Schließen-Button - const closeBtn = flash.querySelector('.flash-close'); - closeBtn.addEventListener('click', () => { - // Ausblend-Animation - flash.style.opacity = '0'; - flash.style.transform = 'translateX(20px)'; - - setTimeout(() => { - flash.remove(); - }, 300); - }); - - // Automatisches Ausblenden nach 5 Sekunden - setTimeout(() => { - if (flash.parentNode) { - flash.style.opacity = '0'; - flash.style.transform = 'translateX(20px)'; - - setTimeout(() => { - if (flash.parentNode) flash.remove(); - }, 300); - } - }, 5000); - - return flash; - } -} \ No newline at end of file +} \ No newline at end of file diff --git a/static/js/mindmap-interaction.js b/static/js/mindmap-interaction.js index ef22ee0..27898b5 100644 --- a/static/js/mindmap-interaction.js +++ b/static/js/mindmap-interaction.js @@ -15,42 +15,269 @@ document.addEventListener('DOMContentLoaded', function() { // Direkten Event-Listener für Knotenauswahl einrichten setupNodeSelectionListener(); + + // Neuronales Netzwerk-Hintergrund-Effekt aktivieren + setupNeuralNetworkEffect(); }); +// Erzeugt subtile Hintergrundeffekte für neuronales Netzwerk +function setupNeuralNetworkEffect() { + const cyContainer = document.getElementById('cy'); + if (!cyContainer) return; + + // Dendrite Animation CSS + const dendriteStyle = document.createElement('style'); + dendriteStyle.textContent = ` + .neuron-pulse { + position: absolute; + border-radius: 50%; + background: radial-gradient(circle, rgba(139, 92, 246, 0.1) 0%, transparent 70%); + pointer-events: none; + z-index: 0; + opacity: 0; + animation: neuronPulse 6s ease-in-out infinite; + transform: translate(-50%, -50%); + } + + @keyframes neuronPulse { + 0%, 100% { opacity: 0; transform: translate(-50%, -50%) scale(0.7); } + 50% { opacity: 0.8; transform: translate(-50%, -50%) scale(1.2); } + } + + .synapse-line { + position: absolute; + height: 1px; + background: linear-gradient(90deg, transparent, rgba(139, 92, 246, 0.3), transparent); + pointer-events: none; + z-index: 0; + opacity: 0; + transform-origin: 0% 50%; + animation: synapseFlow 8s ease-in-out infinite; + } + + @keyframes synapseFlow { + 0%, 100% { opacity: 0; } + 50% { opacity: 0.5; } + } + `; + document.head.appendChild(dendriteStyle); + + // Zufällige Pulsierende Dendrite-Effekte + setInterval(() => { + if (Math.random() > 0.7) { + const pulse = document.createElement('div'); + pulse.className = 'neuron-pulse'; + + // Zufällige Größe und Position + const size = Math.random() * 200 + 100; + pulse.style.width = `${size}px`; + pulse.style.height = `${size}px`; + pulse.style.left = `${Math.random() * 100}%`; + pulse.style.top = `${Math.random() * 100}%`; + + // Animation-Eigenschaften variieren + pulse.style.animationDuration = `${Math.random() * 4 + 3}s`; + pulse.style.animationDelay = `${Math.random() * 2}s`; + + cyContainer.appendChild(pulse); + + // Element nach Animation entfernen + setTimeout(() => pulse.remove(), 7000); + } + + // Zufällige Synapse-Linien-Effekte + if (Math.random() > 0.8) { + const synapse = document.createElement('div'); + synapse.className = 'synapse-line'; + + // Zufällige Position und Größe + const startX = Math.random() * 100; + const startY = Math.random() * 100; + const length = Math.random() * 200 + 50; + const angle = Math.random() * 360; + + synapse.style.width = `${length}px`; + synapse.style.left = `${startX}%`; + synapse.style.top = `${startY}%`; + synapse.style.transform = `rotate(${angle}deg)`; + + // Animation-Eigenschaften + synapse.style.animationDuration = `${Math.random() * 3 + 5}s`; + synapse.style.animationDelay = `${Math.random() * 2}s`; + + cyContainer.appendChild(synapse); + + // Element nach Animation entfernen + setTimeout(() => synapse.remove(), 9000); + } + }, 800); +} + // Richtet grundlegende statische Interaktionen ein function setupStaticInteractions() { - // Vergrößert die Mindmap auf Vollbildmodus, wenn der entsprechende Button geklickt wird - const fullscreenBtn = document.getElementById('fullscreen-btn'); - if (fullscreenBtn) { - fullscreenBtn.addEventListener('click', toggleFullscreen); - } - // Initialisiert die Hover-Effekte für die Seitenleisten-Panels initializePanelEffects(); + + // Prevent default Zoom bei CTRL + Mausrad + document.addEventListener('wheel', function(e) { + if (e.ctrlKey) { + e.preventDefault(); + } + }, { passive: false }); + + // Initialisiert verbesserten Zoom-Handler direkt nach dem Laden + initializeZoomHandler(); } // Richtet erweiterte Interaktionen mit der geladenen Mindmap ein function setupInteractionEnhancements() { console.log('Mindmap geladen - verbesserte Interaktionen werden eingerichtet'); - // Zugriff auf die Mindmap-Instanz - const mindmap = window.mindmapInstance; - if (!mindmap) { - console.warn('Mindmap-Instanz nicht gefunden!'); + // Cytoscape-Instanz + const cy = window.cy; + if (!cy) { + console.warn('Cytoscape-Instanz nicht gefunden!'); return; } - // Verbesserte Zoom-Kontrollen - setupZoomControls(mindmap); + // Hover-Effekte für Knoten + cy.on('mouseover', 'node', function(evt) { + const node = evt.target; + + // Nur anwenden, wenn der Knoten nicht ausgewählt ist + if (!node.selected()) { + node.style({ + 'shadow-opacity': 0.8, + 'shadow-blur': 'mapData(neuronActivity, 0.3, 1, 10, 20)', + 'background-opacity': 1 + }); + } + + // Verbundene Kanten hervorheben + node.connectedEdges().style({ + 'line-opacity': 0.7, + 'width': 'mapData(strength, 0.2, 0.8, 1.5, 2.5)' + }); + }); + + cy.on('mouseout', 'node', function(evt) { + const node = evt.target; + + // Nur zurücksetzen, wenn nicht ausgewählt + if (!node.selected()) { + node.removeStyle(); + } + + // Verbundene Kanten zurücksetzen, wenn nicht mit ausgewähltem Knoten verbunden + node.connectedEdges().forEach(edge => { + const sourceSelected = edge.source().selected(); + const targetSelected = edge.target().selected(); + + if (!sourceSelected && !targetSelected) { + edge.removeStyle(); + } + }); + }); // Verhindere, dass der Browser die Seite scrollt, wenn über der Mindmap gezoomt wird preventScrollWhileZooming(); // Tastaturkürzel für Mindmap-Interaktionen - setupKeyboardShortcuts(mindmap); - - // Verbesserte Touch-Gesten für mobile Geräte - setupTouchInteractions(mindmap); + setupKeyboardShortcuts(cy); +} + +// Initialisiert speziellen Zoom-Handler für sanften Zoom +function initializeZoomHandler() { + // Auf das Laden der Mindmap warten + document.addEventListener('mindmap-loaded', function() { + if (!window.cy) return; + + const cy = window.cy; + + // Laufenden AnimationsFrame-Request speichern + let zoomAnimationFrame = null; + let targetZoom = cy.zoom(); + let currentZoom = targetZoom; + let zoomCenter = { x: 0, y: 0 }; + let zoomTime = 0; + + // Aktuellen Zoom überwachen und sanft anpassen + function updateZoom() { + // Sanfter Übergang zum Ziel-Zoom-Level + zoomTime += 0.08; + + // Easing-Funktion für flüssigere Bewegung + const easedProgress = 1 - Math.pow(1 - Math.min(zoomTime, 1), 3); + + if (currentZoom !== targetZoom) { + currentZoom += (targetZoom - currentZoom) * easedProgress; + + // Zoom mit Position anwenden + cy.zoom({ + level: currentZoom, + position: zoomCenter + }); + + // Loop fortsetzen, bis wir sehr nahe am Ziel sind + if (Math.abs(currentZoom - targetZoom) > 0.001 && zoomTime < 1) { + zoomAnimationFrame = requestAnimationFrame(updateZoom); + } else { + // Endgültigen Zoom setzen, um sicherzustellen, dass wir genau das Ziel erreichen + cy.zoom({ + level: targetZoom, + position: zoomCenter + }); + zoomAnimationFrame = null; + } + } else { + zoomAnimationFrame = null; + } + } + + // Überschreibe den Standard-mousewheel-Handler von Cytoscape + cy.removeAllListeners('mousewheel'); + cy.on('mousewheel', function(e) { + e.preventDefault(); + + const delta = e.originalEvent.deltaY; + const mousePosition = e.position || e.cyPosition; + + // Glätten und Limitieren des Zoom-Faktors + const factor = delta > 0 ? 0.97 : 1.03; + + // Neues Zoom-Level berechnen mit Begrenzung + const maxZoom = cy.maxZoom() || 3; + const minZoom = cy.minZoom() || 0.2; + targetZoom = Math.min(maxZoom, Math.max(minZoom, cy.zoom() * factor)); + + // Position für Zoom setzen + zoomCenter = mousePosition; + + // Zeit zurücksetzen + zoomTime = 0; + + // Laufende Animation abbrechen und neue starten + if (zoomAnimationFrame) { + cancelAnimationFrame(zoomAnimationFrame); + } + + zoomAnimationFrame = requestAnimationFrame(updateZoom); + }); + + // Panning auch flüssiger gestalten + cy.on('pan', function() { + cy.style().selector('node').style({ + 'transition-property': 'none', + }).update(); + }); + + cy.on('panend', function() { + cy.style().selector('node').style({ + 'transition-property': 'background-color, shadow-color, shadow-opacity, shadow-blur', + 'transition-duration': '0.3s' + }).update(); + }); + }); } // Verhindert Browser-Scrolling während Zoom in der Mindmap @@ -58,114 +285,33 @@ function preventScrollWhileZooming() { const cyContainer = document.getElementById('cy'); if (cyContainer) { cyContainer.addEventListener('wheel', function(e) { - if (e.ctrlKey || e.metaKey) { - e.preventDefault(); // Verhindert Browser-Zoom bei Ctrl+Wheel - } + // Verhindern des Standard-Scrollens während des Zooms + e.preventDefault(); }, { passive: false }); } } -// Richtet verbesserte Zoom-Kontrollen ein -function setupZoomControls(mindmap) { - const zoomInBtn = document.getElementById('zoom-in-btn'); - const zoomOutBtn = document.getElementById('zoom-out-btn'); - const resetZoomBtn = document.getElementById('reset-btn'); - - if (zoomInBtn) { - zoomInBtn.addEventListener('click', function() { - mindmap.svg.transition() - .duration(300) - .call(mindmap.svg.zoom().scaleBy, 1.4); - }); - } - - if (zoomOutBtn) { - zoomOutBtn.addEventListener('click', function() { - mindmap.svg.transition() - .duration(300) - .call(mindmap.svg.zoom().scaleBy, 0.7); - }); - } - - if (resetZoomBtn) { - resetZoomBtn.addEventListener('click', function() { - mindmap.svg.transition() - .duration(500) - .call(mindmap.svg.zoom().transform, d3.zoomIdentity); - }); - } -} - -// Vollbildmodus umschalten -function toggleFullscreen() { - const mindmapContainer = document.querySelector('.mindmap-container'); - - if (!mindmapContainer) return; - - if (!document.fullscreenElement) { - // Vollbildmodus aktivieren - if (mindmapContainer.requestFullscreen) { - mindmapContainer.requestFullscreen(); - } else if (mindmapContainer.mozRequestFullScreen) { - mindmapContainer.mozRequestFullScreen(); - } else if (mindmapContainer.webkitRequestFullscreen) { - mindmapContainer.webkitRequestFullscreen(); - } else if (mindmapContainer.msRequestFullscreen) { - mindmapContainer.msRequestFullscreen(); - } - - // Icon ändern - const fullscreenBtn = document.getElementById('fullscreen-btn'); - if (fullscreenBtn) { - const icon = fullscreenBtn.querySelector('i'); - if (icon) { - icon.className = 'fa-solid fa-compress'; - } - fullscreenBtn.setAttribute('title', 'Vollbildmodus beenden'); - } - } else { - // Vollbildmodus beenden - if (document.exitFullscreen) { - document.exitFullscreen(); - } else if (document.mozCancelFullScreen) { - document.mozCancelFullScreen(); - } else if (document.webkitExitFullscreen) { - document.webkitExitFullscreen(); - } else if (document.msExitFullscreen) { - document.msExitFullscreen(); - } - - // Icon zurücksetzen - const fullscreenBtn = document.getElementById('fullscreen-btn'); - if (fullscreenBtn) { - const icon = fullscreenBtn.querySelector('i'); - if (icon) { - icon.className = 'fa-solid fa-expand'; - } - fullscreenBtn.setAttribute('title', 'Vollbildmodus'); - } - } -} - // Initialisiert Effekte für Seitenleisten-Panels function initializePanelEffects() { // Selektiert alle Panel-Elemente - const panels = document.querySelectorAll('[data-sidebar]'); + const panels = document.querySelectorAll('.sidebar-panel'); panels.forEach(panel => { // Hover-Effekt für Panels panel.addEventListener('mouseenter', function() { - this.classList.add('hover'); + this.style.transform = 'translateY(-5px)'; + this.style.boxShadow = '0 10px 25px rgba(0, 0, 0, 0.3), 0 0 15px rgba(139, 92, 246, 0.3)'; }); panel.addEventListener('mouseleave', function() { - this.classList.remove('hover'); + this.style.transform = ''; + this.style.boxShadow = ''; }); }); } // Richtet Tastaturkürzel für Mindmap-Interaktionen ein -function setupKeyboardShortcuts(mindmap) { +function setupKeyboardShortcuts(cy) { document.addEventListener('keydown', function(e) { // Nur fortfahren, wenn keine Texteingabe im Fokus ist if (document.activeElement.tagName === 'INPUT' || @@ -178,229 +324,249 @@ function setupKeyboardShortcuts(mindmap) { switch(e.key) { case '+': case '=': - // Einzoomen + // Einzoomen (sanfter) if (e.ctrlKey || e.metaKey) { e.preventDefault(); - mindmap.svg.transition() - .duration(300) - .call(mindmap.svg.zoom().scaleBy, 1.2); + smoothZoom(cy, 1.15, 400); } break; case '-': - // Auszoomen + // Auszoomen (sanfter) if (e.ctrlKey || e.metaKey) { e.preventDefault(); - mindmap.svg.transition() - .duration(300) - .call(mindmap.svg.zoom().scaleBy, 0.8); + smoothZoom(cy, 0.85, 400); } break; case '0': - // Zoom zurücksetzen + // Zoom auf Gesamtansicht if (e.ctrlKey || e.metaKey) { e.preventDefault(); - mindmap.svg.transition() - .duration(500) - .call(mindmap.svg.zoom().transform, d3.zoomIdentity); - } - break; - - case 'f': - // Vollbildmodus umschalten - if (e.ctrlKey || e.metaKey) { - e.preventDefault(); - toggleFullscreen(); + smoothFit(cy); } break; case 'Escape': // Ausgewählten Knoten abwählen - if (mindmap.selectedNode) { - mindmap.nodeClicked(null, mindmap.selectedNode); - } + cy.nodes().unselect(); + resetNodeSelection(); break; } }); } -// Richtet Touch-Gesten für mobile Geräte ein -function setupTouchInteractions(mindmap) { - const cyContainer = document.getElementById('cy'); - if (!cyContainer) return; +// Sanften Zoom mit Animation anwenden +function smoothZoom(cy, factor, duration = 400) { + const currentZoom = cy.zoom(); + const targetZoom = currentZoom * factor; - let touchStartX, touchStartY; - let touchStartTime; + // Mittelpunkt der Ansicht verwenden + const center = { + x: cy.width() / 2, + y: cy.height() / 2 + }; - // Touch-Start-Event - cyContainer.addEventListener('touchstart', function(e) { - if (e.touches.length === 1) { - touchStartX = e.touches[0].clientX; - touchStartY = e.touches[0].clientY; - touchStartTime = Date.now(); - } - }); - - // Touch-End-Event für Doppeltipp-Erkennung - cyContainer.addEventListener('touchend', function(e) { - if (Date.now() - touchStartTime < 300) { // Kurzer Tipp - const doubleTapDelay = 300; - const now = Date.now(); - - if (now - (window.lastTapTime || 0) < doubleTapDelay) { - // Doppeltipp erkannt - Zentriere Ansicht - mindmap.svg.transition() - .duration(500) - .call(mindmap.svg.zoom().transform, d3.zoomIdentity); - - e.preventDefault(); + // Sanftes Zoomen mit Animation + cy.animation({ + zoom: { + level: targetZoom, + position: center + }, + duration: duration, + easing: 'cubic-bezier(0.19, 1, 0.22, 1)' + }).play(); +} + +// Sanftes Anpassen der Ansicht mit Animation +function smoothFit(cy, padding = 50) { + cy.animation({ + fit: { + eles: cy.elements(), + padding: padding + }, + duration: 600, + easing: 'cubic-bezier(0.19, 1, 0.22, 1)' + }).play(); +} + +// Richtet den Event-Listener für die Knotenauswahl ein +function setupNodeSelectionListener() { + document.addEventListener('mindmap-loaded', function() { + if (!window.cy) return; + + window.cy.on('tap', 'node', function(evt) { + handleNodeSelection(evt.target); + }); + + window.cy.on('tap', function(evt) { + if (evt.target === window.cy) { + resetNodeSelection(); } - - window.lastTapTime = now; - } + }); }); } -// Richtet einen Event-Listener für die Knotenauswahl ein -function setupNodeSelectionListener() { - document.addEventListener('mindmap-node-selected', function(event) { - const node = event.detail; - if (node) { - console.log('Knoten ausgewählt:', node); - showNodeDescriptionSidebar(node); +// Verarbeitet die Knotenauswahl +function handleNodeSelection(node) { + if (!node) return; + + // Stelle sicher, dass nur dieser Knoten ausgewählt ist + window.cy.nodes().unselect(); + node.select(); + + // Speichere ausgewählten Knoten global + window.mindmapInstance.selectedNode = node; + + // Zeige Informationen in der Sidebar an + showNodeDescriptionSidebar(node); + + // Informationspanel aktualisieren + updateNodeInfoPanel(node); + + // Node zentrieren mit Animation + window.cy.animation({ + center: { + eles: node + }, + zoom: 1.3, + duration: 800, + easing: 'cubic-bezier(0.19, 1, 0.22, 1)' + }).play(); + + // Hervorhebung für den ausgewählten Knoten mit Leuchteffekt + node.style({ + 'background-opacity': 1, + 'shadow-opacity': 1, + 'shadow-blur': 20, + 'shadow-color': node.data('color') + }); + + // Verbindungen hervorheben + node.connectedEdges().style({ + 'line-color': '#a78bfa', + 'line-opacity': 0.7, + 'width': 2, + 'line-style': 'solid' + }); +} + +// Setzt die Knotenauswahl zurück +function resetNodeSelection() { + const nodeInfoPanel = document.getElementById('node-info-panel'); + if (nodeInfoPanel) { + nodeInfoPanel.classList.remove('visible'); + } + + showDefaultSidebar(); + + // Globale Referenz zurücksetzen + if (window.mindmapInstance) { + window.mindmapInstance.selectedNode = null; + } +} + +// Zeigt das Informationspanel für einen Knoten an +function updateNodeInfoPanel(node) { + const nodeInfoPanel = document.getElementById('node-info-panel'); + const nodeDescription = document.getElementById('node-description'); + const connectedNodes = document.getElementById('connected-nodes'); + const panelTitle = nodeInfoPanel ? nodeInfoPanel.querySelector('.info-panel-title') : null; + + if (!nodeInfoPanel || !nodeDescription || !connectedNodes || !panelTitle) return; + + // Titel und Beschreibung aktualisieren + panelTitle.textContent = node.data('name'); + nodeDescription.textContent = node.data('description') || 'Keine Beschreibung verfügbar.'; + + // Verbundene Knoten auflisten + connectedNodes.innerHTML = ''; + + // Verbundene Knoten ermitteln + const connectedNodesList = []; + node.connectedEdges().forEach(edge => { + let connectedNode; + if (edge.source().id() === node.id()) { + connectedNode = edge.target(); + } else { + connectedNode = edge.source(); + } + + if (!connectedNodesList.some(n => n.id() === connectedNode.id())) { + connectedNodesList.push(connectedNode); } }); - document.addEventListener('mindmap-node-deselected', function() { - console.log('Knoten abgewählt'); - showDefaultSidebar(); - }); + // Verbundene Knoten im Panel anzeigen + if (connectedNodesList.length > 0) { + connectedNodesList.forEach(connectedNode => { + const nodeLink = document.createElement('span'); + nodeLink.className = 'inline-block px-2 py-1 text-xs rounded-md m-1 cursor-pointer opacity-80 hover:opacity-100 transition-opacity'; + nodeLink.style.backgroundColor = connectedNode.data('color'); + nodeLink.textContent = connectedNode.data('name'); + + // Beim Klick auf den verbundenen Knoten zu diesem navigieren + nodeLink.addEventListener('click', function() { + handleNodeSelection(connectedNode); + }); + + connectedNodes.appendChild(nodeLink); + }); + } else { + connectedNodes.innerHTML = 'Keine verbundenen Knoten'; + } + + // Panel anzeigen mit Animation + nodeInfoPanel.classList.add('visible'); } // Zeigt die Standard-Seitenleiste an function showDefaultSidebar() { - // Finde die Seitenleistenelemente - const aboutMindmapPanel = document.querySelector('[data-sidebar="about-mindmap"]'); - const categoriesPanel = document.querySelector('[data-sidebar="categories"]'); - const nodeDescriptionPanel = document.querySelector('[data-sidebar="node-description"]'); - - if (aboutMindmapPanel && categoriesPanel && nodeDescriptionPanel) { - // Beschreibungspanel ausblenden - nodeDescriptionPanel.style.display = 'none'; - - // Standardpanels einblenden mit Animation - aboutMindmapPanel.style.display = 'block'; - categoriesPanel.style.display = 'block'; - - setTimeout(() => { - aboutMindmapPanel.style.opacity = '1'; - aboutMindmapPanel.style.transform = 'translateY(0)'; - - categoriesPanel.style.opacity = '1'; - categoriesPanel.style.transform = 'translateY(0)'; - }, 50); - } + // Alle Seitenleisten-Panels anzeigen/ausblenden + const allPanels = document.querySelectorAll('[data-sidebar]'); + allPanels.forEach(panel => { + if (panel.getAttribute('data-sidebar') === 'node-description') { + panel.classList.add('hidden'); + } else { + panel.classList.remove('hidden'); + } + }); } // Zeigt die Knotenbeschreibung in der Seitenleiste an function showNodeDescriptionSidebar(node) { - // Finde die Seitenleistenelemente - const aboutMindmapPanel = document.querySelector('[data-sidebar="about-mindmap"]'); - const categoriesPanel = document.querySelector('[data-sidebar="categories"]'); - const nodeDescriptionPanel = document.querySelector('[data-sidebar="node-description"]'); + // Das Knotenbeschreibungs-Panel finden + const nodeDescPanel = document.querySelector('[data-sidebar="node-description"]'); - if (aboutMindmapPanel && categoriesPanel && nodeDescriptionPanel) { - // Standardpanels ausblenden - aboutMindmapPanel.style.transition = 'all 0.3s ease'; - categoriesPanel.style.transition = 'all 0.3s ease'; + if (nodeDescPanel) { + // Panel sichtbar machen + nodeDescPanel.classList.remove('hidden'); - aboutMindmapPanel.style.opacity = '0'; - aboutMindmapPanel.style.transform = 'translateY(10px)'; + // Titel und Beschreibung aktualisieren + const nodeTitleElement = nodeDescPanel.querySelector('[data-node-title]'); + const nodeDescElement = nodeDescPanel.querySelector('[data-node-description]'); - categoriesPanel.style.opacity = '0'; - categoriesPanel.style.transform = 'translateY(10px)'; + if (nodeTitleElement) { + nodeTitleElement.textContent = node.data('name'); + } - setTimeout(() => { - aboutMindmapPanel.style.display = 'none'; - categoriesPanel.style.display = 'none'; - - // Beschreibungspanel vorbereiten - const titleElement = nodeDescriptionPanel.querySelector('[data-node-title]'); - const descriptionElement = nodeDescriptionPanel.querySelector('[data-node-description]'); - - if (titleElement && descriptionElement) { - titleElement.textContent = node.name || 'Unbenannter Knoten'; - - // Beschreibung setzen oder Standardbeschreibung generieren - let description = node.description; - if (!description || description.trim() === '') { - description = generateNodeDescription(node); - } - - descriptionElement.textContent = description; - } - - // Beschreibungspanel einblenden mit Animation - nodeDescriptionPanel.style.display = 'block'; - nodeDescriptionPanel.style.opacity = '0'; - nodeDescriptionPanel.style.transform = 'translateY(10px)'; - - setTimeout(() => { - nodeDescriptionPanel.style.transition = 'all 0.4s ease'; - nodeDescriptionPanel.style.opacity = '1'; - nodeDescriptionPanel.style.transform = 'translateY(0)'; - }, 50); - }, 300); + if (nodeDescElement) { + // Beschreibung mit HTML-Formatierung anzeigen + nodeDescElement.innerHTML = generateNodeDescription(node); + } } } -// Generiert automatisch eine Beschreibung für einen Knoten ohne Beschreibung +// Generiert eine formatierte HTML-Beschreibung für einen Knoten function generateNodeDescription(node) { - const descriptions = { - "Wissen": "Der zentrale Knotenpunkt der Mindmap, der alle wissenschaftlichen Disziplinen und Wissensgebiete verbindet. Hier finden sich grundlegende Erkenntnisse und Verbindungen zu spezifischeren Fachgebieten.", - - "Quantenphysik": "Ein Zweig der Physik, der sich mit dem Verhalten und den Interaktionen von Materie und Energie auf der kleinsten Skala beschäftigt. Quantenmechanische Phänomene wie Superposition und Verschränkung bilden die Grundlage für moderne Technologien wie Quantencomputer und -kommunikation.", - - "Neurowissenschaften": "Interdisziplinäres Forschungsgebiet, das die Struktur, Funktion und Entwicklung des Nervensystems und des Gehirns untersucht. Die Erkenntnisse beeinflussen unser Verständnis von Bewusstsein, Kognition, Verhalten und neurologischen Erkrankungen.", - - "Künstliche Intelligenz": "Forschungsgebiet der Informatik, das sich mit der Entwicklung von Systemen befasst, die menschliche Intelligenzformen simulieren können. KI umfasst maschinelles Lernen, neuronale Netze und verschiedene Ansätze zur Problemlösung und Mustererkennung.", - - "Klimaforschung": "Wissenschaftliche Disziplin, die sich mit der Untersuchung des Erdklimas, seinen Veränderungen und den zugrundeliegenden physikalischen Prozessen beschäftigt. Sie liefert wichtige Erkenntnisse zu Klimawandel, Wettermuster und globalen Umweltveränderungen.", - - "Genetik": "Wissenschaft der Gene, Vererbung und der Variation von Organismen. Moderne genetische Forschung umfasst Genomik, Gentechnologie und das Verständnis der molekularen Grundlagen des Lebens sowie ihrer Anwendungen in Medizin und Biotechnologie.", - - "Astrophysik": "Zweig der Astronomie, der die physikalischen Eigenschaften und Prozesse von Himmelskörpern und des Universums untersucht. Sie erforscht Phänomene wie Schwarze Löcher, Galaxien, kosmische Strahlung und die Entstehung und Entwicklung des Universums.", - - "Philosophie": "Disziplin, die sich mit fundamentalen Fragen des Wissens, der Realität und der Existenz auseinandersetzt. Sie umfasst Bereiche wie Metaphysik, Erkenntnistheorie, Ethik und Logik und bildet die Grundlage für kritisches Denken und wissenschaftliche Methodik.", - - "Wissenschaft": "Systematische Erforschung der Natur und der materiellen Welt durch Beobachtung, Experimente und die Formulierung überprüfbarer Theorien. Sie umfasst Naturwissenschaften, Sozialwissenschaften und angewandte Wissenschaften.", - - "Technologie": "Anwendung wissenschaftlicher Erkenntnisse für praktische Zwecke. Sie umfasst die Entwicklung von Werkzeugen, Maschinen, Materialien und Prozessen zur Lösung von Problemen und zur Verbesserung der menschlichen Lebensbedingungen.", - - "Künste": "Ausdruck menschlicher Kreativität und Imagination in verschiedenen Formen wie Malerei, Musik, Literatur, Theater und Film. Die Künste erforschen ästhetische, emotionale und intellektuelle Dimensionen der menschlichen Erfahrung.", - - "Biologie": "Wissenschaft des Lebens und der lebenden Organismen. Sie umfasst Bereiche wie Molekularbiologie, Evolutionsbiologie, Ökologie und beschäftigt sich mit der Struktur, Funktion, Entwicklung und Evolution lebender Systeme.", - - "Mathematik": "Wissenschaft der Muster, Strukturen und Beziehungen. Sie ist die Sprache der Naturwissenschaften und bildet die Grundlage für quantitative Analysen, logisches Denken und Problemlösung in allen wissenschaftlichen Disziplinen.", - - "Psychologie": "Wissenschaftliche Untersuchung des menschlichen Verhaltens und der mentalen Prozesse. Sie erforscht Bereiche wie Kognition, Emotion, Persönlichkeit, soziale Interaktionen und die Behandlung psychischer Störungen.", - - "Ethik": "Teilgebiet der Philosophie, das sich mit moralischen Prinzipien, Werten und der Frage nach richtigem und falschem Handeln beschäftigt. Sie bildet die Grundlage für moralische Entscheidungsfindung in allen Lebensbereichen." - }; + let description = node.data('description') || 'Keine Beschreibung verfügbar.'; - // Verwende vordefinierte Beschreibung, wenn verfügbar - if (node.name && descriptions[node.name]) { - return descriptions[node.name]; - } + // Einfache HTML-Formatierung (kann erweitert werden) + description = description + .replace(/\n/g, '
') + .replace(/\*\*(.*?)\*\*/g, '$1') + .replace(/\*(.*?)\*/g, '$1') + .replace(/`(.*?)`/g, '$1'); - // Generische Beschreibung basierend auf dem Knotentyp - switch (node.type) { - case 'category': - return `Dieser Knoten repräsentiert die Kategorie "${node.name}", die verschiedene verwandte Konzepte und Ideen zusammenfasst. Wählen Sie einen der verbundenen Unterthemen, um mehr Details zu erfahren.`; - case 'subcategory': - return `"${node.name}" ist eine Unterkategorie, die spezifische Aspekte eines größeren Themenbereichs beleuchtet. Die verbundenen Knoten zeigen wichtige Konzepte und Ideen innerhalb dieses Bereichs.`; - default: - return `Dieser Knoten repräsentiert das Konzept "${node.name}". Erforschen Sie die verbundenen Knoten, um Zusammenhänge und verwandte Ideen zu entdecken.`; - } + return description; } \ No newline at end of file diff --git a/static/js/update_mindmap.js b/static/js/update_mindmap.js index be81ba7..f9a531b 100644 --- a/static/js/update_mindmap.js +++ b/static/js/update_mindmap.js @@ -1,7 +1,7 @@ /** * Update Mindmap - * Dieses Skript fügt die neuen wissenschaftlichen Knoten zur Mindmap hinzu - * und stellt sicher, dass sie korrekt angezeigt werden. + * Dieses Skript fügt Knoten zur Mindmap hinzu und stellt sicher, + * dass sie im neuronalen Netzwerk-Design angezeigt werden. */ // Warte bis DOM geladen ist @@ -16,13 +16,13 @@ document.addEventListener('DOMContentLoaded', function() { // Auf das Laden der Mindmap warten document.addEventListener('mindmap-loaded', function() { - console.log('Mindmap geladen, füge wissenschaftliche Knoten hinzu...'); + console.log('Mindmap geladen, wende neuronales Netzwerk-Design an...'); enhanceMindmap(); }); }); /** - * Erweitert die Mindmap mit den neu hinzugefügten wissenschaftlichen Knoten + * Erweitert die Mindmap mit dem neuronalen Netzwerk-Design */ function enhanceMindmap() { // Auf die bestehende Cytoscape-Instanz zugreifen @@ -33,25 +33,295 @@ function enhanceMindmap() { return; } - // Aktualisiere das Layout mit zusätzlichem Platz für die neuen Knoten + // Aktualisiere das Layout für eine bessere Verteilung cy.layout({ name: 'cose', animate: true, - animationDuration: 800, + animationDuration: 1800, nodeDimensionsIncludeLabels: true, padding: 100, spacingFactor: 1.8, randomize: false, - fit: true + fit: true, + componentSpacing: 100, + nodeRepulsion: 8000, + edgeElasticity: 100, + nestingFactor: 1.2, + gravity: 80 }).run(); - console.log('Mindmap wurde erfolgreich aktualisiert!'); + // Neuronen-Namen mit besserer Lesbarkeit umgestalten + cy.style() + .selector('node') + .style({ + 'text-background-color': 'rgba(10, 14, 25, 0.7)', + 'text-background-opacity': 0.7, + 'text-background-padding': '2px', + 'text-border-opacity': 0.2, + 'text-border-width': 1, + 'text-border-color': '#8b5cf6' + }) + .update(); - // Wenn ein Wissen-Knoten existiert, sicherstellen, dass er im Zentrum ist - const rootNode = cy.getElementById('1'); - if (rootNode.length > 0) { - cy.center(rootNode); + // Sicherstellen, dass alle Knoten Neuronen-Eigenschaften haben + cy.nodes().forEach(node => { + if (!node.data('neuronSize')) { + const neuronSize = Math.floor(Math.random() * 8) + 3; + node.data('neuronSize', neuronSize); + } + + if (!node.data('neuronActivity')) { + const neuronActivity = Math.random() * 0.7 + 0.3; + node.data('neuronActivity', neuronActivity); + } + + // Zusätzliche Neuronale Eigenschaften + node.data('pulseFrequency', Math.random() * 4 + 2); // Pulsfrequenz (2-6 Hz) + node.data('refractionPeriod', Math.random() * 300 + 700); // Refraktionszeit (700-1000ms) + node.data('threshold', Math.random() * 0.3 + 0.6); // Aktivierungsschwelle (0.6-0.9) + }); + + // Sicherstellen, dass alle Kanten Synapse-Eigenschaften haben + cy.edges().forEach(edge => { + if (!edge.data('strength')) { + const strength = Math.random() * 0.6 + 0.2; + edge.data('strength', strength); + } + + // Zusätzliche synaptische Eigenschaften + edge.data('conductionVelocity', Math.random() * 0.5 + 0.3); // Leitungsgeschwindigkeit (0.3-0.8) + edge.data('latency', Math.random() * 100 + 50); // Signalverzögerung (50-150ms) + }); + + // Neuronales Netzwerk-Stil anwenden + applyNeuralNetworkStyle(cy); + + console.log('Mindmap wurde erfolgreich im neuronalen Netzwerk-Stil aktualisiert'); + + // Spezielle Effekte für das neuronale Netzwerk hinzufügen + startNeuralActivitySimulation(cy); +} + +/** + * Wendet detaillierte neuronale Netzwerkstile auf die Mindmap an + * @param {Object} cy - Cytoscape-Instanz + */ +function applyNeuralNetworkStyle(cy) { + // Wende erweiterte Stile für Neuronen und Synapsen an + cy.style() + .selector('node') + .style({ + 'label': 'data(name)', + 'text-valign': 'bottom', + 'text-halign': 'center', + 'color': '#ffffff', + 'text-outline-width': 1.5, + 'text-outline-color': '#0a0e19', + 'text-outline-opacity': 0.9, + 'font-size': 10, + 'text-margin-y': 7, + 'width': 'mapData(neuronSize, 3, 10, 15, 40)', + 'height': 'mapData(neuronSize, 3, 10, 15, 40)', + 'background-color': 'data(color)', + 'background-opacity': 0.85, + 'border-width': 0, + 'shape': 'ellipse', + 'shadow-blur': 'mapData(neuronActivity, 0.3, 1, 5, 15)', + 'shadow-color': 'data(color)', + 'shadow-opacity': 0.6, + 'shadow-offset-x': 0, + 'shadow-offset-y': 0 + }) + .selector('edge') + .style({ + 'width': 'mapData(strength, 0.2, 0.8, 0.7, 2)', + 'curve-style': 'bezier', + 'line-color': '#8a8aaa', + 'line-opacity': 'mapData(strength, 0.2, 0.8, 0.4, 0.7)', + 'line-style': function(ele) { + const strength = ele.data('strength'); + if (strength <= 0.4) return 'dotted'; + if (strength <= 0.6) return 'dashed'; + return 'solid'; + }, + 'target-arrow-shape': 'none', + 'source-endpoint': '0% 50%', + 'target-endpoint': '100% 50%' + }) + .selector('node[isRoot]') + .style({ + 'font-size': 12, + 'font-weight': 'bold', + 'width': 50, + 'height': 50, + 'background-color': '#6366f1', + 'shadow-blur': 20, + 'shadow-color': '#6366f1', + 'shadow-opacity': 0.8, + 'text-margin-y': 8 + }) + .update(); +} + +/** + * Simuliert neuronale Aktivität in der Mindmap + * @param {Object} cy - Cytoscape-Instanz + */ +function startNeuralActivitySimulation(cy) { + // Neuronen-Zustand für die Simulation + const neuronStates = new Map(); + + // Initialisieren aller Neuronen-Zustände + cy.nodes().forEach(node => { + neuronStates.set(node.id(), { + potential: Math.random() * 0.3, // Startpotential + lastFired: 0, // Zeitpunkt der letzten Aktivierung + isRefractory: false, // Refraktärphase + refractoryUntil: 0 // Ende der Refraktärphase + }); + }); + + // Neuronale Aktivität simulieren + function simulateNeuralActivity() { + const currentTime = Date.now(); + const nodes = cy.nodes().toArray(); + + // Zufällige Stimulation eines Neurons + if (Math.random() > 0.7) { + const randomNodeIndex = Math.floor(Math.random() * nodes.length); + const randomNode = nodes[randomNodeIndex]; + + const state = neuronStates.get(randomNode.id()); + if (state && !state.isRefractory) { + state.potential += 0.5; // Erhöhe das Potential durch externe Stimulation + } + } + + // Neuronen aktualisieren + nodes.forEach(node => { + const nodeId = node.id(); + const state = neuronStates.get(nodeId); + const threshold = node.data('threshold') || 0.7; + const refractoryPeriod = node.data('refractionPeriod') || 1000; + + // Überprüfen, ob die Refraktärphase beendet ist + if (state.isRefractory && currentTime >= state.refractoryUntil) { + state.isRefractory = false; + state.potential = 0.1; // Ruhepotential nach Refraktärphase + } + + // Wenn nicht in Refraktärphase und Potential über Schwelle + if (!state.isRefractory && state.potential >= threshold) { + // Neuron feuert + fireNeuron(node, state, currentTime); + } else if (!state.isRefractory) { + // Potential langsam verlieren, wenn nicht gefeuert wird + state.potential *= 0.95; + } + }); + + // Simulation fortsetzen + requestAnimationFrame(simulateNeuralActivity); } + + // Neuron "feuern" lassen + function fireNeuron(node, state, currentTime) { + // Neuron aktivieren + node.animate({ + style: { + 'background-opacity': 1, + 'shadow-opacity': 1, + 'shadow-blur': 25 + }, + duration: 300, + easing: 'ease-in-cubic', + complete: function() { + // Zurück zum normalen Zustand + node.animate({ + style: { + 'background-opacity': 0.85, + 'shadow-opacity': 0.6, + 'shadow-blur': 'mapData(neuronActivity, 0.3, 1, 5, 15)' + }, + duration: 600, + easing: 'ease-out-cubic' + }); + } + }); + + // Refraktärphase setzen + state.isRefractory = true; + state.lastFired = currentTime; + state.refractoryPeriod = node.data('refractionPeriod') || 1000; + state.refractoryUntil = currentTime + state.refractoryPeriod; + state.potential = 0; // Potential zurücksetzen + + // Signal über verbundene Synapsen weiterleiten + propagateSignal(node, currentTime); + } + + // Signal über Synapsen propagieren + function propagateSignal(sourceNode, currentTime) { + // Verbundene Kanten auswählen + const edges = sourceNode.connectedEdges().filter(edge => + edge.source().id() === sourceNode.id() // Nur ausgehende Kanten + ); + + // Durch alle Kanten iterieren + edges.forEach(edge => { + // Signalverzögerung basierend auf synaptischen Eigenschaften + const latency = edge.data('latency') || 100; + const strength = edge.data('strength') || 0.5; + + // Signal entlang der Kante senden + setTimeout(() => { + edge.animate({ + style: { + 'line-color': '#a78bfa', + 'line-opacity': 0.9, + 'width': 2.5 + }, + duration: 200, + easing: 'ease-in', + complete: function() { + // Kante zurücksetzen + edge.animate({ + style: { + 'line-color': '#8a8aaa', + 'line-opacity': 'mapData(strength, 0.2, 0.8, 0.4, 0.7)', + 'width': 'mapData(strength, 0.2, 0.8, 0.7, 2)' + }, + duration: 400, + easing: 'ease-out' + }); + + // Zielknoten potenzial erhöhen + const targetNode = edge.target(); + const targetState = neuronStates.get(targetNode.id()); + + if (targetState && !targetState.isRefractory) { + // Potentialzunahme basierend auf synaptischer Stärke + targetState.potential += strength * 0.4; + + // Subtile Anzeige der Potenzialänderung + targetNode.animate({ + style: { + 'background-opacity': Math.min(1, 0.85 + (strength * 0.2)), + 'shadow-opacity': Math.min(1, 0.6 + (strength * 0.3)), + 'shadow-blur': Math.min(25, 10 + (strength * 15)) + }, + duration: 300, + easing: 'ease-in-out' + }); + } + } + }); + }, latency); + }); + } + + // Starte die Simulation + simulateNeuralActivity(); } // Hilfe-Funktion zum Hinzufügen eines Flash-Hinweises diff --git a/templates/mindmap.html b/templates/mindmap.html index 3bfc794..c465e8f 100644 --- a/templates/mindmap.html +++ b/templates/mindmap.html @@ -1,486 +1,228 @@ {% extends "base.html" %} -{% block title %}Mindmap{% endblock %} +{% block title %}Interaktive Mindmap{% endblock %} {% block extra_css %} {% endblock %} {% block content %} - -
- -
-

- Wissenslandkarte -

-

- Visualisiere die Verbindungen zwischen Gedanken und Konzepten -

+
+ +
+

Interaktive Wissenslandkarte

- -
- -
- - - - - - -
+ +
- -
+ +
+ + + + +
- -
-

Knoteninfo

-

Wählen Sie einen Knoten aus...

- -
-
Verknüpfte Knoten
- -
+ +
+

Knoteninformationen

+
+

Wählen Sie einen Knoten aus, um Details anzuzeigen.

- - + `; + sidebar.innerHTML = html; } @@ -236,316 +236,316 @@ function resetSelection(cy) { if (sidebar) { sidebar.innerHTML = ''; } -} - -/** - * Generiert Standarddaten für die Mindmap als Fallback - */ -function generateDefaultData() { - return { - nodes: [ - { id: 'root', name: 'Wissen', description: 'Zentrale Wissensbasis', category: 'Zentral', color_code: '#4299E1' }, - { id: 'philosophy', name: 'Philosophie', description: 'Philosophisches Denken', category: 'Philosophie', color_code: '#9F7AEA', parent_id: 'root' }, - { id: 'science', name: 'Wissenschaft', description: 'Wissenschaftliche Erkenntnisse', category: 'Wissenschaft', color_code: '#48BB78', parent_id: 'root' }, - { id: 'technology', name: 'Technologie', description: 'Technologische Entwicklungen', category: 'Technologie', color_code: '#ED8936', parent_id: 'root' }, - { id: 'arts', name: 'Künste', description: 'Künstlerische Ausdrucksformen', category: 'Künste', color_code: '#ED64A6', parent_id: 'root' }, - { id: 'psychology', name: 'Psychologie', description: 'Menschliches Verhalten und Geist', category: 'Psychologie', color_code: '#4299E1', parent_id: 'root' } - ] - }; -} - -/** - * Rendert die Mindmap mit Cytoscape.js - */ -function renderMindmap(data) { - console.log('Rendere Mindmap mit Daten:', data); - - // Konvertiere Backend-Daten in Cytoscape-Format - const elements = convertToCytoscapeFormat(data); - - // Leere den Container - cyContainer.innerHTML = ''; - - // Erstelle Cytoscape-Instanz - mindmap = cytoscape({ - container: cyContainer, - elements: elements, - style: [ - { - selector: 'node', - style: { - 'background-color': 'data(color)', - 'label': 'data(name)', - 'width': 30, - 'height': 30, - 'font-size': 12, - 'text-valign': 'bottom', - 'text-halign': 'center', - 'text-margin-y': 8, - 'color': document.documentElement.classList.contains('dark') ? '#f1f5f9' : '#334155', - 'text-background-color': document.documentElement.classList.contains('dark') ? 'rgba(30, 41, 59, 0.8)' : 'rgba(241, 245, 249, 0.8)', - 'text-background-opacity': 0.8, - 'text-background-padding': '2px', - 'text-background-shape': 'roundrectangle', - 'text-wrap': 'ellipsis', - 'text-max-width': '100px' - } - }, - { - selector: 'edge', - style: { - 'width': 2, - 'line-color': document.documentElement.classList.contains('dark') ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)', - 'target-arrow-color': document.documentElement.classList.contains('dark') ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)', - 'curve-style': 'bezier' - } - }, - { - selector: 'node:selected', - style: { - 'background-color': 'data(color)', - 'border-width': 3, - 'border-color': '#8b5cf6', - 'width': 40, - 'height': 40, - 'font-size': 14, - 'font-weight': 'bold', - 'text-background-color': '#8b5cf6', - 'text-background-opacity': 0.9 - } - } - ], - layout: { - name: 'cose', - animate: true, - animationDuration: 800, - nodeDimensionsIncludeLabels: true, - refresh: 30, - randomize: true, - componentSpacing: 100, - nodeRepulsion: 8000, - nodeOverlap: 20, - idealEdgeLength: 200, - edgeElasticity: 100, - nestingFactor: 1.2, - gravity: 80, - fit: true, - padding: 30 - } - }); - - // Event-Listener für Knoteninteraktionen - mindmap.on('tap', 'node', function(evt) { - const node = evt.target; - const nodeData = node.data(); - - // Update Info-Panel - updateNodeInfoPanel(nodeData); - - // Lade verbundene Knoten - updateConnectedNodes(node); - }); - - // Toolbar-Buttons aktivieren - if (fitButton) { - fitButton.addEventListener('click', () => { - mindmap.fit(); - mindmap.center(); - }); } - if (resetButton) { - resetButton.addEventListener('click', () => { - mindmap.layout({ + /** + * Generiert Standarddaten für die Mindmap als Fallback + */ + function generateDefaultData() { + return { + nodes: [ + { id: 'root', name: 'Wissen', description: 'Zentrale Wissensbasis', category: 'Zentral', color_code: '#4299E1' }, + { id: 'philosophy', name: 'Philosophie', description: 'Philosophisches Denken', category: 'Philosophie', color_code: '#9F7AEA', parent_id: 'root' }, + { id: 'science', name: 'Wissenschaft', description: 'Wissenschaftliche Erkenntnisse', category: 'Wissenschaft', color_code: '#48BB78', parent_id: 'root' }, + { id: 'technology', name: 'Technologie', description: 'Technologische Entwicklungen', category: 'Technologie', color_code: '#ED8936', parent_id: 'root' }, + { id: 'arts', name: 'Künste', description: 'Künstlerische Ausdrucksformen', category: 'Künste', color_code: '#ED64A6', parent_id: 'root' }, + { id: 'psychology', name: 'Psychologie', description: 'Menschliches Verhalten und Geist', category: 'Psychologie', color_code: '#4299E1', parent_id: 'root' } + ] + }; + } + + /** + * Rendert die Mindmap mit Cytoscape.js + */ + function renderMindmap(data) { + console.log('Rendere Mindmap mit Daten:', data); + + // Konvertiere Backend-Daten in Cytoscape-Format + const elements = convertToCytoscapeFormat(data); + + // Leere den Container + cyContainer.innerHTML = ''; + + // Erstelle Cytoscape-Instanz + mindmap = cytoscape({ + container: cyContainer, + elements: elements, + style: [ + { + selector: 'node', + style: { + 'background-color': 'data(color)', + 'label': 'data(name)', + 'width': 30, + 'height': 30, + 'font-size': 12, + 'text-valign': 'bottom', + 'text-halign': 'center', + 'text-margin-y': 8, + 'color': document.documentElement.classList.contains('dark') ? '#f1f5f9' : '#334155', + 'text-background-color': document.documentElement.classList.contains('dark') ? 'rgba(30, 41, 59, 0.8)' : 'rgba(241, 245, 249, 0.8)', + 'text-background-opacity': 0.8, + 'text-background-padding': '2px', + 'text-background-shape': 'roundrectangle', + 'text-wrap': 'ellipsis', + 'text-max-width': '100px' + } + }, + { + selector: 'edge', + style: { + 'width': 2, + 'line-color': document.documentElement.classList.contains('dark') ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)', + 'target-arrow-color': document.documentElement.classList.contains('dark') ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)', + 'curve-style': 'bezier' + } + }, + { + selector: 'node:selected', + style: { + 'background-color': 'data(color)', + 'border-width': 3, + 'border-color': '#8b5cf6', + 'width': 40, + 'height': 40, + 'font-size': 14, + 'font-weight': 'bold', + 'text-background-color': '#8b5cf6', + 'text-background-opacity': 0.9 + } + } + ], + layout: { name: 'cose', animate: true, + animationDuration: 800, + nodeDimensionsIncludeLabels: true, + refresh: 30, randomize: true, - fit: true - }).run(); - }); - } - - if (toggleLabelsButton) { - let labelsVisible = true; - toggleLabelsButton.addEventListener('click', () => { - labelsVisible = !labelsVisible; - - if (labelsVisible) { - mindmap.style() - .selector('node') - .style('label', 'data(name)') - .update(); - } else { - mindmap.style() - .selector('node') - .style('label', '') - .update(); + componentSpacing: 100, + nodeRepulsion: 8000, + nodeOverlap: 20, + idealEdgeLength: 200, + edgeElasticity: 100, + nestingFactor: 1.2, + gravity: 80, + fit: true, + padding: 30 } }); + + // Event-Listener für Knoteninteraktionen + mindmap.on('tap', 'node', function(evt) { + const node = evt.target; + const nodeData = node.data(); + + // Update Info-Panel + updateNodeInfoPanel(nodeData); + + // Lade verbundene Knoten + updateConnectedNodes(node); + }); + + // Toolbar-Buttons aktivieren + if (fitButton) { + fitButton.addEventListener('click', () => { + mindmap.fit(); + mindmap.center(); + }); + } + + if (resetButton) { + resetButton.addEventListener('click', () => { + mindmap.layout({ + name: 'cose', + animate: true, + randomize: true, + fit: true + }).run(); + }); + } + + if (toggleLabelsButton) { + let labelsVisible = true; + toggleLabelsButton.addEventListener('click', () => { + labelsVisible = !labelsVisible; + + if (labelsVisible) { + mindmap.style() + .selector('node') + .style('label', 'data(name)') + .update(); + } else { + mindmap.style() + .selector('node') + .style('label', '') + .update(); + } + }); + } + + // Dark Mode-Änderungen überwachen + document.addEventListener('darkModeToggled', function(event) { + updateDarkModeStyles(event.detail.isDark); + }); + + // Initial fit und center + setTimeout(() => { + mindmap.fit(); + mindmap.center(); + }, 100); } - // Dark Mode-Änderungen überwachen - document.addEventListener('darkModeToggled', function(event) { - updateDarkModeStyles(event.detail.isDark); - }); - - // Initial fit und center - setTimeout(() => { - mindmap.fit(); - mindmap.center(); - }, 100); -} - -/** - * Konvertiert die Backend-Daten ins Cytoscape-Format - */ -function convertToCytoscapeFormat(data) { - const elements = { - nodes: [], - edges: [] - }; - - // Nodes hinzufügen - if (data.nodes && data.nodes.length > 0) { - data.nodes.forEach(node => { - elements.nodes.push({ - data: { - id: String(node.id), - name: node.name, - description: node.description || 'Keine Beschreibung verfügbar', - category: node.category || 'Allgemein', - color: node.color_code || getRandomColor() + /** + * Konvertiert die Backend-Daten ins Cytoscape-Format + */ + function convertToCytoscapeFormat(data) { + const elements = { + nodes: [], + edges: [] + }; + + // Nodes hinzufügen + if (data.nodes && data.nodes.length > 0) { + data.nodes.forEach(node => { + elements.nodes.push({ + data: { + id: String(node.id), + name: node.name, + description: node.description || 'Keine Beschreibung verfügbar', + category: node.category || 'Allgemein', + color: node.color_code || getRandomColor() + } + }); + + // Kante zum Elternknoten hinzufügen (falls vorhanden) + if (node.parent_id) { + elements.edges.push({ + data: { + id: `edge-${node.parent_id}-${node.id}`, + source: String(node.parent_id), + target: String(node.id) + } + }); } }); - // Kante zum Elternknoten hinzufügen (falls vorhanden) - if (node.parent_id) { - elements.edges.push({ - data: { - id: `edge-${node.parent_id}-${node.id}`, - source: String(node.parent_id), - target: String(node.id) - } + // Zusätzliche Kanten zwischen Knoten hinzufügen (falls in den Daten vorhanden) + if (data.edges && data.edges.length > 0) { + data.edges.forEach(edge => { + elements.edges.push({ + data: { + id: `edge-${edge.source}-${edge.target}`, + source: String(edge.source), + target: String(edge.target) + } + }); }); } - }); + } - // Zusätzliche Kanten zwischen Knoten hinzufügen (falls in den Daten vorhanden) - if (data.edges && data.edges.length > 0) { - data.edges.forEach(edge => { - elements.edges.push({ - data: { - id: `edge-${edge.source}-${edge.target}`, - source: String(edge.source), - target: String(edge.target) - } + return elements; + } + + /** + * Aktualisiert das Informations-Panel mit den Knotendaten + */ + function updateNodeInfoPanel(nodeData) { + if (nodeInfoPanel && nodeDescription) { + // Panel anzeigen + nodeInfoPanel.style.display = 'block'; + + // Titel und Beschreibung aktualisieren + const titleElement = nodeInfoPanel.querySelector('.info-panel-title'); + if (titleElement) { + titleElement.textContent = nodeData.name; + } + + if (nodeDescription) { + nodeDescription.textContent = nodeData.description || 'Keine Beschreibung verfügbar'; + } + } + } + + /** + * Aktualisiert die Liste der verbundenen Knoten + */ + function updateConnectedNodes(node) { + if (connectedNodes) { + // Leere den Container + connectedNodes.innerHTML = ''; + + // Hole verbundene Knoten + const connectedEdges = node.connectedEdges(); + + if (connectedEdges.length === 0) { + connectedNodes.innerHTML = '
Keine verbundenen Knoten
'; + return; + } + + // Füge alle verbundenen Knoten hinzu + connectedEdges.forEach(edge => { + const targetNode = edge.target().id() === node.id() ? edge.source() : edge.target(); + const targetData = targetNode.data(); + + const nodeLink = document.createElement('div'); + nodeLink.className = 'node-link'; + nodeLink.innerHTML = ` + + ${targetData.name} + `; + + // Klick-Event zum Fokussieren des Knotens + nodeLink.addEventListener('click', () => { + mindmap.center(targetNode); + targetNode.select(); + updateNodeInfoPanel(targetData); + updateConnectedNodes(targetNode); }); + + connectedNodes.appendChild(nodeLink); }); } } - return elements; -} - -/** - * Aktualisiert das Informations-Panel mit den Knotendaten - */ -function updateNodeInfoPanel(nodeData) { - if (nodeInfoPanel && nodeDescription) { - // Panel anzeigen - nodeInfoPanel.style.display = 'block'; + /** + * Aktualisiert die Styles bei Dark Mode-Änderungen + */ + function updateDarkModeStyles(isDark) { + if (!mindmap) return; - // Titel und Beschreibung aktualisieren - const titleElement = nodeInfoPanel.querySelector('.info-panel-title'); - if (titleElement) { - titleElement.textContent = nodeData.name; - } + const textColor = isDark ? '#f1f5f9' : '#334155'; + const textBgColor = isDark ? 'rgba(30, 41, 59, 0.8)' : 'rgba(241, 245, 249, 0.8)'; + const edgeColor = isDark ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)'; - if (nodeDescription) { - nodeDescription.textContent = nodeData.description || 'Keine Beschreibung verfügbar'; - } + mindmap.style() + .selector('node') + .style({ + 'color': textColor, + 'text-background-color': textBgColor + }) + .selector('edge') + .style({ + 'line-color': edgeColor, + 'target-arrow-color': edgeColor + }) + .update(); } -} - -/** - * Aktualisiert die Liste der verbundenen Knoten - */ -function updateConnectedNodes(node) { - if (connectedNodes) { - // Leere den Container - connectedNodes.innerHTML = ''; - - // Hole verbundene Knoten - const connectedEdges = node.connectedEdges(); - - if (connectedEdges.length === 0) { - connectedNodes.innerHTML = '
Keine verbundenen Knoten
'; - return; - } - - // Füge alle verbundenen Knoten hinzu - connectedEdges.forEach(edge => { - const targetNode = edge.target().id() === node.id() ? edge.source() : edge.target(); - const targetData = targetNode.data(); - - const nodeLink = document.createElement('div'); - nodeLink.className = 'node-link'; - nodeLink.innerHTML = ` - - ${targetData.name} - `; - - // Klick-Event zum Fokussieren des Knotens - nodeLink.addEventListener('click', () => { - mindmap.center(targetNode); - targetNode.select(); - updateNodeInfoPanel(targetData); - updateConnectedNodes(targetNode); - }); - - connectedNodes.appendChild(nodeLink); - }); + + /** + * Generiert eine zufällige Farbe + */ + function getRandomColor() { + const colors = [ + '#4299E1', // Blau + '#9F7AEA', // Lila + '#48BB78', // Grün + '#ED8936', // Orange + '#ED64A6', // Pink + '#F56565' // Rot + ]; + return colors[Math.floor(Math.random() * colors.length)]; } -} - -/** - * Aktualisiert die Styles bei Dark Mode-Änderungen - */ -function updateDarkModeStyles(isDark) { - if (!mindmap) return; - - const textColor = isDark ? '#f1f5f9' : '#334155'; - const textBgColor = isDark ? 'rgba(30, 41, 59, 0.8)' : 'rgba(241, 245, 249, 0.8)'; - const edgeColor = isDark ? 'rgba(255, 255, 255, 0.15)' : 'rgba(30, 41, 59, 0.15)'; - - mindmap.style() - .selector('node') - .style({ - 'color': textColor, - 'text-background-color': textBgColor - }) - .selector('edge') - .style({ - 'line-color': edgeColor, - 'target-arrow-color': edgeColor - }) - .update(); -} - -/** - * Generiert eine zufällige Farbe - */ -function getRandomColor() { - const colors = [ - '#4299E1', // Blau - '#9F7AEA', // Lila - '#48BB78', // Grün - '#ED8936', // Orange - '#ED64A6', // Pink - '#F56565' // Rot - ]; - return colors[Math.floor(Math.random() * colors.length)]; -} // Initialisiere die Mindmap-Seite initMindmapPage(); \ No newline at end of file diff --git a/static/js/update_mindmap.js b/static/js/update_mindmap.js index 2011422..dec3545 100644 --- a/static/js/update_mindmap.js +++ b/static/js/update_mindmap.js @@ -16,7 +16,7 @@ document.addEventListener('DOMContentLoaded', function() { console.error('Mindmap-Container #cy nicht gefunden!'); return; } - + // Prüfe, ob Cytoscape verfügbar ist if (typeof cytoscape === 'undefined') { console.error('Cytoscape ist nicht definiert!'); diff --git a/templates/base.html b/templates/base.html index 362eb77..078534b 100644 --- a/templates/base.html +++ b/templates/base.html @@ -111,12 +111,6 @@ - - - - - - @@ -741,204 +735,205 @@ {% block scripts %}{% endblock %} - + diff --git a/templates/mindmap.html b/templates/mindmap.html index c7ba353..362608e 100644 --- a/templates/mindmap.html +++ b/templates/mindmap.html @@ -228,7 +228,5 @@ - - {% endblock %} \ No newline at end of file From f093a6211c8feed607e5597dad555f1f206cb3d2 Mon Sep 17 00:00:00 2001 From: marwin Date: Tue, 6 May 2025 22:12:46 +0100 Subject: [PATCH 06/16] ich bin dran ! --- static/js/update_mindmap.js | 39 ++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/static/js/update_mindmap.js b/static/js/update_mindmap.js index dec3545..837e0f8 100644 --- a/static/js/update_mindmap.js +++ b/static/js/update_mindmap.js @@ -24,18 +24,30 @@ document.addEventListener('DOMContentLoaded', function() { } console.log('Cytoscape ist verfügbar'); - // Beispiel-Daten (kannst du später ersetzen) + // Beispiel-Daten entfernt, stattdessen große Mindmap-Daten verwenden const elements = [ - { data: { id: 'a', label: 'Neuron A' } }, - { data: { id: 'b', label: 'Neuron B' } }, - { data: { id: 'c', label: 'Neuron C' } }, - { data: { source: 'a', target: 'b' } }, - { data: { source: 'a', target: 'c' } } + // Knoten + ...mindmapData.nodes.map(node => ({ + data: { + id: node.id, + label: node.label, + category: node.category, + description: node.description + } + })), + // Kanten + ...mindmapData.edges.map(edge => ({ + data: { + source: edge.source, + target: edge.target, + label: edge.label + } + })) ]; console.log('Initialisiere Cytoscape...'); - // Initialisiere Cytoscape + // Initialisiere Cytoscape mit großen Daten window.cy = cytoscape({ container: cyContainer, elements: elements, @@ -43,7 +55,7 @@ document.addEventListener('DOMContentLoaded', function() { { selector: 'node', style: { - 'background-color': '#60a5fa', + 'background-color': 'data(color)', 'label': 'data(label)', 'color': '#fff', 'text-background-color': '#222a', @@ -68,7 +80,13 @@ document.addEventListener('DOMContentLoaded', function() { 'line-color': '#a78bfa', 'target-arrow-color': '#a78bfa', 'target-arrow-shape': 'triangle', - 'curve-style': 'bezier' + 'curve-style': 'bezier', + 'label': 'data(label)', + 'font-size': 12, + 'color': '#fff', + 'text-background-color': '#222a', + 'text-background-opacity': 0.7, + 'text-background-padding': '2px', } } ], @@ -80,6 +98,9 @@ document.addEventListener('DOMContentLoaded', function() { console.log('Cytoscape initialisiert'); + // Mindmap mit echten Daten befüllen (Styles, Farben etc.) + updateMindmap(); + // Event auslösen, damit andere Scripte reagieren können document.dispatchEvent(new Event('mindmap-loaded')); console.log('mindmap-loaded Event ausgelöst'); From acceec4352bb29d314f50fdb9019510fd48db2b7 Mon Sep 17 00:00:00 2001 From: marwin Date: Tue, 6 May 2025 22:24:49 +0100 Subject: [PATCH 07/16] hab glaube gefixed --- templates/base.html | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/base.html b/templates/base.html index 078534b..5e1efb9 100644 --- a/templates/base.html +++ b/templates/base.html @@ -734,6 +734,7 @@ {% block scripts %}{% endblock %} + {% block extra_js %}{% endblock %} - - - - - - - - - - -
-
-

Interaktive Mindmap

-
- -
-
- -
- - - - - - - -
- -
- -
- -
- -
- Mindmap-Anwendung © 2023 -
-
- - - - - - - - \ No newline at end of file diff --git a/static/js/mindmap.js b/static/js/mindmap.js deleted file mode 100644 index b6c441d..0000000 --- a/static/js/mindmap.js +++ /dev/null @@ -1,690 +0,0 @@ -/** - * Mindmap.js - Interaktive Mind-Map Implementierung - * - Event-Listener und Interaktionslogik - * - Fetch API für REST-Zugriffe - * - Socket.IO für Echtzeit-Synchronisation - * - Lazy Loading & Progressive Disclosure - */ - -(async () => { - /* 1. Event-Listener und Interaktionslogik */ - - // Warte auf die Cytoscape-Instanz - document.addEventListener('mindmap-loaded', function() { - const cy = window.cy; - if (!cy) return; - - // Tooltip-Funktionalität - cy.nodes().unbind('mouseover').bind('mouseover', (event) => { - const node = event.target; - const description = node.data('description'); - - if (description) { - const tooltip = document.getElementById('node-tooltip') || - document.createElement('div'); - - if (!tooltip.id) { - tooltip.id = 'node-tooltip'; - tooltip.style.position = 'absolute'; - tooltip.style.backgroundColor = '#333'; - tooltip.style.color = '#fff'; - tooltip.style.padding = '8px'; - tooltip.style.borderRadius = '4px'; - tooltip.style.maxWidth = '250px'; - tooltip.style.zIndex = 10; - tooltip.style.pointerEvents = 'none'; - tooltip.style.transition = 'opacity 0.2s'; - tooltip.style.boxShadow = '0 2px 10px rgba(0,0,0,0.3)'; - document.body.appendChild(tooltip); - } - - const renderedPosition = node.renderedPosition(); - const containerRect = cy.container().getBoundingClientRect(); - - tooltip.innerHTML = description; - tooltip.style.left = (containerRect.left + renderedPosition.x + 25) + 'px'; - tooltip.style.top = (containerRect.top + renderedPosition.y - 15) + 'px'; - tooltip.style.opacity = '1'; - } - }); - - // Mouseout-Event für Tooltip - cy.nodes().unbind('mouseout').bind('mouseout', () => { - const tooltip = document.getElementById('node-tooltip'); - if (tooltip) { - tooltip.style.opacity = '0'; - } - }); - - // Kontextmenü - setupContextMenu(cy); - }); -})(); - -/** - * Richtet das Kontextmenü ein - * @param {Object} cy - Cytoscape-Instanz - */ -function setupContextMenu(cy) { - cy.on('cxttap', 'node', function(e) { - const node = e.target; - const nodeData = node.data(); - - // Position des Kontextmenüs berechnen - const renderedPosition = node.renderedPosition(); - const containerRect = cy.container().getBoundingClientRect(); - const menuX = containerRect.left + renderedPosition.x; - const menuY = containerRect.top + renderedPosition.y; - - // Kontextmenü erstellen oder aktualisieren - let contextMenu = document.getElementById('context-menu'); - if (!contextMenu) { - contextMenu = document.createElement('div'); - contextMenu.id = 'context-menu'; - contextMenu.style.position = 'absolute'; - contextMenu.style.backgroundColor = '#fff'; - contextMenu.style.border = '1px solid #ccc'; - contextMenu.style.borderRadius = '4px'; - contextMenu.style.padding = '5px 0'; - contextMenu.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)'; - contextMenu.style.zIndex = 1000; - document.body.appendChild(contextMenu); - } - - // Menüinhalte - contextMenu.innerHTML = ` - - - - `; - - // Styling für Menüpunkte - const menuItems = contextMenu.querySelectorAll('.menu-item'); - menuItems.forEach(item => { - item.style.padding = '8px 16px'; - item.style.cursor = 'pointer'; - item.style.transition = 'background-color 0.2s'; - - item.addEventListener('mouseover', () => { - item.style.backgroundColor = '#f0f0f0'; - }); - - item.addEventListener('mouseout', () => { - item.style.backgroundColor = ''; - }); - - item.addEventListener('click', () => { - const action = item.dataset.action; - handleContextMenuAction(action, node); - contextMenu.style.display = 'none'; - }); - }); - - // Menü positionieren - contextMenu.style.left = menuX + 'px'; - contextMenu.style.top = menuY + 'px'; - contextMenu.style.display = 'block'; - - // Klick außerhalb schließt Menü - document.addEventListener('click', function closeMenu(e) { - if (!contextMenu.contains(e.target)) { - contextMenu.style.display = 'none'; - document.removeEventListener('click', closeMenu); - } - }); - }); -} - -/** - * Behandelt Aktionen aus dem Kontextmenü - * @param {string} action - Die ausgewählte Aktion - * @param {Object} node - Der betroffene Knoten - */ -function handleContextMenuAction(action, node) { - switch (action) { - case 'edit': - // Implementiere Bearbeitungslogik - console.log('Bearbeite Knoten:', node.id()); - break; - case 'connect': - // Implementiere Verbindungslogik - console.log('Erstelle Verbindung für:', node.id()); - break; - case 'delete': - // Implementiere Löschlogik - console.log('Lösche Knoten:', node.id()); - break; - } -} - - /* 2. Hilfs-Funktionen für API-Zugriffe */ - const get = async endpoint => { - try { - const response = await fetch(endpoint); - if (!response.ok) { - console.error(`API-Fehler: ${endpoint} antwortet mit Status ${response.status}`); - return []; // Leeres Array zurückgeben bei Fehlern - } - return await response.json(); - } catch (error) { - console.error(`Fehler beim Abrufen von ${endpoint}:`, error); - return []; // Leeres Array zurückgeben bei Netzwerkfehlern - } - }; - - const post = async (endpoint, body) => { - try { - const response = await fetch(endpoint, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body) - }); - if (!response.ok) { - console.error(`API-Fehler: ${endpoint} antwortet mit Status ${response.status}`); - return {}; // Leeres Objekt zurückgeben bei Fehlern - } - return await response.json(); - } catch (error) { - console.error(`Fehler beim POST zu ${endpoint}:`, error); - return {}; // Leeres Objekt zurückgeben bei Netzwerkfehlern - } - }; - - const del = async endpoint => { - try { - const response = await fetch(endpoint, { method: 'DELETE' }); - if (!response.ok) { - console.error(`API-Fehler: ${endpoint} antwortet mit Status ${response.status}`); - return {}; // Leeres Objekt zurückgeben bei Fehlern - } - return await response.json(); - } catch (error) { - console.error(`Fehler beim DELETE zu ${endpoint}:`, error); - return {}; // Leeres Objekt zurückgeben bei Netzwerkfehlern - } - }; - - /* 3. Kategorien laden für Style-Informationen */ - let categories = await get('/api/categories'); - - /* 4. Daten laden und Rendering */ - const loadMindmap = async () => { - try { - // Initial nur die oberste Ebene laden - const rootNodes = await get('/api/mind_map_nodes?level=root'); - - // Graph leeren (für Reload-Fälle) - cy.elements().remove(); - - // Überprüfen, ob nodes ein Array ist, wenn nicht, setze es auf ein leeres Array - const nodesArray = Array.isArray(rootNodes) ? rootNodes : []; - - // Root-Knoten zum Graph hinzufügen - cy.add( - nodesArray.map(node => { - // Kategorie-Informationen für Styling abrufen - const category = categories.find(c => c.id === node.category_id) || {}; - - return { - data: { - id: node.id.toString(), - name: node.name, - description: node.description, - color: node.color_code || category.color_code || '#6b7280', - icon: node.icon || category.icon, - category_id: node.category_id, - hasChildren: node.has_children || false, // Neue Eigenschaft - expanded: false // Neue Eigenschaft für den Expansionsstatus - }, - position: node.x && node.y ? { x: node.x, y: node.y } : undefined - }; - }) - ); - - // Überprüfen, ob relationships ein Array ist, wenn nicht, setze es auf ein leeres Array - const relationshipsArray = Array.isArray(relationships) ? relationships : []; - - // Kanten zum Graph hinzufügen - cy.add( - relationshipsArray.map(rel => ({ - data: { - id: `${rel.parent_id}_${rel.child_id}`, - source: rel.parent_id.toString(), - target: rel.child_id.toString() - } - })) - ); - - // Wenn keine Knoten geladen wurden, Fallback-Knoten erstellen - if (nodesArray.length === 0) { - // Mindestens einen Standardknoten hinzufügen - cy.add({ - data: { - id: 'fallback-1', - name: 'Mindmap', - description: 'Erstellen Sie hier Ihre eigene Mindmap', - color: '#3b82f6', - icon: 'help-circle' - }, - position: { x: 300, y: 200 } - }); - - // Erfolgsmeldung anzeigen - console.log('Mindmap erfolgreich initialisiert mit Fallback-Knoten'); - - // Info-Meldung für Benutzer anzeigen - const infoBox = document.createElement('div'); - infoBox.classList.add('info-message'); - infoBox.style.position = 'absolute'; - infoBox.style.top = '50%'; - infoBox.style.left = '50%'; - infoBox.style.transform = 'translate(-50%, -50%)'; - infoBox.style.padding = '15px 20px'; - infoBox.style.backgroundColor = 'rgba(59, 130, 246, 0.9)'; - infoBox.style.color = 'white'; - infoBox.style.borderRadius = '8px'; - infoBox.style.zIndex = '5'; - infoBox.style.maxWidth = '80%'; - infoBox.style.textAlign = 'center'; - infoBox.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)'; - infoBox.innerHTML = 'Mindmap erfolgreich initialisiert.
Verwenden Sie die Werkzeugleiste, um Knoten hinzuzufügen.'; - - document.getElementById('cy').appendChild(infoBox); - - // Meldung nach 5 Sekunden ausblenden - setTimeout(() => { - infoBox.style.opacity = '0'; - infoBox.style.transition = 'opacity 0.5s ease'; - setTimeout(() => { - if (infoBox.parentNode) { - infoBox.parentNode.removeChild(infoBox); - } - }, 500); - }, 5000); - } - - // Layout anwenden wenn keine Positionsdaten vorhanden - const nodesWithoutPosition = cy.nodes().filter(node => - !node.position() || (node.position().x === 0 && node.position().y === 0) - ); - - if (nodesWithoutPosition.length > 0) { - cy.layout({ - name: 'breadthfirst', - directed: true, - padding: 30, - spacingFactor: 1.2 - }).run(); - } - } catch (error) { - console.error('Fehler beim Laden der Mindmap:', error); - alert('Die Mindmap konnte nicht geladen werden. Bitte prüfen Sie die Konsole für Details.'); - } - }; - - // Initial laden - await loadMindmap(); - - /* 5. Socket.IO für Echtzeit-Synchronisation */ - const socket = io(); - - socket.on('node_added', async (node) => { - // Kategorie-Informationen für Styling abrufen - const category = categories.find(c => c.id === node.category_id) || {}; - - cy.add({ - data: { - id: node.id.toString(), - name: node.name, - description: node.description, - color: node.color_code || category.color_code || '#6b7280', - icon: node.icon || category.icon, - category_id: node.category_id - } - }); - - // Layout neu anwenden, wenn nötig - if (!node.x || !node.y) { - cy.layout({ name: 'breadthfirst', directed: true, padding: 30 }).run(); - } - }); - - socket.on('node_updated', (node) => { - const cyNode = cy.$id(node.id.toString()); - if (cyNode.length > 0) { - // Kategorie-Informationen für Styling abrufen - const category = categories.find(c => c.id === node.category_id) || {}; - - cyNode.data({ - name: node.name, - description: node.description, - color: node.color_code || category.color_code || '#6b7280', - icon: node.icon || category.icon, - category_id: node.category_id - }); - - if (node.x && node.y) { - cyNode.position({ x: node.x, y: node.y }); - } - } - }); - - socket.on('node_deleted', (nodeId) => { - const cyNode = cy.$id(nodeId.toString()); - if (cyNode.length > 0) { - cy.remove(cyNode); - } - }); - - socket.on('relationship_added', (rel) => { - cy.add({ - data: { - id: `${rel.parent_id}_${rel.child_id}`, - source: rel.parent_id.toString(), - target: rel.child_id.toString() - } - }); - }); - - socket.on('relationship_deleted', (rel) => { - const edgeId = `${rel.parent_id}_${rel.child_id}`; - const cyEdge = cy.$id(edgeId); - if (cyEdge.length > 0) { - cy.remove(cyEdge); - } - }); - - socket.on('category_updated', async () => { - // Kategorien neu laden - categories = await get('/api/categories'); - // Nodes aktualisieren, die diese Kategorie verwenden - cy.nodes().forEach(node => { - const categoryId = node.data('category_id'); - if (categoryId) { - const category = categories.find(c => c.id === categoryId); - if (category) { - node.data('color', node.data('color_code') || category.color_code); - node.data('icon', node.data('icon') || category.icon); - } - } - }); - }); - - /* 6. UI-Interaktionen */ - // Knoten hinzufügen - const btnAddNode = document.getElementById('addNode'); - if (btnAddNode) { - btnAddNode.addEventListener('click', async () => { - const name = prompt('Knotenname eingeben:'); - if (!name) return; - - const description = prompt('Beschreibung (optional):'); - - // Kategorie auswählen - let categoryId = null; - if (categories.length > 0) { - const categoryOptions = categories.map((c, i) => `${i}: ${c.name}`).join('\n'); - const categoryChoice = prompt( - `Kategorie auswählen (Nummer eingeben):\n${categoryOptions}`, - '0' - ); - - if (categoryChoice !== null) { - const index = parseInt(categoryChoice, 10); - if (!isNaN(index) && index >= 0 && index < categories.length) { - categoryId = categories[index].id; - } - } - } - - // Knoten erstellen - await post('/api/mind_map_node', { - name, - description, - category_id: categoryId - }); - // Darstellung wird durch Socket.IO Event übernommen - }); - } - - // Verbindung hinzufügen - const btnAddEdge = document.getElementById('addEdge'); - if (btnAddEdge) { - btnAddEdge.addEventListener('click', async () => { - const sel = cy.$('node:selected'); - if (sel.length !== 2) { - alert('Bitte genau zwei Knoten auswählen (Parent → Child)'); - return; - } - - const [parent, child] = sel.map(node => node.id()); - await post('/api/node_relationship', { - parent_id: parent, - child_id: child - }); - // Darstellung wird durch Socket.IO Event übernommen - }); - } - - // Knoten bearbeiten - const btnEditNode = document.getElementById('editNode'); - if (btnEditNode) { - btnEditNode.addEventListener('click', async () => { - const sel = cy.$('node:selected'); - if (sel.length !== 1) { - alert('Bitte genau einen Knoten auswählen'); - return; - } - - const node = sel[0]; - const nodeData = node.data(); - - const name = prompt('Knotenname:', nodeData.name); - if (!name) return; - - const description = prompt('Beschreibung:', nodeData.description || ''); - - // Kategorie auswählen - let categoryId = nodeData.category_id; - if (categories.length > 0) { - const categoryOptions = categories.map((c, i) => `${i}: ${c.name}`).join('\n'); - const categoryChoice = prompt( - `Kategorie auswählen (Nummer eingeben):\n${categoryOptions}`, - categories.findIndex(c => c.id === categoryId).toString() - ); - - if (categoryChoice !== null) { - const index = parseInt(categoryChoice, 10); - if (!isNaN(index) && index >= 0 && index < categories.length) { - categoryId = categories[index].id; - } - } - } - - // Knoten aktualisieren - await post(`/api/mind_map_node/${nodeData.id}`, { - name, - description, - category_id: categoryId - }); - // Darstellung wird durch Socket.IO Event übernommen - }); - } - - // Knoten löschen - const btnDeleteNode = document.getElementById('deleteNode'); - if (btnDeleteNode) { - btnDeleteNode.addEventListener('click', async () => { - const sel = cy.$('node:selected'); - if (sel.length !== 1) { - alert('Bitte genau einen Knoten auswählen'); - return; - } - - if (confirm('Sind Sie sicher, dass Sie diesen Knoten löschen möchten?')) { - const nodeId = sel[0].id(); - await del(`/api/mind_map_node/${nodeId}`); - // Darstellung wird durch Socket.IO Event übernommen - } - }); - } - - // Verbindung löschen - const btnDeleteEdge = document.getElementById('deleteEdge'); - if (btnDeleteEdge) { - btnDeleteEdge.addEventListener('click', async () => { - const sel = cy.$('edge:selected'); - if (sel.length !== 1) { - alert('Bitte genau eine Verbindung auswählen'); - return; - } - - if (confirm('Sind Sie sicher, dass Sie diese Verbindung löschen möchten?')) { - const edge = sel[0]; - const parentId = edge.source().id(); - const childId = edge.target().id(); - - await del(`/api/node_relationship/${parentId}/${childId}`); - // Darstellung wird durch Socket.IO Event übernommen - } - }); - } - - // Layout aktualisieren - const btnReLayout = document.getElementById('reLayout'); - if (btnReLayout) { - btnReLayout.addEventListener('click', () => { - cy.layout({ - name: 'breadthfirst', - directed: true, - padding: 30, - spacingFactor: 1.2 - }).run(); - }); - } - - /* 7. Position speichern bei Drag & Drop */ - cy.on('dragfree', 'node', async (e) => { - const node = e.target; - const position = node.position(); - - await post(`/api/mind_map_node/${node.id()}/position`, { - x: Math.round(position.x), - y: Math.round(position.y) - }); - - // Andere Benutzer erhalten die Position über den node_updated Event - }); - -/* 8. Export-Funktion (optional) */ - const btnExport = document.getElementById('exportMindmap'); - if (btnExport) { - btnExport.addEventListener('click', () => { - const elements = cy.json().elements; - const exportData = { - nodes: elements.nodes.map(n => ({ - id: n.data.id, - name: n.data.name, - description: n.data.description, - category_id: n.data.category_id, - x: Math.round(n.position?.x || 0), - y: Math.round(n.position?.y || 0) - })), - relationships: elements.edges.map(e => ({ - parent_id: e.data.source, - child_id: e.data.target - })) - }; - - const blob = new Blob([JSON.stringify(exportData, null, 2)], {type: 'application/json'}); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'mindmap_export.json'; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - URL.revokeObjectURL(url); - }); - } - - /* 10. Filter-Funktion nach Kategorien (optional) */ - const setupCategoryFilters = () => { - const filterContainer = document.getElementById('category-filters'); - if (!filterContainer || !categories.length) return; - - filterContainer.innerHTML = ''; - - // "Alle anzeigen" Option - const allBtn = document.createElement('button'); - allBtn.innerText = 'Alle Kategorien'; - allBtn.className = 'category-filter active'; - allBtn.onclick = () => { - document.querySelectorAll('.category-filter').forEach(btn => btn.classList.remove('active')); - allBtn.classList.add('active'); - cy.nodes().removeClass('filtered').show(); - cy.edges().show(); - }; - filterContainer.appendChild(allBtn); - - // Filter-Button pro Kategorie - categories.forEach(category => { - const btn = document.createElement('button'); - btn.innerText = category.name; - btn.className = 'category-filter'; - btn.style.backgroundColor = category.color_code; - btn.style.color = '#fff'; - btn.onclick = () => { - document.querySelectorAll('.category-filter').forEach(btn => btn.classList.remove('active')); - btn.classList.add('active'); - - const matchingNodes = cy.nodes().filter(node => node.data('category_id') === category.id); - cy.nodes().addClass('filtered').hide(); - matchingNodes.removeClass('filtered').show(); - - // Verbindungen zu/von diesen Knoten anzeigen - cy.edges().hide(); - matchingNodes.connectedEdges().show(); - }; - filterContainer.appendChild(btn); - }); - }; - - // Filter-Funktionalität aktivieren (optional) - // setupCategoryFilters(); - - /* 11. Suchfunktion (optional) */ - const searchInput = document.getElementById('search-mindmap'); - if (searchInput) { - searchInput.addEventListener('input', (e) => { - const searchTerm = e.target.value.toLowerCase(); - - if (!searchTerm) { - cy.nodes().removeClass('search-hidden').show(); - cy.edges().show(); - return; - } - - cy.nodes().forEach(node => { - const name = node.data('name').toLowerCase(); - const description = (node.data('description') || '').toLowerCase(); - - if (name.includes(searchTerm) || description.includes(searchTerm)) { - node.removeClass('search-hidden').show(); - node.connectedEdges().show(); - } else { - node.addClass('search-hidden').hide(); - // Kanten nur verstecken, wenn beide verbundenen Knoten versteckt sind - node.connectedEdges().forEach(edge => { - const otherNode = edge.source().id() === node.id() ? edge.target() : edge.source(); - if (otherNode.hasClass('search-hidden')) { - edge.hide(); - } - }); - } - }); - }); - } - - console.log('Mindmap erfolgreich initialisiert'); -})(); \ No newline at end of file diff --git a/static/js/modules/mindmap.js b/static/js/modules/mindmap.js deleted file mode 100644 index e5eba3ae8fc1d1bc3e0b0ee3fbd5c4b8a4b06686..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 29000 zcmeI5>24g?mB;IIfO&_O9DsDj-Le%V$aw5{v`}MBEZK-;4`9Q9DJ~LiiqeoxE!ODm z<~{Ny&)`o%X8yl>`tUAwZ&kHOIT;`zq-u8E_NpMUCp(am(7b$7ah z?x@@C9(UW_({9my-<{~&dARdL-=B7e`n=!$r90MjSEKjBy>!;R`%2%RXzaE|^NCT% z`u(VTsL_x0`%>2%-Ai4c=>AUFZEv+-gyyR-kNHnD_e0J3Kx5ty|Kg~dn!VKOkHd)f zS7UyoQCBtgYWJHn{H}yg%)FwXS$9wK_5|ah{yz%88$Rr~(>)5izo+kawZn;i{L@T$ z915lf0mGC6cLFB!?sMJyUh{tlnC^8iwBm_A8zq(jjswwg)@^o|y65^Hsz1@E#TgH5 zt#>u%)e3`|KFbjjE6Wq%(D~Wak!$v-U^mqiGoma=j=`?J-HP8 zsQKUzCrgY{DKs2S8vhVRLpP)cT0RMKcOLmOxk-2VH%a=o*4>r_0h#RwM;>;s_03Lz zVyXLlha}$?uS_d$cQ^HESKlHXH+m!I-BysU#~N`Y_)k{U8`|GxXGi1N|B2vp%DFZg zW%dQpLs16U(Gj}8rrlItb$Q~AxiBDyPO}_WrN^m3*UEFdgS~1HQoQ^iUvp84O=n>G1dfW zGB~Hss!=_al!aErMj;VL!Y8*G4!2*C*nQ0a;$`=lKD`vZPW2fpyAk+wqA_#Xu>+0y zVI{vC-Ft;R`HFT0w_}aIqt)1h)%u($zsY%ml(@C|EXd8WCpjm=a6>EGZX4aZBXHr( z4#az`>{G#pCOfWIvTe6`3kxI8=qcl-BOcX)@$Ry{n(NbGdIS2fp8Z?fXzaPVx#@D;fe~06e8!=q7g{-8>h{6)$fJU|_l|V4ZCibwU*o(}Nds^a z2z+|#U`xqZ!lXC9j`TH8X6IM34%PqU<>VfnS zi(S`)e2>%@+!cq2qfFN}3Tr(tpxc;Al=0yga;wFcjSwM0t(7Sw>V1_9J)+m&244!fVE>sHCQNO}-iVpSf! zC0hJaaoJR_7GvI7_lb06*ltHli8p+v@ww%uQbT?~3_X|Z9qTi3)KpoD>!((8co*tn z=&oCzQs1`{n5=%Zj+Q$_e*H+hmGI;~0+0S&5TS2)vZ?a!JNR`y-{G_T`jK`X=TIK; ztjndiSI#Yqn(>$WK^EZ5QW?W#Ndgv$eXfZ<_|@xz5?@A!u~^-IH~5cq&0)XkaFo~5 zpSIzmPD><`LiQhu`af5saXvmcOw(Z@>)6jA`9itRt#iTw7A6tXXgPKKcjBDYJT_Eq zt3|-y4MfM$O7*K(NCTb;ZC##K3djYI#4Wt`Qqn^m279w7`N?Bnveu#X+Yz+q1MJk# zmSQeVE|~9Gu6Z$eRNQf>ZUA?Q?(d5pF^9}KGA(b4`_(XPWmGvO7Ttfz^24Q<(j)V} zu{ydTT`!}2a+*)hzK<}}Di(Mhs~357f{e^+5|QV&gV&hIa!dZWcD^a>F&2MY(BC+V z_TL5`?YQ~k@qxx(Rl1?imNz03cB6= zrYFvpH7qo5p&9E)GFcpFSHluv^6n?`r>ks|*o1nv*JqvydQMN#v*S=_r}|43YbJc~ zV=bMC9?YW_k8-UJw=J7Q6`gu)^o*XH7!2ErF3Hp$XZu6*dX3TdY*T(5H|i1*vkyi4 zJYI7wS}@qjG89Bh?R?@mU~xPkD=o;O5j78_=9VCP6l4h=Sj8RQaLQ+VuoG+Uj^XKe z!Br>>Y;Q_alOZbpR;jZ73%nb&I@bS2Gw#pyjpbKVcd&(=C~&^kmT{*|loIEGNmBgY zPJ(X=5;9*q12sx)2TiSGSkDe}yI?Sw&h-0R`nDlzbjxG7R@AIYe}}frx8b}g+HWhe znd^UeF_%=p>!;#E>Dk}~y7=dykJ~Gs_e|d*AuSz`lxKvWdHTNB!mhsOdKjc<7|}lD z{JR*h(5JO`M|nRJ6hOMImP~eMl8hDSGgOW-!ilWaPolcz0grUYXO@ys`kLvI(6a5d zvm>*GX_rgeW4Wf4_A^?EP1WIUNQS^X_RYkTGwYk#=<-Tm9|n3eUMmWkX(j8)!VjRo z`yu8sd$!PSV|FQ(lw3X>n|1ZudT^}%PUHvn>8ath?hAQvv?=;Yct_Q!FHLjl8ury{ zO*L(GYO{ysqp_=~v~V`oVY{!D`#YxlQ3r5K<5sgp(Hd+X6(0*bWF3p0(xSinJVZB) z#_IeioW}I%b6KSE2-~sP39$_)lzbxcj(vt>-7$SRw2q9pb}89oogPGXkz1@*a&UMB z=w#>jIV9%E%G3SfwTN2MZl71xT*bA*uh?xc$oJ2)5hD52rxJ1aPQx(yF37^cN(X!| zdPc_jU~2O%E5E7PX@4B>|4x0O?~ioW_=5tGPr>Ua0~OdSRv~A@o&XoxwLV;QeX;@^I}g=4 zXWCZQ6yX4?nw@p2q0hU50N%>mwaU-PhtVyoPdgWsgZ2zU@Ue z>(?WAJeOD6)6ZeZ>`eEdcuFgF9$SYfA0I%ShAIR0*eZAXE6$S%AX#IUCZCOr-`5IH zH4iFmXcg09gK|&b)aV#%7qz?2J^VNNGgLLd9Y&PVWs85&%fmn9&1(x(Dcbd(TG!ac z#MN=ni@bNEAxhBD{3~bq$lii_3n5bzsAQ%ZDNo`u!z+3hDe zD(fKDHQmNOorgD`qt|K!QIE=}8q7;YDaxgPH+Z{;;xF)GA^-mM;6xgWHFg~+X&kw8 z9%{Qk<*5<3{noo@&s#w+Vm*sK@q$!>sh<#E(fx0Iwd2-5=g5y*5kKx0XsX?b9LDQ? zuic4qHw7qZ{-*)%8~Q?kzou_E3AG5$prz)C%Y(w$G{cNV_Z3)p^<| ze=5ejxMKqBEw7N;USdki0L=P6m4sU?yp;ZKh%(;6inhYp7NleloaWRk6|sI3cLYM@ zW4(@Ew<-Pl0shLUFqSRHE-8zEe9e;}PdS~P!*=yb1M`MGoXP{oei^>&=%6Zc0kycID9LBnKH)?OB=L9ZD@!n!OM! z)b;+C!CE=RJ`@HqV`A30Wh!TIstMlMYEHW@sn>oc>&1h7(Tjl7#C~tIa#&fOu$5{YiSk>!JC$G4*kmFe9C)6^h_9C|8g47C=QId=FyBW>HT*_>A zdvx7DraO^Wm@h*PEN8R+!iBK*Q!d6JZ^#{eDy7$GLtsyVU=PW?$cd?89q2c-z+(0M zl&bZlV9o)PKF_>TjM}iYvqqQYbRDk{qGMRevC5UjPE(#^_TADLBGqW4?_M}5O0~1j zO<&Eg=fUA>i2v5X!FNq@Nnv(eu1e0*@2BD7t2>`lDn;uQMlzE62AX*n%2 zDpx6gFEjM%ey3ci{M{pv=^1LdLiu~l@Grt|m8+M(r~Czn^!LcmX%&HT?eh0jR@f{3 zJ?>SrI^{~O-_2vS?zX;0Y(9mVdt<4iN&g2SYwAp75<_3(`H_+G90hf|Tk`8n1A^O}r9wZv3*J(bVf4d6grV>@uQBPe1C< zAGG3_)Dx5$bw6@|gKxjSL3M+e<^8u%->|cHs~}r7iAwU{Q>6or^m%B!SoeJqM2K{K zEJIFL*WCJk_;79mocETM;`Ja&W8^Zo zc04(Sz>@(n64J6YExM(9P)3+dqNaF;R-W@)y(B(a<>y}URFw#BN>mC2bd+EzBQ(Z`xLO{G zE_80^(p0CO+x}9@{K=U3Y>(Gyr$OuM`mDCRav~e?aUS^m^4j)5J~H~yH;)vCWQrOs zxicrC(`Cw`^J~Oo9chcta`w+6ru*E_&fe94ES=w<;vdjm^#9)KGub_{|J|UAoIu*y z&8wo?VDw03yOcze@W@rGg8jpCo?Y>fh0Kcq94~dFq7@WIIRl zXxHK_o`-4m=$G;A&~uOZ^Np>zmbasE)?VJx=05;+umBSq3T!7uK5hV zrh0EP>)LMj#<~N1RloAw22TfA2E0y(w69=&{Ma_un0k)wvmYq0vAw;UKka+v9i`MX z(sx*TMe!Zg$F|S@#cJX^;!OM*KKXYjqNnk1TGyy8_`meMEVm>bP+@b$U+bds?7(E% z-$>#;R@Ph33F(zHsTk8&hwOoW;&)mt#GJ{=QS41Afrg$VIjyV5u2Z>hvi;sK^~12`Nd z?frYdzNx2z&WD2UME{^sd}7d^r^YjV8aTmS{L-<;lkwQO5>H~&U*cU+P`m8qFMU

;oPZ{ZUUib1rs$wSIi3GtgQ$HI|UG{!NT=_$mP z#Yl1E%<53{$d&WAx*L3)Ync^=rs?~e?LO~BFzQU%&EFy2&y3PtwzOi@J}A09U}LtW z1&;!Zyqz9A45zxaWOOM#Hmj7A_WYsz$+f9YODKuF^XzPmmIirA$>}*+>j_WOEvRo? z^EVy1MCEp@uWfCK_45>mycHX!GKbFi8EHNrox=8_OYr@@0ludz5<_6Ejgz*%SGb5P zEGFGl4Dq4XU8sBZlb{_}^#3=Ckf!u7QK8}u6ut+V`#`JtZmd#r&ZPl)CQHW7A)&rj zp8eD%F2(ayJ)0@@+%kMA{ILVSQ*Sl2UYHB?#)qj{K-G@tr068sYj9y;hlX z5EJ&_PmgbXRp9J=&97)Ht0O7!Y(vr5=c3&Gp!K;u%4hm-aK)ksx-M8_+Ri?IBgkp= zq4Trn;)pYWXguzn0_Rxwn#1GuX7+ybykV@9u4NG%iXn`=vU5ptolDUo__T2g;=90k zx?PBB+=gxG8@{8r<~v1<_x1CI?x$~ufi_f;`uk&>vGa5yy`J!Pg}Uu=_=c$9+C&zR zzWr#UVI8mno-+WqSrn_*po#vC*_d`N^;)=-rN;USGmK*6lrN!^yq&YTKP)5f;T? zi^~5_5Z>L#TSen5aXkKQsdTjYd-gM^u1R`{DlB4QmiZog0-Bh}pMB+73pijoDOT6s zQbc?~M8)~)P1(~sx{|4;`4;Qi-*f6m;Zx3`Y+ZbOw4I;nH?zh5*DEX+jNN&)y1mP! zokhJov&XT^&Z4D0oZ!^{%Q&2yT1RajQMvu%uEQVqYU_~0S!(>{g46TLsz(3x-7j#9 zXsyOi?8)$Z(Hs_NMx2vYfssA8rc-4Q?Kf(T`))YyCo%DvT5NKk+kRr_nMa$tZgc(W z81|{1pA6Jaoc!%y{oQj(@V)$6_Xhpw(Z{D2#=pzCL4Q=vV}GmOLXu1D!n@B*E7m!; z?NcS^H1(~zzbWBy8?v16hBC8Hr8gjY^mh;57Cz>K?cF%(- { + cy.add({ + group: 'nodes', + data: { + ...subtheme, + expanded: false + } + }); + + // Kante zum Elternknoten hinzufügen + cy.add({ + group: 'edges', + data: { + id: `${node.id()}_${subtheme.id}`, + source: node.id(), + target: subtheme.id + } + }); + }); + + // Node als expandiert markieren + node.data('expanded', true); + + // Layout neu berechnen mit Animation + cy.layout({ + name: 'cose', + animate: true, + animationDuration: 500, + refresh: 20, + fit: true, + padding: 30 + }).run(); + + // Erfolgsmeldung anzeigen + showFlash('Subthemen erfolgreich geladen', 'success'); + + } catch (error) { + console.error('Fehler beim Laden der Subthemen:', error); + showFlash('Fehler beim Laden der Subthemen', 'error'); + } } \ No newline at end of file diff --git a/static/mindmap.js b/static/mindmap.js deleted file mode 100644 index f6a2257..0000000 --- a/static/mindmap.js +++ /dev/null @@ -1,2061 +0,0 @@ -/** - * MindMap D3.js Modul - * Visualisiert die Mindmap mit D3.js - */ - -class MindMapVisualization { - constructor(containerSelector, options = {}) { - this.containerSelector = containerSelector; - this.container = d3.select(containerSelector); - this.width = options.width || this.container.node().clientWidth || 800; - this.height = options.height || 800; // Erhöhung der Standardhöhe für bessere Sichtbarkeit - this.nodeRadius = options.nodeRadius || 22; - this.selectedNodeRadius = options.selectedNodeRadius || 28; - this.linkDistance = options.linkDistance || 150; - this.chargeStrength = options.chargeStrength || -1000; - this.centerForce = options.centerForce || 0.15; - this.onNodeClick = options.onNodeClick || ((node) => console.log('Node clicked:', node)); - - this.nodes = []; - this.links = []; - this.simulation = null; - this.svg = null; - this.linkElements = null; - this.nodeElements = null; - this.textElements = null; - this.tooltipEnabled = options.tooltipEnabled !== undefined ? options.tooltipEnabled : true; - - this.mouseoverNode = null; - this.selectedNode = null; - - this.zoomFactor = 1; - this.tooltipDiv = null; - this.isLoading = true; - - // Flash-Nachrichten-Container - this.flashContainer = null; - - // Authentischere Farbpalette mit dezenten, professionellen Farben - this.colorPalette = { - 'default': '#6b7280', // Grau - 'root': '#4f46e5', // Indigo - 'philosophy': '#3b82f6', // Blau - 'science': '#10b981', // Smaragdgrün - 'technology': '#6366f1', // Indigo - 'arts': '#8b5cf6', // Violett - 'ai': '#7c3aed', // Violett - 'ethics': '#475569', // Slate - 'math': '#0369a1', // Dunkelblau - 'psychology': '#0284c7', // Hellblau - 'biology': '#059669', // Grün - 'literature': '#4338ca', // Indigo - 'history': '#0f766e', // Teal - 'economics': '#374151', // Dunkelgrau - 'sociology': '#4f46e5', // Indigo - 'design': '#0891b2', // Cyan - 'languages': '#2563eb' // Blau - }; - - // Sicherstellen, dass der Container bereit ist - if (this.container.node()) { - this.init(); - this.setupDefaultNodes(); - this.setupFlashMessages(); - - // Sofortige Datenladung - window.setTimeout(() => { - this.loadData(); - }, 100); - } else { - console.error('Mindmap-Container nicht gefunden:', containerSelector); - } - } - - // Flash-Nachrichten-System einrichten - setupFlashMessages() { - // Flash-Container erstellen, falls er noch nicht existiert - if (!document.getElementById('mindmap-flash-container')) { - this.flashContainer = document.createElement('div'); - this.flashContainer.id = 'mindmap-flash-container'; - this.flashContainer.className = 'mindmap-flash-container'; - this.flashContainer.style.position = 'fixed'; - this.flashContainer.style.top = '20px'; - this.flashContainer.style.right = '20px'; - this.flashContainer.style.zIndex = '1000'; - this.flashContainer.style.maxWidth = '350px'; - this.flashContainer.style.display = 'flex'; - this.flashContainer.style.flexDirection = 'column'; - this.flashContainer.style.gap = '10px'; - document.body.appendChild(this.flashContainer); - } else { - this.flashContainer = document.getElementById('mindmap-flash-container'); - } - - // Prüfen, ob Server-seitige Flash-Nachrichten existieren und anzeigen - this.checkForServerFlashMessages(); - } - - // Prüft auf Server-seitige Flash-Nachrichten - async checkForServerFlashMessages() { - try { - const response = await fetch('/api/get_flash_messages'); - if (response.ok) { - const messages = await response.json(); - messages.forEach(message => { - this.showFlash(message.message, message.category); - }); - } - } catch (err) { - console.error('Fehler beim Abrufen der Flash-Nachrichten:', err); - } - } - - // Zeigt eine Flash-Nachricht an - showFlash(message, type = 'info', duration = 5000) { - if (!this.flashContainer) return; - - const flashElement = document.createElement('div'); - flashElement.className = `mindmap-flash flash-${type}`; - flashElement.style.padding = '12px 18px'; - flashElement.style.borderRadius = '8px'; - flashElement.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)'; - flashElement.style.display = 'flex'; - flashElement.style.alignItems = 'center'; - flashElement.style.justifyContent = 'space-between'; - flashElement.style.fontSize = '14px'; - flashElement.style.fontWeight = '500'; - flashElement.style.backdropFilter = 'blur(10px)'; - flashElement.style.opacity = '0'; - flashElement.style.transform = 'translateY(-20px)'; - flashElement.style.transition = 'all 0.3s ease'; - - // Spezifische Stile je nach Nachrichtentyp - switch(type) { - case 'success': - flashElement.style.backgroundColor = 'rgba(34, 197, 94, 0.9)'; - flashElement.style.borderLeft = '5px solid #16a34a'; - flashElement.style.color = 'white'; - break; - case 'error': - flashElement.style.backgroundColor = 'rgba(239, 68, 68, 0.9)'; - flashElement.style.borderLeft = '5px solid #dc2626'; - flashElement.style.color = 'white'; - break; - case 'warning': - flashElement.style.backgroundColor = 'rgba(245, 158, 11, 0.9)'; - flashElement.style.borderLeft = '5px solid #d97706'; - flashElement.style.color = 'white'; - break; - default: // info - flashElement.style.backgroundColor = 'rgba(59, 130, 246, 0.9)'; - flashElement.style.borderLeft = '5px solid #2563eb'; - flashElement.style.color = 'white'; - } - - // Icon je nach Nachrichtentyp - let icon = ''; - switch(type) { - case 'success': - icon = ''; - break; - case 'error': - icon = ''; - break; - case 'warning': - icon = ''; - break; - default: - icon = ''; - } - - // Inhalt der Nachricht mit Icon - const contentWrapper = document.createElement('div'); - contentWrapper.style.display = 'flex'; - contentWrapper.style.alignItems = 'center'; - contentWrapper.style.gap = '12px'; - - const iconElement = document.createElement('div'); - iconElement.className = 'flash-icon'; - iconElement.innerHTML = icon; - - const textElement = document.createElement('div'); - textElement.className = 'flash-text'; - textElement.textContent = message; - - contentWrapper.appendChild(iconElement); - contentWrapper.appendChild(textElement); - - // Schließen-Button - const closeButton = document.createElement('button'); - closeButton.className = 'flash-close'; - closeButton.innerHTML = ''; - closeButton.style.background = 'none'; - closeButton.style.border = 'none'; - closeButton.style.color = 'currentColor'; - closeButton.style.cursor = 'pointer'; - closeButton.style.marginLeft = '15px'; - closeButton.style.padding = '3px'; - closeButton.style.fontSize = '14px'; - closeButton.style.opacity = '0.7'; - closeButton.style.transition = 'opacity 0.2s'; - - closeButton.addEventListener('mouseover', () => { - closeButton.style.opacity = '1'; - }); - - closeButton.addEventListener('mouseout', () => { - closeButton.style.opacity = '0.7'; - }); - - closeButton.addEventListener('click', () => { - this.removeFlash(flashElement); - }); - - // Zusammenfügen - flashElement.appendChild(contentWrapper); - flashElement.appendChild(closeButton); - - // Zum Container hinzufügen - this.flashContainer.appendChild(flashElement); - - // Animation einblenden - setTimeout(() => { - flashElement.style.opacity = '1'; - flashElement.style.transform = 'translateY(0)'; - }, 10); - - // Automatisches Ausblenden nach der angegebenen Zeit - if (duration > 0) { - setTimeout(() => { - this.removeFlash(flashElement); - }, duration); - } - - return flashElement; - } - - // Entfernt eine Flash-Nachricht mit Animation - removeFlash(flashElement) { - if (!flashElement) return; - - flashElement.style.opacity = '0'; - flashElement.style.transform = 'translateY(-20px)'; - - setTimeout(() => { - if (flashElement.parentNode) { - flashElement.parentNode.removeChild(flashElement); - } - }, 300); - } - - // Standardknoten als Fallback einrichten, falls die API nicht reagiert - setupDefaultNodes() { - // Basis-Mindmap mit Hauptthemen - const defaultNodes = [ - { id: "root", name: "Wissen", description: "Zentrale Wissensbasis", thought_count: 3 }, - { id: "philosophy", name: "Philosophie", description: "Philosophisches Denken", thought_count: 2 }, - { id: "science", name: "Wissenschaft", description: "Wissenschaftliche Erkenntnisse", thought_count: 5 }, - { id: "technology", name: "Technologie", description: "Technologische Entwicklungen", thought_count: 7 }, - { id: "arts", name: "Künste", description: "Künstlerische Ausdrucksformen", thought_count: 4 }, - { id: "ai", name: "Künstliche Intelligenz", description: "KI-Forschung und Anwendungen", thought_count: 6 }, - { id: "ethics", name: "Ethik", description: "Moralische Grundsätze", thought_count: 2 }, - { id: "math", name: "Mathematik", description: "Mathematische Konzepte", thought_count: 3 }, - { id: "psychology", name: "Psychologie", description: "Menschliches Verhalten und Kognition", thought_count: 4 }, - { id: "biology", name: "Biologie", description: "Lebenswissenschaften", thought_count: 3 }, - { id: "literature", name: "Literatur", description: "Literarische Werke und Analysen", thought_count: 2 } - ]; - - const defaultLinks = [ - { source: "root", target: "philosophy" }, - { source: "root", target: "science" }, - { source: "root", target: "technology" }, - { source: "root", target: "arts" }, - { source: "science", target: "math" }, - { source: "science", target: "biology" }, - { source: "technology", target: "ai" }, - { source: "philosophy", target: "ethics" }, - { source: "philosophy", target: "psychology" }, - { source: "arts", target: "literature" }, - { source: "ai", target: "ethics" }, - { source: "psychology", target: "biology" } - ]; - - // Als Fallback verwenden, falls die API fehlschlägt - this.defaultNodes = defaultNodes; - this.defaultLinks = defaultLinks; - } - - init() { - // SVG erstellen, wenn noch nicht vorhanden - if (!this.svg) { - // Container zuerst leeren und Loading-State ausblenden - const loadingOverlay = this.container.select('.mindmap-loading'); - if (loadingOverlay) { - loadingOverlay.style('opacity', 0.8); - } - - this.svg = this.container - .append('svg') - .attr('width', '100%') - .attr('height', this.height) - .attr('viewBox', `0 0 ${this.width} ${this.height}`) - .attr('class', 'mindmap-svg') - .call( - d3.zoom() - .scaleExtent([0.1, 5]) - .on('zoom', (event) => { - this.handleZoom(event.transform); - }) - ); - - // Hauptgruppe für alles, was zoom-transformierbar ist - this.g = this.svg.append('g'); - - // SVG-Definitionen für Filter und Effekte - const defs = this.g.append('defs'); - - // Verbesserte Glasmorphismus- und Glow-Effekte - - // Basis Glow-Effekt - D3Extensions.createGlowFilter(defs, 'glow-effect', '#b38fff', 8); - - // Spezifische Effekte für verschiedene Zustände - D3Extensions.createGlowFilter(defs, 'hover-glow', '#58a9ff', 6); - D3Extensions.createGlowFilter(defs, 'selected-glow', '#b38fff', 10); - - // Schatten für alle Knoten - D3Extensions.createShadowFilter(defs, 'shadow-effect'); - - // Glasmorphismus-Effekt für Knoten - D3Extensions.createGlassMorphismFilter(defs, 'glass-effect'); - - // Erweiterte Effekte - this.createAdvancedNodeEffects(defs); - - // Tooltip initialisieren mit verbessertem Glasmorphism-Stil - if (!d3.select('body').select('.node-tooltip').size()) { - this.tooltipDiv = d3.select('body') - .append('div') - .attr('class', 'node-tooltip') - .style('opacity', 0) - .style('position', 'absolute') - .style('pointer-events', 'none') - .style('background', 'rgba(24, 28, 45, 0.85)') - .style('color', '#ffffff') - .style('border', '1px solid rgba(179, 143, 255, 0.3)') - .style('border-radius', '16px') - .style('padding', '12px 16px') - .style('font-size', '14px') - .style('font-weight', '500') - .style('line-height', '1.5') - .style('max-width', '280px') - .style('box-shadow', '0 12px 30px rgba(0, 0, 0, 0.5), 0 0 15px rgba(179, 143, 255, 0.25)') - .style('backdrop-filter', 'blur(20px)') - .style('-webkit-backdrop-filter', 'blur(20px)') - .style('z-index', '1000'); - } else { - this.tooltipDiv = d3.select('body').select('.node-tooltip'); - } - - // Initialisierung abgeschlossen - Loading-Overlay ausblenden - setTimeout(() => { - if (loadingOverlay) { - loadingOverlay.transition() - .duration(500) - .style('opacity', 0) - .on('end', function() { - loadingOverlay.style('display', 'none'); - }); - } - }, 1000); - } - - // Force-Simulation initialisieren - this.simulation = d3.forceSimulation() - .force('link', d3.forceLink().id(d => d.id).distance(this.linkDistance)) - .force('charge', d3.forceManyBody().strength(this.chargeStrength)) - .force('center', d3.forceCenter(this.width / 2, this.height / 2).strength(this.centerForce)) - .force('collision', d3.forceCollide().radius(this.nodeRadius * 2.5)); - - // Globale Mindmap-Instanz für externe Zugriffe setzen - window.mindmapInstance = this; - } - - // Erstellt erweiterte Effekte für die Knoten - createAdvancedNodeEffects(defs) { - // Verbesserte innere Leuchteffekte für Knoten - const innerGlow = defs.append('filter') - .attr('id', 'inner-glow') - .attr('x', '-50%') - .attr('y', '-50%') - .attr('width', '200%') - .attr('height', '200%'); - - // Farbiger innerer Glühen - innerGlow.append('feGaussianBlur') - .attr('in', 'SourceAlpha') - .attr('stdDeviation', 2) - .attr('result', 'blur'); - - innerGlow.append('feOffset') - .attr('in', 'blur') - .attr('dx', 0) - .attr('dy', 0) - .attr('result', 'offsetBlur'); - - innerGlow.append('feFlood') - .attr('flood-color', 'rgba(179, 143, 255, 0.8)') - .attr('result', 'glowColor'); - - innerGlow.append('feComposite') - .attr('in', 'glowColor') - .attr('in2', 'offsetBlur') - .attr('operator', 'in') - .attr('result', 'innerGlow'); - - // Verbinden der Filter - const innerGlowMerge = innerGlow.append('feMerge'); - innerGlowMerge.append('feMergeNode') - .attr('in', 'innerGlow'); - innerGlowMerge.append('feMergeNode') - .attr('in', 'SourceGraphic'); - - // 3D-Glaseffekt mit verbesserter Tiefe - D3Extensions.create3DGlassEffect(defs, '3d-glass'); - - // Pulseffekt für Hervorhebung - const pulseFilter = defs.append('filter') - .attr('id', 'pulse-effect') - .attr('x', '-50%') - .attr('y', '-50%') - .attr('width', '200%') - .attr('height', '200%'); - - // Animation definieren - const pulseAnimation = pulseFilter.append('feComponentTransfer') - .append('feFuncA') - .attr('type', 'linear') - .attr('slope', '1.5'); - } - - // Behandelt die Zoom-Transformation für die SVG mit verbesserter Anpassung - handleZoom(transform) { - this.g.attr('transform', transform); - this.zoomFactor = transform.k; - - // Knotengröße dynamisch an Zoom anpassen für bessere Lesbarkeit - if (this.nodeElements) { - // Berechne relativen Radius basierend auf Zoom - const nodeScaleFactor = 1 / Math.sqrt(transform.k); - const minRadiusFactor = 0.6; // Minimale Größe beim Herauszoomen - const maxRadiusFactor = 1.2; // Maximale Größe beim Hineinzoomen - - // Beschränke den Skalierungsfaktor in sinnvollen Grenzen - const cappedScaleFactor = Math.max(minRadiusFactor, Math.min(nodeScaleFactor, maxRadiusFactor)); - - this.nodeElements.selectAll('circle') - .attr('r', d => { - return d === this.selectedNode - ? this.selectedNodeRadius * cappedScaleFactor - : this.nodeRadius * cappedScaleFactor; - }) - .attr('stroke-width', 2 * cappedScaleFactor); // Strichstärke anpassen - - // Schriftgröße dynamisch anpassen - this.nodeElements.selectAll('text') - .style('font-size', `${14 * cappedScaleFactor}px`) - .attr('dy', 4 * cappedScaleFactor); - - // Verbindungslinien anpassen - this.linkElements - .attr('stroke-width', 1.5 * cappedScaleFactor) - .attr('marker-end', transform.k < 0.6 ? 'none' : 'url(#arrowhead)'); // Pfeile bei starkem Zoom ausblenden - } - } - - // Lädt die Mindmap-Daten - async loadData() { - try { - // Zeige Lade-Animation - this.showLoading(); - - // API-Aufruf durchführen, um die Kategorien und ihre Knoten zu laden - const response = await fetch('/api/mindmap/public'); - if (!response.ok) { - throw new Error('API-Fehler: ' + response.statusText); - } - - const data = await response.json(); - console.log('Geladene Mindmap-Daten:', data); - - // Verarbeite die hierarchischen Daten in flache Knoten und Links - const processed = this.processApiData(data); - this.nodes = processed.nodes; - this.links = processed.links; - - // Verbindungszählungen aktualisieren - this.updateConnectionCounts(); - - // Visualisierung aktualisieren - this.updateVisualization(); - - // Lade-Animation ausblenden - this.hideLoading(); - - // Erfolgreiche Ladung melden - this.showFlash('Mindmap-Daten erfolgreich geladen', 'success'); - } catch (error) { - console.error('Fehler beim Laden der Mindmap-Daten:', error); - - // Bei einem Fehler die Fallback-Daten verwenden - this.nodes = this.defaultNodes; - this.links = this.defaultLinks; - - // Verbindungszählungen auch für Fallback-Daten aktualisieren - this.updateConnectionCounts(); - - // Fehler anzeigen - this.showError('Mindmap-Daten konnten nicht geladen werden. Verwende Standarddaten.'); - this.showFlash('Fehler beim Laden der Mindmap-Daten. Standarddaten werden angezeigt.', 'error'); - - // Visualisierung auch im Fehlerfall aktualisieren - this.updateVisualization(); - this.hideLoading(); - } - } - - // Verarbeitet die API-Daten in das benötigte Format - processApiData(apiData) { - // Erstelle einen Root-Knoten, der alle Kategorien verbindet - const rootNode = { - id: "root", - name: "Wissen", - description: "Zentrale Wissensbasis", - thought_count: 0 - }; - - let nodes = [rootNode]; - let links = []; - - // Für jede Kategorie Knoten und Verbindungen erstellen - apiData.forEach(category => { - // Kategorie als Knoten hinzufügen - const categoryNode = { - id: `category_${category.id}`, - name: category.name, - description: category.description, - color_code: category.color_code, - icon: category.icon, - thought_count: 0, - type: 'category' - }; - - nodes.push(categoryNode); - - // Mit Root-Knoten verbinden - links.push({ - source: "root", - target: categoryNode.id - }); - - // Alle Knoten aus dieser Kategorie hinzufügen - if (category.nodes && category.nodes.length > 0) { - category.nodes.forEach(node => { - // Zähle die Gedanken für die Kategorie - categoryNode.thought_count += node.thought_count || 0; - - const mindmapNode = { - id: `node_${node.id}`, - name: node.name, - description: node.description || '', - color_code: node.color_code || category.color_code, - thought_count: node.thought_count || 0, - type: 'node', - categoryId: category.id - }; - - nodes.push(mindmapNode); - - // Mit Kategorie-Knoten verbinden - links.push({ - source: categoryNode.id, - target: mindmapNode.id - }); - }); - } - - // Rekursiv Unterkategorien verarbeiten - if (category.children && category.children.length > 0) { - this.processSubcategories(category.children, nodes, links, categoryNode.id); - } - }); - - // Root-Knoten-Gedankenzähler aktualisieren - rootNode.thought_count = nodes.reduce((sum, node) => sum + (node.thought_count || 0), 0); - - return { nodes, links }; - } - - // Verarbeitet Unterkategorien rekursiv - processSubcategories(subcategories, nodes, links, parentId) { - subcategories.forEach(category => { - // Kategorie als Knoten hinzufügen - const categoryNode = { - id: `category_${category.id}`, - name: category.name, - description: category.description, - color_code: category.color_code, - icon: category.icon, - thought_count: 0, - type: 'subcategory' - }; - - nodes.push(categoryNode); - - // Mit Eltern-Kategorie verbinden - links.push({ - source: parentId, - target: categoryNode.id - }); - - // Alle Knoten aus dieser Kategorie hinzufügen - if (category.nodes && category.nodes.length > 0) { - category.nodes.forEach(node => { - // Zähle die Gedanken für die Kategorie - categoryNode.thought_count += node.thought_count || 0; - - const mindmapNode = { - id: `node_${node.id}`, - name: node.name, - description: node.description || '', - color_code: node.color_code || category.color_code, - thought_count: node.thought_count || 0, - type: 'node', - categoryId: category.id - }; - - nodes.push(mindmapNode); - - // Mit Kategorie-Knoten verbinden - links.push({ - source: categoryNode.id, - target: mindmapNode.id - }); - }); - } - - // Rekursiv Unterkategorien verarbeiten - if (category.children && category.children.length > 0) { - this.processSubcategories(category.children, nodes, links, categoryNode.id); - } - }); - } - - // Zeigt den Ladebildschirm an - showLoading() { - const loadingOverlay = this.container.select('.mindmap-loading'); - - if (loadingOverlay && !loadingOverlay.empty()) { - loadingOverlay - .style('display', 'flex') - .style('opacity', 1); - - // Ladebalken-Animation - const progressBar = loadingOverlay.select('.loading-progress'); - if (!progressBar.empty()) { - let progress = 0; - const progressInterval = setInterval(() => { - progress += Math.random() * 15; - if (progress > 90) { - progress = 90 + Math.random() * 5; - clearInterval(progressInterval); - } - updateProgress(progress); - }, 200); - - function updateProgress(progress) { - progressBar.style('width', `${Math.min(progress, 95)}%`); - } - } - } - } - - // Blendet den Ladebildschirm aus - hideLoading() { - const loadingOverlay = this.container.select('.mindmap-loading'); - - if (loadingOverlay && !loadingOverlay.empty()) { - // Lade-Fortschritt auf 100% setzen - const progressBar = loadingOverlay.select('.loading-progress'); - if (!progressBar.empty()) { - progressBar.transition() - .duration(300) - .style('width', '100%'); - } - - // Overlay ausblenden - setTimeout(() => { - loadingOverlay.transition() - .duration(500) - .style('opacity', 0) - .on('end', function() { - loadingOverlay.style('display', 'none'); - }); - }, 400); - } - } - - // Verarbeitet hierarchische Daten in flache Knoten und Links - processHierarchicalData(hierarchicalNodes, parentId = null) { - let nodes = []; - let links = []; - - for (const node of hierarchicalNodes) { - nodes.push({ - id: node.id, - name: node.name, - description: node.description || '', - thought_count: node.thought_count || 0 - }); - - if (parentId) { - links.push({ - source: parentId, - target: node.id - }); - } - - if (node.children && node.children.length > 0) { - const { nodes: childNodes, links: childLinks } = this.processHierarchicalData(node.children, node.id); - nodes = [...nodes, ...childNodes]; - links = [...links, ...childLinks]; - } - } - - return { nodes, links }; - } - - // Generiert eine konsistente Farbe basierend auf dem Knotennamen - generateColorFromString(str) { - // Authentischere, dezente Farben für wissenschaftliche Darstellung - const colors = [ - '#4f46e5', '#0369a1', '#0f766e', '#374151', '#4338ca', - '#0284c7', '#059669', '#475569', '#6366f1', '#0891b2' - ]; - - let hash = 0; - for (let i = 0; i < str.length; i++) { - hash = str.charCodeAt(i) + ((hash << 5) - hash); - } - - return colors[Math.abs(hash) % colors.length]; - } - - /** - * Aktualisiert die Visualisierung basierend auf den aktuellen Daten - */ - updateVisualization() { - if (!this.g || !this.nodes.length) return; - - // Daten für Simulation vorbereiten - // Kopieren der Knoten und Links, um Referenzen zu erhalten - const nodes = this.nodes.map(d => Object.assign({}, d)); - const links = this.links.map(d => Object.assign({}, d)); - - // Links erstellen oder aktualisieren - this.linkElements = this.g.selectAll('.link') - .data(links, d => `${d.source.id || d.source}-${d.target.id || d.target}`); - - // Links entfernen, die nicht mehr existieren - this.linkElements.exit().remove(); - - // Neue Links erstellen - const linkEnter = this.linkElements - .enter().append('path') - .attr('class', 'link') - .attr('stroke-width', 2) - .attr('stroke', 'rgba(255, 255, 255, 0.3)') - .attr('fill', 'none') - .attr('marker-end', 'url(#arrowhead)'); - - // Alle Links aktualisieren - this.linkElements = linkEnter.merge(this.linkElements); - - // Pfeilspitzen für die Links definieren - if (!this.g.select('#arrowhead').size()) { - this.g.append('defs').append('marker') - .attr('id', 'arrowhead') - .attr('viewBox', '0 -5 10 10') - .attr('refX', 28) // Abstand vom Ende des Links zum Knoten - .attr('refY', 0) - .attr('orient', 'auto') - .attr('markerWidth', 6) - .attr('markerHeight', 6) - .attr('xoverflow', 'visible') - .append('path') - .attr('d', 'M 0,-3 L 8,0 L 0,3') - .attr('fill', 'rgba(255, 255, 255, 0.6)'); - } - - // Knoten erstellen oder aktualisieren - this.nodeElements = this.g.selectAll('.node') - .data(nodes, d => d.id); - - // Knoten entfernen, die nicht mehr existieren - this.nodeElements.exit().remove(); - - // Container für neue Knoten erstellen - const nodeEnter = this.nodeElements - .enter().append('g') - .attr('class', 'node') - .call(d3.drag() - .on('start', (event, d) => this.dragStarted(event, d)) - .on('drag', (event, d) => this.dragged(event, d)) - .on('end', (event, d) => this.dragEnded(event, d)) - ) - .on('mouseover', (event, d) => this.nodeMouseover(event, d)) - .on('mouseout', (event, d) => this.nodeMouseout(event, d)) - .on('click', (event, d) => this.nodeClicked(event, d)); - - // Kreisformen für die Knoten hinzufügen - nodeEnter.append('circle') - .attr('r', d => this.nodeRadius) - .attr('fill', d => this.getNodeColor(d)) - .attr('stroke', 'rgba(255, 255, 255, 0.12)') - .attr('stroke-width', 2) - .style('filter', 'url(#glass-effect)'); - - // Label für die Knoten hinzufügen - nodeEnter.append('text') - .attr('class', 'node-label') - .attr('dy', 4) - .attr('text-anchor', 'middle') - .text(d => this.truncateNodeLabel(d.name)) - .style('font-size', d => D3Extensions.getAdaptiveFontSize(d.name, 16, 10) + 'px'); - - // Alle Knoten aktualisieren - this.nodeElements = nodeEnter.merge(this.nodeElements); - - // Simulation mit den neuen Daten aktualisieren - this.simulation - .nodes(nodes) - .force('link', d3.forceLink(links).id(d => d.id).distance(this.linkDistance)); - - // Simulation-Tick-Funktion setzen - this.simulation.on('tick', () => this.ticked()); - - // Simulation neustarten - this.simulation.alpha(1).restart(); - - // Nach kurzer Verzögerung die Knoten mit zusätzlichen Effekten versehen - setTimeout(() => { - this.nodeElements.selectAll('circle') - .transition() - .duration(500) - .attr('r', d => { - // Größe abhängig von der Anzahl der Gedanken - const baseRadius = this.nodeRadius; - const bonus = d.thought_count ? Math.min(d.thought_count / 3, 6) : 0; - return baseRadius + bonus; - }); - }, 300); - } - - // Lange Knotenbeschriftungen abkürzen - truncateNodeLabel(label) { - if (!label) return ''; - - const maxLength = 18; // Maximale Zeichenlänge - - if (label.length <= maxLength) { - return label; - } else { - return label.substring(0, maxLength - 3) + '...'; - } - } - - // Bestimmt die Farbe eines Knotens basierend auf seinem Typ oder direkt angegebener Farbe - getNodeColor(node) { - // Direkt angegebene Farbe verwenden, wenn vorhanden - if (node.color_code) { - return node.color_code; - } - - // Kategorietyp-basierte Färbung mit dezenten, wissenschaftlichen Farben - if (node.type === 'category') { - return this.colorPalette.root; - } else if (node.type === 'subcategory') { - return this.colorPalette.science; - } - - // Fallback für verschiedene Knotentypen - return this.colorPalette[node.id] || this.colorPalette.default; - } - - // Aktualisiert die Positionen in jedem Simulationsschritt - ticked() { - if (!this.linkElements || !this.nodeElements) return; - - // Aktualisierung der Linkpositionen mit gebogenem Pfad - this.linkElements - .attr('d', d => { - const dx = d.target.x - d.source.x; - const dy = d.target.y - d.source.y; - const dr = Math.sqrt(dx * dx + dy * dy) * 1.5; // Kurvenstärke - return `M${d.source.x},${d.source.y}A${dr},${dr} 0 0,1 ${d.target.x},${d.target.y}`; - }); - - // Aktualisierung der Knotenpositionen - this.nodeElements - .attr('transform', d => `translate(${d.x},${d.y})`); - } - - // D3.js Drag-Funktionen - dragStarted(event, d) { - if (!event.active) this.simulation.alphaTarget(0.3).restart(); - d.fx = d.x; - d.fy = d.y; - } - - dragged(event, d) { - d.fx = event.x; - d.fy = event.y; - } - - dragEnded(event, d) { - if (!event.active) this.simulation.alphaTarget(0); - d.fx = null; - d.fy = null; - } - - // Hover-Effekte für Knoten - nodeMouseover(event, d) { - if (this.tooltipEnabled) { - // Tooltip-Inhalt erstellen - const tooltipContent = ` -

${d.name}
-
${d.description || 'Keine Beschreibung verfügbar'}
- ${d.thought_count > 0 ? `
${d.thought_count} Gedanken verknüpft
` : ''} - `; - - this.tooltipDiv.html(tooltipContent) - .style('opacity', 0.95); - - // Tooltip positionieren (oberhalb des Nodes) - const nodeRect = event.target.getBoundingClientRect(); - const tooltipWidth = 250; - const tooltipHeight = 100; // Ungefähre Höhe des Tooltips - - const leftPos = nodeRect.left + (nodeRect.width / 2) - (tooltipWidth / 2); - const topPos = nodeRect.top - tooltipHeight - 10; // 10px Abstand - - this.tooltipDiv - .style('left', `${leftPos}px`) - .style('top', `${topPos}px`) - .style('width', `${tooltipWidth}px`); - } - - // Speichern des aktuellen Hover-Nodes - this.mouseoverNode = d; - - // Highlights für verbundene Nodes und Links hinzufügen - if (this.g) { - // Verbundene Nodes identifizieren - const connectedNodes = this.getConnectedNodesById(d.id); - const connectedNodeIds = connectedNodes.map(node => node.id); - - // Alle Nodes etwas transparenter machen - this.g.selectAll('.node') - .transition() - .duration(200) - .style('opacity', node => { - if (node.id === d.id || connectedNodeIds.includes(node.id)) { - return 1.0; - } else { - return 0.5; - } - }); - - // Den Hover-Node hervorheben mit größerem Radius - this.g.selectAll('.node') - .filter(node => node.id === d.id) - .select('circle') - .transition() - .duration(200) - .attr('r', this.nodeRadius * 1.2) - .style('filter', 'url(#hover-glow)') - .style('stroke', 'rgba(255, 255, 255, 0.25)'); - - // Verbundene Links hervorheben - this.g.selectAll('.link') - .transition() - .duration(200) - .style('opacity', link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - - if (sourceId === d.id || targetId === d.id) { - return 0.9; - } else { - return 0.3; - } - }) - .style('stroke-width', link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - - if (sourceId === d.id || targetId === d.id) { - return 3; - } else { - return 2; - } - }) - .style('stroke', link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - - if (sourceId === d.id || targetId === d.id) { - return 'rgba(179, 143, 255, 0.7)'; - } else { - return 'rgba(255, 255, 255, 0.3)'; - } - }); - } - } - - nodeMouseout(event, d) { - if (this.tooltipEnabled) { - this.tooltipDiv.transition() - .duration(200) - .style('opacity', 0); - } - - this.mouseoverNode = null; - - // Highlights zurücksetzen, falls kein Node ausgewählt ist - if (!this.selectedNode && this.g) { - // Alle Nodes wieder auf volle Deckkraft setzen - this.g.selectAll('.node') - .transition() - .duration(200) - .style('opacity', 1.0); - - // Hover-Node-Radius zurücksetzen - this.g.selectAll('.node') - .filter(node => node.id === d.id) - .select('circle') - .transition() - .duration(200) - .attr('r', this.nodeRadius) - .style('filter', 'none') - .style('stroke', 'rgba(255, 255, 255, 0.12)'); - - // Links zurücksetzen - this.g.selectAll('.link') - .transition() - .duration(200) - .style('opacity', 0.7) - .style('stroke-width', 2) - .style('stroke', 'rgba(255, 255, 255, 0.3)'); - } - // Falls ein Node ausgewählt ist, den Highlight-Status für diesen beibehalten - else if (this.selectedNode && this.g) { - const connectedNodes = this.getConnectedNodesById(this.selectedNode.id); - const connectedNodeIds = connectedNodes.map(node => node.id); - - // Alle Nodes auf den richtigen Highlight-Status setzen - this.g.selectAll('.node') - .transition() - .duration(200) - .style('opacity', node => { - if (node.id === this.selectedNode.id || connectedNodeIds.includes(node.id)) { - return 1.0; - } else { - return 0.5; - } - }); - - // Hover-Node zurücksetzen, wenn er nicht der ausgewählte ist - if (d.id !== this.selectedNode.id) { - this.g.selectAll('.node') - .filter(node => node.id === d.id) - .select('circle') - .transition() - .duration(200) - .attr('r', this.nodeRadius) - .style('filter', 'none') - .style('stroke', 'rgba(255, 255, 255, 0.12)'); - } - - // Links auf den richtigen Highlight-Status setzen - this.g.selectAll('.link') - .transition() - .duration(200) - .style('opacity', link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - - if (sourceId === this.selectedNode.id || targetId === this.selectedNode.id) { - return 0.9; - } else { - return 0.3; - } - }) - .style('stroke-width', link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - - if (sourceId === this.selectedNode.id || targetId === this.selectedNode.id) { - return 3; - } else { - return 2; - } - }) - .style('stroke', link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - - if (sourceId === this.selectedNode.id || targetId === this.selectedNode.id) { - return 'rgba(179, 143, 255, 0.7)'; - } else { - return 'rgba(255, 255, 255, 0.3)'; - } - }); - } - } - - // Findet alle verbundenen Knoten zu einem gegebenen Knoten - getConnectedNodes(node) { - if (!this.links || !this.nodes || !node) return []; - - // Sicherstellen, dass der Knoten eine ID hat - const nodeId = node.id || node; - - return this.nodes.filter(n => - this.links.some(link => { - const sourceId = link.source?.id || link.source; - const targetId = link.target?.id || link.target; - return (sourceId === nodeId && targetId === n.id) || - (targetId === nodeId && sourceId === n.id); - }) - ); - } - - // Prüft, ob zwei Knoten verbunden sind - isConnected(a, b) { - if (!this.links || !a || !b) return false; - - // Sicherstellen, dass die Knoten IDs haben - const aId = a.id || a; - const bId = b.id || b; - - return this.links.some(link => { - const sourceId = link.source?.id || link.source; - const targetId = link.target?.id || link.target; - return (sourceId === aId && targetId === bId) || - (targetId === aId && sourceId === bId); - }); - } - - // Überprüft, ob ein Link zwischen zwei Knoten existiert - hasLink(source, target) { - if (!this.links || !source || !target) return false; - - // Sicherstellen, dass die Knoten IDs haben - const sourceId = source.id || source; - const targetId = target.id || target; - - return this.links.some(link => { - const linkSourceId = link.source?.id || link.source; - const linkTargetId = link.target?.id || link.target; - return (linkSourceId === sourceId && linkTargetId === targetId) || - (linkTargetId === sourceId && linkSourceId === targetId); - }); - } - - // Sicherere Methode zum Abrufen verbundener Knoten, die Prüfungen enthält - getConnectedNodesById(nodeId) { - if (!this.links || !this.nodes || !nodeId) return []; - - return this.nodes.filter(n => - this.links.some(link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - return (sourceId === nodeId && targetId === n.id) || - (targetId === nodeId && sourceId === n.id); - }) - ); - } - - // Aktualisiert die Verbindungszählungen für alle Knoten - updateConnectionCounts() { - if (!this.nodes || !this.links) return; - - // Für jeden Knoten die Anzahl der Verbindungen berechnen - this.nodes.forEach(node => { - // Sichere Methode, um verbundene Knoten zu zählen - const connectedNodes = this.nodes.filter(n => - n.id !== node.id && this.links.some(link => { - const sourceId = link.source.id || link.source; - const targetId = link.target.id || link.target; - return (sourceId === node.id && targetId === n.id) || - (targetId === node.id && sourceId === n.id); - }) - ); - - // Speichere die Anzahl als Eigenschaft des Knotens - node.connectionCount = connectedNodes.length; - }); - } - - // Klick-Handler für Knoten mit verbesserter Seitenleisten-Interaktion - nodeClicked(event, d) { - event.preventDefault(); - event.stopPropagation(); - - // Selection-Handling: Knoten auswählen/abwählen - if (this.selectedNode === d) { - // Wenn der gleiche Knoten geklickt wird, Selektion aufheben - this.selectedNode = null; - this.nodeElements.classed('selected', false); - - this.nodeElements - .select('circle:not(.node-background):not(.thought-indicator)') - .transition() - .duration(300) - .attr('r', this.nodeRadius) - .style('filter', 'url(#glass-with-reflection)') - .attr('stroke-width', 2); - - // Event auslösen: Knoten abgewählt - document.dispatchEvent(new CustomEvent('mindmap-node-deselected')); - - // Standardinformationspanels wieder anzeigen - this.showDefaultSidebar(); - - // Gedankenbereich ausblenden, wenn vorhanden - const thoughtContainer = document.getElementById('thought-container'); - if (thoughtContainer) { - // Sanfte Ausblendanimation - thoughtContainer.style.transition = 'all 0.3s ease-out'; - thoughtContainer.style.opacity = '0'; - thoughtContainer.style.transform = 'translateY(10px)'; - - setTimeout(() => { - // Gedankenbereich komplett ausblenden - thoughtContainer.style.display = 'none'; - - // "Empty state" anzeigen oder andere UI-Anpassungen vornehmen - const emptyStateEl = document.getElementById('mindmap-empty-state'); - if (emptyStateEl) { - emptyStateEl.style.display = 'flex'; - emptyStateEl.style.opacity = '0'; - setTimeout(() => { - emptyStateEl.style.transition = 'all 0.5s ease'; - emptyStateEl.style.opacity = '1'; - }, 50); - } - }, 300); - } - - // Alle Kanten zurücksetzen - this.linkElements - .classed('highlighted', false) - .transition() - .duration(300) - .style('stroke', 'rgba(75, 85, 99, 0.4)') - .style('stroke-width', 2) - .style('opacity', 0.7); - - // Interface-Callback für Knoten-Abwahl - if (typeof window.onNodeDeselected === 'function') { - window.onNodeDeselected(); - } - - // Flash-Nachricht für abgewählten Knoten - this.showFlash('Knotenauswahl aufgehoben', 'info', 2000); - - return; - } - - // Bisher ausgewählten Knoten zurücksetzen - if (this.selectedNode) { - this.nodeElements - .filter(n => n === this.selectedNode) - .classed('selected', false) - .select('circle:not(.node-background):not(.thought-indicator)') - .transition() - .duration(300) - .attr('r', this.nodeRadius) - .style('filter', 'url(#glass-with-reflection)') - .attr('stroke-width', 2); - } - - // Neuen Knoten auswählen - this.selectedNode = d; - - // Selected-Klasse für den Knoten setzen - this.nodeElements - .classed('selected', n => n === d); - - // Event auslösen: Knoten ausgewählt - document.dispatchEvent(new CustomEvent('mindmap-node-selected', { - detail: d - })); - - // Visuelles Feedback für Auswahl - this.nodeElements - .filter(n => n === d) - .select('circle:not(.node-background):not(.thought-indicator)') - .transition() - .duration(300) - .attr('r', this.selectedNodeRadius) - .style('filter', 'url(#selected-glow)') - .attr('stroke-width', 3) - .attr('stroke', 'rgba(79, 70, 229, 0.6)'); - - // Verbundene Kanten hervorheben - const connectedLinks = this.links.filter(link => - link.source === d || link.source.id === d.id || - link.target === d || link.target.id === d.id - ); - - // Alle Kanten zurücksetzen und dann verbundene hervorheben - this.linkElements - .classed('highlighted', false) - .transition() - .duration(300) - .style('stroke', 'rgba(75, 85, 99, 0.4)') - .style('stroke-width', 2) - .style('opacity', 0.7); - - this.linkElements - .filter(link => - connectedLinks.some(l => - (l.source === link.source || l.source.id === link.source.id) && - (l.target === link.target || l.target.id === link.target.id) - ) - ) - .classed('highlighted', true) - .transition() - .duration(300) - .style('stroke', 'rgba(79, 70, 229, 0.7)') - .style('stroke-width', 3) - .style('opacity', 0.9); - - // Knoten zentrieren - this.centerNodeInView(d); - - // Gedanken laden - this.loadThoughtsForNode(d); - - // Callback für UI-Integration - if (typeof this.onNodeClick === 'function') { - this.onNodeClick(d); - } - - // Interface-Callback für externe Verwendung - if (typeof window.onNodeSelected === 'function') { - window.onNodeSelected(d); - } - } - - // Neue Methode: Zeigt die Standardseitenleiste an (Über die Mindmap und Kategorien) - showDefaultSidebar() { - // Finde die Seitenleistenelemente - const aboutMindmapPanel = document.querySelector('[data-sidebar="about-mindmap"]'); - const categoriesPanel = document.querySelector('[data-sidebar="categories"]'); - const nodeDescriptionPanel = document.querySelector('[data-sidebar="node-description"]'); - - if (aboutMindmapPanel && categoriesPanel && nodeDescriptionPanel) { - // Beschreibungspanel ausblenden - nodeDescriptionPanel.style.display = 'none'; - - // Standardpanels einblenden mit Animation - aboutMindmapPanel.style.display = 'block'; - categoriesPanel.style.display = 'block'; - - setTimeout(() => { - aboutMindmapPanel.style.opacity = '1'; - aboutMindmapPanel.style.transform = 'translateY(0)'; - - categoriesPanel.style.opacity = '1'; - categoriesPanel.style.transform = 'translateY(0)'; - }, 50); - } - } - - // Neue Methode: Zeigt die Knotenbeschreibung in der Seitenleiste an - showNodeDescriptionSidebar(node) { - // Finde die Seitenleistenelemente - const aboutMindmapPanel = document.querySelector('[data-sidebar="about-mindmap"]'); - const categoriesPanel = document.querySelector('[data-sidebar="categories"]'); - const nodeDescriptionPanel = document.querySelector('[data-sidebar="node-description"]'); - - if (aboutMindmapPanel && categoriesPanel && nodeDescriptionPanel) { - // Standardpanels ausblenden - aboutMindmapPanel.style.transition = 'all 0.3s ease'; - categoriesPanel.style.transition = 'all 0.3s ease'; - - aboutMindmapPanel.style.opacity = '0'; - aboutMindmapPanel.style.transform = 'translateY(10px)'; - - categoriesPanel.style.opacity = '0'; - categoriesPanel.style.transform = 'translateY(10px)'; - - setTimeout(() => { - aboutMindmapPanel.style.display = 'none'; - categoriesPanel.style.display = 'none'; - - // Beschreibungspanel vorbereiten - const titleElement = nodeDescriptionPanel.querySelector('[data-node-title]'); - const descriptionElement = nodeDescriptionPanel.querySelector('[data-node-description]'); - - if (titleElement && descriptionElement) { - titleElement.textContent = node.name || 'Unbenannter Knoten'; - - // Beschreibung setzen oder Standardbeschreibung generieren - let description = node.description; - if (!description || description.trim() === '') { - description = this.generateNodeDescription(node); - } - - descriptionElement.textContent = description; - } - - // Beschreibungspanel einblenden mit Animation - nodeDescriptionPanel.style.display = 'block'; - nodeDescriptionPanel.style.opacity = '0'; - nodeDescriptionPanel.style.transform = 'translateY(10px)'; - - setTimeout(() => { - nodeDescriptionPanel.style.transition = 'all 0.4s ease'; - nodeDescriptionPanel.style.opacity = '1'; - nodeDescriptionPanel.style.transform = 'translateY(0)'; - }, 50); - }, 300); - } - } - - // Neue Methode: Generiert automatisch eine Beschreibung für einen Knoten ohne Beschreibung - generateNodeDescription(node) { - const descriptions = { - "Wissen": "Der zentrale Knotenpunkt der Mindmap, der alle wissenschaftlichen Disziplinen und Wissensgebiete verbindet. Hier finden sich grundlegende Erkenntnisse und Verbindungen zu spezifischeren Fachgebieten.", - - "Quantenphysik": "Ein Zweig der Physik, der sich mit dem Verhalten und den Interaktionen von Materie und Energie auf der kleinsten Skala beschäftigt. Quantenmechanische Phänomene wie Superposition und Verschränkung bilden die Grundlage für moderne Technologien wie Quantencomputer und -kommunikation.", - - "Neurowissenschaften": "Interdisziplinäres Forschungsgebiet, das die Struktur, Funktion und Entwicklung des Nervensystems und des Gehirns untersucht. Die Erkenntnisse beeinflussen unser Verständnis von Bewusstsein, Kognition, Verhalten und neurologischen Erkrankungen.", - - "Künstliche Intelligenz": "Forschungsgebiet der Informatik, das sich mit der Entwicklung von Systemen befasst, die menschliche Intelligenzformen simulieren können. KI umfasst maschinelles Lernen, neuronale Netze und verschiedene Ansätze zur Problemlösung und Mustererkennung.", - - "Klimaforschung": "Wissenschaftliche Disziplin, die sich mit der Untersuchung des Erdklimas, seinen Veränderungen und den zugrundeliegenden physikalischen Prozessen beschäftigt. Sie liefert wichtige Erkenntnisse zu Klimawandel, Wettermuster und globalen Umweltveränderungen.", - - "Genetik": "Wissenschaft der Gene, Vererbung und der Variation von Organismen. Moderne genetische Forschung umfasst Genomik, Gentechnologie und das Verständnis der molekularen Grundlagen des Lebens sowie ihrer Anwendungen in Medizin und Biotechnologie.", - - "Astrophysik": "Zweig der Astronomie, der die physikalischen Eigenschaften und Prozesse von Himmelskörpern und des Universums untersucht. Sie erforscht Phänomene wie Schwarze Löcher, Galaxien, kosmische Strahlung und die Entstehung und Entwicklung des Universums.", - - "Philosophie": "Disziplin, die sich mit fundamentalen Fragen des Wissens, der Realität und der Existenz auseinandersetzt. Sie umfasst Bereiche wie Metaphysik, Erkenntnistheorie, Ethik und Logik und bildet die Grundlage für kritisches Denken und wissenschaftliche Methodik.", - - "Wissenschaft": "Systematische Erforschung der Natur und der materiellen Welt durch Beobachtung, Experimente und die Formulierung überprüfbarer Theorien. Sie umfasst Naturwissenschaften, Sozialwissenschaften und angewandte Wissenschaften.", - - "Technologie": "Anwendung wissenschaftlicher Erkenntnisse für praktische Zwecke. Sie umfasst die Entwicklung von Werkzeugen, Maschinen, Materialien und Prozessen zur Lösung von Problemen und zur Verbesserung der menschlichen Lebensbedingungen.", - - "Künste": "Ausdruck menschlicher Kreativität und Imagination in verschiedenen Formen wie Malerei, Musik, Literatur, Theater und Film. Die Künste erforschen ästhetische, emotionale und intellektuelle Dimensionen der menschlichen Erfahrung.", - - "Biologie": "Wissenschaft des Lebens und der lebenden Organismen. Sie umfasst Bereiche wie Molekularbiologie, Evolutionsbiologie, Ökologie und beschäftigt sich mit der Struktur, Funktion, Entwicklung und Evolution lebender Systeme.", - - "Mathematik": "Wissenschaft der Muster, Strukturen und Beziehungen. Sie ist die Sprache der Naturwissenschaften und bildet die Grundlage für quantitative Analysen, logisches Denken und Problemlösung in allen wissenschaftlichen Disziplinen.", - - "Psychologie": "Wissenschaftliche Untersuchung des menschlichen Verhaltens und der mentalen Prozesse. Sie erforscht Bereiche wie Kognition, Emotion, Persönlichkeit, soziale Interaktionen und die Behandlung psychischer Störungen.", - - "Ethik": "Teilgebiet der Philosophie, das sich mit moralischen Prinzipien, Werten und der Frage nach richtigem und falschem Handeln beschäftigt. Sie bildet die Grundlage für moralische Entscheidungsfindung in allen Lebensbereichen." - }; - - // Verwende vordefinierte Beschreibung, wenn verfügbar - if (node.name && descriptions[node.name]) { - return descriptions[node.name]; - } - - // Generische Beschreibung basierend auf dem Knotentyp - switch (node.type) { - case 'category': - return `Dieser Knoten repräsentiert die Kategorie "${node.name}", die verschiedene verwandte Konzepte und Ideen zusammenfasst. Wählen Sie einen der verbundenen Unterthemen, um mehr Details zu erfahren.`; - case 'subcategory': - return `"${node.name}" ist eine Unterkategorie, die spezifische Aspekte eines größeren Themenbereichs beleuchtet. Die verbundenen Knoten zeigen wichtige Konzepte und Ideen innerhalb dieses Bereichs.`; - default: - return `Dieser Knoten repräsentiert das Konzept "${node.name}". Erforschen Sie die verbundenen Knoten, um Zusammenhänge und verwandte Ideen zu entdecken.`; - } - } - - // Lädt die Gedanken für einen Knoten und zeigt sie an - loadThoughtsForNode(node) { - // UI-Element für Gedanken finden - const thoughtContainer = document.getElementById('thought-container'); - const loadingIndicator = document.getElementById('thoughts-loading'); - const thoughtsList = document.getElementById('thoughts-list'); - const thoughtsTitle = document.getElementById('thoughts-title'); - const emptyStateEl = document.getElementById('mindmap-empty-state'); - - if (!thoughtContainer || !thoughtsList) { - console.error('Gedanken-Container nicht gefunden'); - this.showFlash('Fehler: Gedanken-Container nicht gefunden', 'error'); - return; - } - - // "Empty state" ausblenden - if (emptyStateEl) { - emptyStateEl.style.transition = 'all 0.3s ease'; - emptyStateEl.style.opacity = '0'; - setTimeout(() => { - emptyStateEl.style.display = 'none'; - }, 300); - } - - // Container anzeigen mit Animation - thoughtContainer.style.display = 'block'; - setTimeout(() => { - thoughtContainer.style.transition = 'all 0.4s ease'; - thoughtContainer.style.opacity = '1'; - thoughtContainer.style.transform = 'translateY(0)'; - }, 50); - - // Titel setzen - if (thoughtsTitle) { - thoughtsTitle.textContent = `Gedanken zu "${node.name}"`; - } - - // Ladeanimation anzeigen - if (loadingIndicator) { - loadingIndicator.style.display = 'flex'; - } - - // Bisherige Gedanken leeren - if (thoughtsList) { - thoughtsList.innerHTML = ''; - } - - // Flash-Nachricht über ausgewählten Knoten - this.showFlash(`Knoten "${node.name}" ausgewählt`, 'info'); - - // Verzögerung für Animation - setTimeout(() => { - // API-Aufruf für echte Daten aus der Datenbank - this.fetchThoughtsForNode(node.id) - .then(thoughts => { - // Ladeanimation ausblenden - if (loadingIndicator) { - loadingIndicator.style.display = 'none'; - } - - // Gedanken anzeigen oder "leer"-Zustand - if (thoughts && thoughts.length > 0) { - this.renderThoughts(thoughts, thoughtsList); - } else { - this.renderEmptyThoughts(thoughtsList, node); - this.showFlash(`Keine Gedanken zu "${node.name}" gefunden`, 'warning'); - } - }) - .catch(error => { - console.error('Fehler beim Laden der Gedanken:', error); - if (loadingIndicator) { - loadingIndicator.style.display = 'none'; - } - this.renderErrorState(thoughtsList); - this.showFlash('Fehler beim Laden der Gedanken. Bitte versuche es später erneut.', 'error'); - }); - }, 600); // Verzögerung für bessere UX - } - - // Holt Gedanken für einen Knoten aus der Datenbank - async fetchThoughtsForNode(nodeId) { - try { - // Extrahiere die tatsächliche ID aus dem nodeId Format (z.B. "node_123" oder "category_456") - const id = nodeId.toString().split('_')[1]; - if (!id) { - console.warn('Ungültige Node-ID: ', nodeId); - this.showFlash('Ungültige Knoten-ID: ' + nodeId, 'warning'); - return []; - } - - // API-Aufruf an den entsprechenden Endpunkt - const response = await fetch(`/api/nodes/${id}/thoughts`); - - if (!response.ok) { - throw new Error(`API-Fehler: ${response.statusText}`); - } - - const thoughts = await response.json(); - console.log('Geladene Gedanken für Knoten:', thoughts); - - if (thoughts.length > 0) { - this.showFlash(`${thoughts.length} Gedanken zum Thema geladen`, 'info'); - } else { - this.showFlash('Keine Gedanken für diesen Knoten gefunden', 'info'); - } - - return thoughts; - } catch (error) { - console.error('Fehler beim Laden der Gedanken für Knoten:', error); - this.showFlash('Fehler beim Laden der Gedanken', 'error'); - return []; - } - } - - // Rendert die Gedanken in der UI - renderThoughts(thoughts, container) { - if (!container) return; - - container.innerHTML = ''; - - thoughts.forEach(thought => { - const thoughtCard = document.createElement('div'); - thoughtCard.className = 'thought-card'; - thoughtCard.setAttribute('data-id', thought.id); - - const cardColor = thought.color_code || this.colorPalette.default; - - thoughtCard.innerHTML = ` -
-

${thought.title}

-
- ${new Date(thought.created_at).toLocaleDateString('de-DE')} - ${thought.author ? `von ${thought.author.username}` : ''} -
-
-
-

${thought.abstract || thought.content.substring(0, 150) + '...'}

-
- - `; - - // Event-Listener für Klick auf Gedanken - thoughtCard.addEventListener('click', (e) => { - // Verhindern, dass der Link-Klick den Kartenklick auslöst - if (e.target.tagName === 'A') return; - window.location.href = `/thoughts/${thought.id}`; - }); - - container.appendChild(thoughtCard); - }); - } - - // Rendert eine Leermeldung, wenn keine Gedanken vorhanden sind - renderEmptyThoughts(container, node) { - if (!container) return; - - const emptyState = document.createElement('div'); - emptyState.className = 'empty-thoughts-state'; - - emptyState.innerHTML = ` -
- -
-

Keine Gedanken verknüpft

-

Zu "${node.name}" sind noch keine Gedanken verknüpft.

- - `; - - container.appendChild(emptyState); - } - - // Rendert einen Fehlerzustand - renderErrorState(container) { - if (!container) return; - - const errorState = document.createElement('div'); - errorState.className = 'error-thoughts-state'; - - errorState.innerHTML = ` -
- -
-

Fehler beim Laden

-

Die Gedanken konnten nicht geladen werden. Bitte versuche es später erneut.

- - `; - - // Event-Listener für Retry-Button - const retryButton = errorState.querySelector('.retry-button'); - if (retryButton && this.selectedNode) { - retryButton.addEventListener('click', () => { - this.loadThoughtsForNode(this.selectedNode); - }); - } - - container.appendChild(errorState); - } - - // Zentriert einen Knoten in der Ansicht - centerNodeInView(node) { - // Sanfter Übergang zur Knotenzentrierüng - const transform = d3.zoomTransform(this.svg.node()); - const scale = transform.k; - - const x = -node.x * scale + this.width / 2; - const y = -node.y * scale + this.height / 2; - - this.svg.transition() - .duration(750) - .call( - d3.zoom().transform, - d3.zoomIdentity.translate(x, y).scale(scale) - ); - - // Flash-Nachricht für Zentrierung - if (node && node.name) { - this.showFlash(`Ansicht auf "${node.name}" zentriert`, 'info', 2000); - } - } - - // Fehlermeldung anzeigen - showError(message) { - // Standard-Fehlermeldung als Banner - const errorBanner = d3.select('body').selectAll('.error-banner').data([0]); - - const errorEnter = errorBanner.enter() - .append('div') - .attr('class', 'error-banner') - .style('position', 'fixed') - .style('bottom', '-100px') - .style('left', '50%') - .style('transform', 'translateX(-50%)') - .style('background', 'rgba(220, 38, 38, 0.9)') - .style('color', 'white') - .style('padding', '12px 20px') - .style('border-radius', '8px') - .style('z-index', '1000') - .style('box-shadow', '0 10px 25px rgba(0, 0, 0, 0.3)') - .style('font-weight', '500') - .style('max-width', '90%') - .style('text-align', 'center'); - - const banner = errorEnter.merge(errorBanner); - banner.html(` ${message}`) - .transition() - .duration(500) - .style('bottom', '20px') - .transition() - .delay(5000) - .duration(500) - .style('bottom', '-100px'); - - // Auch als Flash-Nachricht anzeigen - this.showFlash(message, 'error'); - } - - // Fokussieren auf einen bestimmten Knoten per ID - focusNode(nodeId) { - const targetNode = this.nodes.find(n => n.id === nodeId); - if (!targetNode) { - this.showFlash(`Knoten mit ID "${nodeId}" nicht gefunden`, 'error'); - return; - } - - // Ausgewählten Zustand zurücksetzen - this.selectedNode = null; - - // Node-Klick simulieren - this.nodeClicked(null, targetNode); - - // Fokussieren mit einer Animation - if (targetNode.x && targetNode.y) { - const transform = d3.zoomIdentity - .translate(this.width / 2 - targetNode.x * 1.2, this.height / 2 - targetNode.y * 1.2) - .scale(1.2); - - this.svg.transition() - .duration(750) - .call( - d3.zoom().transform, - transform - ); - - this.showFlash(`Fokus auf Knoten "${targetNode.name}" gesetzt`, 'success'); - } - } - - // Filtert Knoten nach Suchbegriff - filterBySearchTerm(searchTerm) { - if (!searchTerm || searchTerm.trim() === '') { - // Alle Knoten anzeigen, wenn kein Suchbegriff - this.nodeElements - .style('display', 'block') - .selectAll('circle') - .style('opacity', 1); - - this.textElements - .style('opacity', 1); - - this.linkElements - .style('display', 'block') - .style('stroke-opacity', 0.5); - - this.showFlash('Suchfilter zurückgesetzt', 'info', 2000); - - return; - } - - searchTerm = searchTerm.toLowerCase().trim(); - - // Knoten finden, die dem Suchbegriff entsprechen - const matchingNodes = this.nodes.filter(node => - node.name.toLowerCase().includes(searchTerm) || - (node.description && node.description.toLowerCase().includes(searchTerm)) - ); - - const matchingNodeIds = matchingNodes.map(n => n.id); - - // Nur passende Knoten und ihre Verbindungen anzeigen - this.nodeElements - .style('display', d => matchingNodeIds.includes(d.id) ? 'block' : 'none') - .selectAll('circle') - .style('opacity', 1); - - this.textElements - .style('opacity', d => matchingNodeIds.includes(d.id) ? 1 : 0.2); - - this.linkElements - .style('display', link => - matchingNodeIds.includes(link.source.id) && matchingNodeIds.includes(link.target.id) ? 'block' : 'none') - .style('stroke-opacity', 0.7); - - // Wenn nur ein Knoten gefunden wurde, darauf fokussieren - if (matchingNodes.length === 1) { - this.focusNode(matchingNodes[0].id); - } - - // Wenn mehr als ein Knoten gefunden wurde, Simulation mit reduzierter Stärke neu starten - if (matchingNodes.length > 1) { - this.simulation.alpha(0.3).restart(); - this.showFlash(`${matchingNodes.length} Knoten für "${searchTerm}" gefunden`, 'success'); - } else if (matchingNodes.length === 0) { - this.showFlash(`Keine Knoten für "${searchTerm}" gefunden`, 'warning'); - } - } -} - -// D3-Erweiterungen für spezielle Effekte -class D3Extensions { - static createGlowFilter(defs, id, color = '#b38fff', strength = 5) { - const filter = defs.append('filter') - .attr('id', id) - .attr('height', '300%') - .attr('width', '300%') - .attr('x', '-100%') - .attr('y', '-100%'); - - // Farbe und Sättigung - const colorMatrix = filter.append('feColorMatrix') - .attr('type', 'matrix') - .attr('values', ` - 1 0 0 0 ${color === '#b38fff' ? 0.7 : 0.35} - 0 1 0 0 ${color === '#58a9ff' ? 0.7 : 0.35} - 0 0 1 0 ${color === '#58a9ff' ? 0.7 : 0.55} - 0 0 0 1 0 - `) - .attr('result', 'colored'); - - // Weichzeichner für Glühen - const blur = filter.append('feGaussianBlur') - .attr('in', 'colored') - .attr('stdDeviation', strength) - .attr('result', 'blur'); - - // Kombination von Original und Glühen - const merge = filter.append('feMerge'); - - merge.append('feMergeNode') - .attr('in', 'blur'); - - merge.append('feMergeNode') - .attr('in', 'SourceGraphic'); - - return filter; - } - - static createShadowFilter(defs, id) { - const filter = defs.append('filter') - .attr('id', id) - .attr('height', '200%') - .attr('width', '200%') - .attr('x', '-50%') - .attr('y', '-50%'); - - // Offset der Lichtquelle - const offset = filter.append('feOffset') - .attr('in', 'SourceAlpha') - .attr('dx', 3) - .attr('dy', 4) - .attr('result', 'offset'); - - // Weichzeichnung für Schatten - const blur = filter.append('feGaussianBlur') - .attr('in', 'offset') - .attr('stdDeviation', 5) - .attr('result', 'blur'); - - // Schatten-Opazität - const opacity = filter.append('feComponentTransfer'); - - opacity.append('feFuncA') - .attr('type', 'linear') - .attr('slope', 0.3); - - // Zusammenführen - const merge = filter.append('feMerge'); - - merge.append('feMergeNode'); - merge.append('feMergeNode') - .attr('in', 'SourceGraphic'); - - return filter; - } - - static createGlassMorphismFilter(defs, id) { - const filter = defs.append('filter') - .attr('id', id) - .attr('width', '300%') - .attr('height', '300%') - .attr('x', '-100%') - .attr('y', '-100%'); - - // Basis-Hintergrundfarbe - const bgColor = filter.append('feFlood') - .attr('flood-color', 'rgba(24, 28, 45, 0.75)') - .attr('result', 'bgColor'); - - // Weichzeichnung des Originalelements - const blur = filter.append('feGaussianBlur') - .attr('in', 'SourceGraphic') - .attr('stdDeviation', '3') - .attr('result', 'blur'); - - // Komposition des Glaseffekts mit Original - const composite1 = filter.append('feComposite') - .attr('in', 'bgColor') - .attr('in2', 'blur') - .attr('operator', 'in') - .attr('result', 'glass'); - - // Leichter Farbakzent - const colorMatrix = filter.append('feColorMatrix') - .attr('in', 'glass') - .attr('type', 'matrix') - .attr('values', '1 0 0 0 0.1 0 1 0 0 0.1 0 0 1 0 0.3 0 0 0 1 0') - .attr('result', 'coloredGlass'); - - // Leichte Transparenz an den Rändern - const specLight = filter.append('feSpecularLighting') - .attr('in', 'blur') - .attr('surfaceScale', '3') - .attr('specularConstant', '0.75') - .attr('specularExponent', '20') - .attr('lighting-color', '#ffffff') - .attr('result', 'specLight'); - - specLight.append('fePointLight') - .attr('x', '-20') - .attr('y', '-30') - .attr('z', '120'); - - // Lichtkombination - const composite2 = filter.append('feComposite') - .attr('in', 'specLight') - .attr('in2', 'coloredGlass') - .attr('operator', 'in') - .attr('result', 'lightedGlass'); - - // Alle Effekte kombinieren - const merge = filter.append('feMerge') - .attr('result', 'glassMerge'); - - merge.append('feMergeNode') - .attr('in', 'coloredGlass'); - - merge.append('feMergeNode') - .attr('in', 'lightedGlass'); - - merge.append('feMergeNode') - .attr('in', 'SourceGraphic'); - - return filter; - } - - // Erstellt einen erweiterten 3D-Glaseffekt mit Lichtreflexion - static create3DGlassEffect(defs, id) { - const filter = defs.append('filter') - .attr('id', id) - .attr('width', '300%') - .attr('height', '300%') - .attr('x', '-100%') - .attr('y', '-100%'); - - // Hintergrund-Färbung mit Transparenz - const bgColor = filter.append('feFlood') - .attr('flood-color', 'rgba(24, 28, 45, 0.7)') - .attr('result', 'bgColor'); - - // Alpha-Kanal modifizieren - const composite1 = filter.append('feComposite') - .attr('in', 'bgColor') - .attr('in2', 'SourceAlpha') - .attr('operator', 'in') - .attr('result', 'shape'); - - // Leichte Unschärfe hinzufügen - const blur = filter.append('feGaussianBlur') - .attr('in', 'shape') - .attr('stdDeviation', '2') - .attr('result', 'blurredShape'); - - // Lichtquelle für 3D-Effekt - const specLight = filter.append('feSpecularLighting') - .attr('in', 'blurredShape') - .attr('surfaceScale', '5') - .attr('specularConstant', '1') - .attr('specularExponent', '20') - .attr('lighting-color', '#ffffff') - .attr('result', 'specLight'); - - specLight.append('fePointLight') - .attr('x', '50') - .attr('y', '-50') - .attr('z', '200'); - - // Farbmatrix für Lichttönung - const colorMatrix = filter.append('feColorMatrix') - .attr('in', 'specLight') - .attr('type', 'matrix') - .attr('values', '1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0') - .attr('result', 'coloredLight'); - - // Alle Effekte kombinieren - const merge = filter.append('feMerge'); - - merge.append('feMergeNode') - .attr('in', 'blurredShape'); - - merge.append('feMergeNode') - .attr('in', 'coloredLight'); - - merge.append('feMergeNode') - .attr('in', 'SourceGraphic'); - - return filter; - } -} - -// Globales Objekt für Zugriff außerhalb des Moduls -window.MindMapVisualization = MindMapVisualization; \ No newline at end of file From 121f46df01dde5f999e088b26cdb1b0d8a8c293a Mon Sep 17 00:00:00 2001 From: marwin Date: Fri, 9 May 2025 19:58:03 +0100 Subject: [PATCH 13/16] =?UTF-8?q?=E2=9C=A8=20feat(mindmap):=20erweitere=20?= =?UTF-8?q?die=20Funktionalit=C3=A4t=20zur=20Handhabung=20von=20Untertheme?= =?UTF-8?q?n=20und=20verbessere=20die=20Benutzerinteraktion=20durch=20neue?= =?UTF-8?q?=20Navigations-=20und=20Layout-Elemente=20in=20update=5Fmindmap?= =?UTF-8?q?.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- static/js/update_mindmap.js | 175 +++++++++++++++++++++++++++++------- 1 file changed, 144 insertions(+), 31 deletions(-) diff --git a/static/js/update_mindmap.js b/static/js/update_mindmap.js index 335c5a7..f840067 100644 --- a/static/js/update_mindmap.js +++ b/static/js/update_mindmap.js @@ -168,7 +168,9 @@ document.addEventListener('DOMContentLoaded', function() { id: node.id, label: node.label, category: node.category, - description: node.description + description: node.description, + hasChildren: node.hasChildren, + expanded: node.expanded } })), // Kanten @@ -264,9 +266,11 @@ document.addEventListener('DOMContentLoaded', function() { document.dispatchEvent(new Event('mindmap-loaded')); console.log('mindmap-loaded Event ausgelöst'); - // Event-Listener für Knoten-Klicks hinzufügen + // Event-Listener für Knoten-Klicks cy.on('tap', 'node', async function(evt) { const node = evt.target; + console.log('Node clicked:', node.id(), 'hasChildren:', node.data('hasChildren'), 'expanded:', node.data('expanded')); + if (node.data('hasChildren') && !node.data('expanded')) { await loadSubthemes(node); } @@ -298,7 +302,9 @@ function updateMindmap() { label: node.label, category: node.category, description: node.description, - color: categoryColors[node.category] || '#60a5fa' + color: categoryColors[node.category] || '#60a5fa', + hasChildren: node.hasChildren, + expanded: node.expanded } }); }); @@ -664,47 +670,95 @@ function createFlashContainer() { // Funktion zum Laden der Subthemen async function loadSubthemes(node) { try { - // Simuliere Datenbankabfrage (später durch echte API ersetzen) + console.log('Loading subthemes for node:', node.id()); + + // Simuliere Datenbankabfrage const subthemes = subthemesDatabase[node.id()]; - if (!subthemes) return; + if (!subthemes) { + console.log('No subthemes found for node:', node.id()); + return; + } // Animation starten showFlash('Lade Subthemen...', 'info'); + + // Neue Seite erstellen + const mindmapContainer = document.querySelector('.mindmap-container'); + const newPage = document.createElement('div'); + newPage.className = 'mindmap-page'; + newPage.style.display = 'none'; + + // Kopfzeile erstellen + const header = document.createElement('div'); + header.className = 'mindmap-header'; + header.innerHTML = ` + +

${node.data('label')}

+ `; + + // Container für die neue Mindmap + const newContainer = document.createElement('div'); + newContainer.id = `cy-${node.id()}`; + newContainer.className = 'mindmap-view'; + + // Elemente zur Seite hinzufügen + newPage.appendChild(header); + newPage.appendChild(newContainer); + mindmapContainer.appendChild(newPage); + + // Neue Cytoscape-Instanz erstellen + const newCy = cytoscape({ + container: newContainer, + elements: [], + style: cy.style(), + layout: { + name: 'cose', + animate: true, + animationDuration: 500, + refresh: 20, + fit: true, + padding: 30, + nodeRepulsion: 4500, + idealEdgeLength: 50, + edgeElasticity: 0.45 + } + }); // Neue Knoten hinzufügen subthemes.forEach(subtheme => { - cy.add({ + newCy.add({ group: 'nodes', data: { - ...subtheme, - expanded: false - } - }); - - // Kante zum Elternknoten hinzufügen - cy.add({ - group: 'edges', - data: { - id: `${node.id()}_${subtheme.id}`, - source: node.id(), - target: subtheme.id + id: subtheme.id, + label: subtheme.label, + category: subtheme.category, + description: subtheme.description, + hasChildren: subtheme.hasChildren, + expanded: false, + color: categoryColors[subtheme.category] || '#60a5fa' } }); }); - - // Node als expandiert markieren - node.data('expanded', true); - // Layout neu berechnen mit Animation - cy.layout({ - name: 'cose', - animate: true, - animationDuration: 500, - refresh: 20, - fit: true, - padding: 30 - }).run(); + // Event-Listener für die neue Mindmap + newCy.on('tap', 'node', async function(evt) { + const clickedNode = evt.target; + if (clickedNode.data('hasChildren') && !clickedNode.data('expanded')) { + await loadSubthemes(clickedNode); + } + }); + + // Alte Seite ausblenden und neue anzeigen + cy.container().style.display = 'none'; + newPage.style.display = 'block'; + + // Layout ausführen + newCy.layout().run(); // Erfolgsmeldung anzeigen showFlash('Subthemen erfolgreich geladen', 'success'); @@ -713,4 +767,63 @@ async function loadSubthemes(node) { console.error('Fehler beim Laden der Subthemen:', error); showFlash('Fehler beim Laden der Subthemen', 'error'); } -} \ No newline at end of file +} + +// Funktion zum Zurücknavigieren +function goBack() { + const currentPage = document.querySelector('.mindmap-page:not([style*="display: none"])'); + if (currentPage) { + currentPage.style.display = 'none'; + cy.container().style.display = 'block'; + } +} + +// CSS-Styles für die neue Seite +const style = document.createElement('style'); +style.textContent = ` + .mindmap-page { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: var(--bg-color, #1a1a1a); + z-index: 1000; + } + + .mindmap-header { + display: flex; + align-items: center; + padding: 1rem; + background: rgba(0, 0, 0, 0.2); + border-bottom: 1px solid rgba(255, 255, 255, 0.1); + } + + .back-button { + background: none; + border: none; + color: #fff; + cursor: pointer; + padding: 0.5rem; + margin-right: 1rem; + border-radius: 50%; + transition: background-color 0.3s; + } + + .back-button:hover { + background: rgba(255, 255, 255, 0.1); + } + + .mindmap-title { + color: #fff; + font-size: 1.5rem; + font-weight: 600; + margin: 0; + } + + .mindmap-view { + width: 100%; + height: calc(100% - 4rem); + } +`; +document.head.appendChild(style); \ No newline at end of file From 118f8ed1325aeadac4c02310085649e6181bca5b Mon Sep 17 00:00:00 2001 From: marwin Date: Fri, 9 May 2025 20:00:46 +0100 Subject: [PATCH 14/16] =?UTF-8?q?=E2=9C=A8=20feat:=20enhance=20mindmap=20u?= =?UTF-8?q?pdate=20functionality=20in=20update=5Fmindmap.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- static/js/update_mindmap.js | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/static/js/update_mindmap.js b/static/js/update_mindmap.js index f840067..2a6c7d2 100644 --- a/static/js/update_mindmap.js +++ b/static/js/update_mindmap.js @@ -110,7 +110,9 @@ const mindmapData = { category: 'Philosophie', description: 'Die Lehre vom Denken und der Erkenntnis', hasChildren: true, - expanded: false + expanded: false, + neuronSize: 8, + neuronActivity: 0.8 }, { id: 'science', @@ -118,7 +120,9 @@ const mindmapData = { category: 'Wissenschaft', description: 'Systematische Erforschung der Natur und Gesellschaft', hasChildren: true, - expanded: false + expanded: false, + neuronSize: 8, + neuronActivity: 0.8 }, { id: 'technology', @@ -126,7 +130,9 @@ const mindmapData = { category: 'Technologie', description: 'Anwendung wissenschaftlicher Erkenntnisse', hasChildren: true, - expanded: false + expanded: false, + neuronSize: 8, + neuronActivity: 0.8 }, { id: 'arts', @@ -134,10 +140,19 @@ const mindmapData = { category: 'Künste', description: 'Kreativer Ausdruck und künstlerische Gestaltung', hasChildren: true, - expanded: false + expanded: false, + neuronSize: 8, + neuronActivity: 0.8 } ], - edges: [] + edges: [ + { source: 'philosophy', target: 'science', strength: 0.8 }, + { source: 'science', target: 'technology', strength: 0.8 }, + { source: 'technology', target: 'arts', strength: 0.6 }, + { source: 'arts', target: 'philosophy', strength: 0.6 }, + { source: 'philosophy', target: 'technology', strength: 0.4 }, + { source: 'science', target: 'arts', strength: 0.4 } + ] }; // Warte bis DOM geladen ist @@ -170,6 +185,7 @@ document.addEventListener('DOMContentLoaded', function() { category: node.category, description: node.description, hasChildren: node.hasChildren, + expanded: node.expanded, expanded: node.expanded } })), From 5ade301f8076ee9daa81d77d183558e580b4c9df Mon Sep 17 00:00:00 2001 From: marwin Date: Fri, 9 May 2025 20:06:35 +0100 Subject: [PATCH 15/16] noch nicht ganz --- static/js/update_mindmap.js | 353 +++++++++++++++++++++++------------- 1 file changed, 227 insertions(+), 126 deletions(-) diff --git a/static/js/update_mindmap.js b/static/js/update_mindmap.js index 2a6c7d2..ceb1dbc 100644 --- a/static/js/update_mindmap.js +++ b/static/js/update_mindmap.js @@ -186,7 +186,8 @@ document.addEventListener('DOMContentLoaded', function() { description: node.description, hasChildren: node.hasChildren, expanded: node.expanded, - expanded: node.expanded + neuronSize: node.neuronSize, + neuronActivity: node.neuronActivity } })), // Kanten @@ -194,14 +195,15 @@ document.addEventListener('DOMContentLoaded', function() { data: { source: edge.source, target: edge.target, - label: edge.label + label: edge.label, + strength: edge.strength } })) ]; console.log('Initialisiere Cytoscape...'); - // Initialisiere Cytoscape mit einfachem, stabilem Design + // Initialisiere Cytoscape mit neuronalem Design window.cy = cytoscape({ container: cyContainer, elements: elements, @@ -212,18 +214,26 @@ document.addEventListener('DOMContentLoaded', function() { 'background-color': 'data(color)', 'label': 'data(label)', 'color': '#fff', - 'text-background-color': '#222222', - 'text-background-opacity': 0.7, + 'text-background-color': 'rgba(0, 0, 0, 0.7)', + 'text-background-opacity': 0.8, 'text-background-padding': '4px', 'text-valign': 'center', 'text-halign': 'center', - 'font-size': 18, - 'width': 40, - 'height': 40, + 'font-size': 16, + 'width': 'mapData(neuronSize, 3, 10, 30, 60)', + 'height': 'mapData(neuronSize, 3, 10, 30, 60)', 'border-width': 2, 'border-color': '#fff', + 'border-opacity': 0.8, 'overlay-padding': 4, - 'z-index': 10 + 'z-index': 10, + 'shape': 'ellipse', + 'background-opacity': 0.85, + 'shadow-blur': 'mapData(neuronActivity, 0.3, 1, 10, 20)', + 'shadow-color': 'data(color)', + 'shadow-opacity': 0.6, + 'shadow-offset-x': 0, + 'shadow-offset-y': 0 } }, { @@ -236,25 +246,31 @@ document.addEventListener('DOMContentLoaded', function() { selector: 'node:selected', style: { 'border-color': '#f59e42', - 'border-width': 4 + 'border-width': 4, + 'shadow-blur': 30, + 'shadow-opacity': 0.8 } }, { selector: 'edge', style: { - 'width': 3, + 'width': 'mapData(strength, 0.2, 1, 1, 3)', 'line-color': '#a78bfa', + 'line-opacity': 'mapData(strength, 0.2, 1, 0.4, 0.8)', 'target-arrow-color': '#a78bfa', - 'target-arrow-shape': 'triangle', + 'target-arrow-shape': 'none', 'curve-style': 'bezier', - 'label': 'data(label)', - 'font-size': 12, - 'color': '#fff', - 'text-background-color': '#222222', - 'text-background-opacity': 0.7, - 'text-background-padding': '2px', - 'opacity': 0.8, - 'line-style': 'solid' + 'control-point-distances': [20, -20], + 'control-point-weights': [0.5, 0.5], + 'edge-distances': 'intersection', + 'loop-direction': '-45deg', + 'loop-sweep': '-90deg', + 'line-style': function(ele) { + const strength = ele.data('strength'); + if (strength <= 0.4) return 'dotted'; + if (strength <= 0.6) return 'dashed'; + return 'solid'; + } } }, { @@ -263,18 +279,57 @@ document.addEventListener('DOMContentLoaded', function() { 'width': 5, 'line-color': '#f59e42', 'target-arrow-color': '#f59e42', - 'opacity': 1 + 'opacity': 1, + 'line-style': 'solid' } } ], layout: { name: 'cose', + animate: true, + animationDuration: 1000, + nodeDimensionsIncludeLabels: true, + padding: 100, + spacingFactor: 1.8, + randomize: false, + fit: true, + componentSpacing: 100, + nodeRepulsion: 8000, + edgeElasticity: 100, animate: true } }); console.log('Cytoscape initialisiert'); + // Füge neuronale Eigenschaften zu allen Knoten hinzu + cy.nodes().forEach(node => { + const data = node.data(); + node.data({ + ...data, + neuronSize: data.neuronSize || 8, + neuronActivity: data.neuronActivity || 0.8, + refractionPeriod: Math.random() * 300 + 700, + threshold: Math.random() * 0.3 + 0.6, + lastFired: 0, + color: categoryColors[data.category] || '#60a5fa' + }); + }); + + // Füge synaptische Eigenschaften zu allen Kanten hinzu + cy.edges().forEach(edge => { + const data = edge.data(); + edge.data({ + ...data, + strength: data.strength || 0.5, + conductionVelocity: Math.random() * 0.5 + 0.3, + latency: Math.random() * 100 + 50 + }); + }); + + // Starte neuronale Aktivitätssimulation + startNeuralActivitySimulation(cy); + // Mindmap mit echten Daten befüllen (Styles, Farben etc.) updateMindmap(); @@ -302,113 +357,142 @@ const categoryColors = { 'Psychologie': '#ef4444' }; -// Mindmap aktualisieren +// Funktion zum Initialisieren des neuronalen Designs +function initializeNeuralDesign(cy) { + // Füge neuronale Eigenschaften zu allen Knoten hinzu + cy.nodes().forEach(node => { + const data = node.data(); + node.data({ + ...data, + neuronSize: data.neuronSize || 8, + neuronActivity: data.neuronActivity || 0.8, + refractionPeriod: Math.random() * 300 + 700, + threshold: Math.random() * 0.3 + 0.6, + lastFired: 0, + color: categoryColors[data.category] || '#60a5fa' + }); + }); + + // Füge synaptische Eigenschaften zu allen Kanten hinzu + cy.edges().forEach(edge => { + const data = edge.data(); + edge.data({ + ...data, + strength: data.strength || 0.5, + conductionVelocity: Math.random() * 0.5 + 0.3, + latency: Math.random() * 100 + 50 + }); + }); + + // Wende neuronales Styling an + cy.style() + .selector('node') + .style({ + 'background-color': 'data(color)', + 'label': 'data(label)', + 'color': '#fff', + 'text-background-color': 'rgba(0, 0, 0, 0.7)', + 'text-background-opacity': 0.8, + 'text-background-padding': '4px', + 'text-valign': 'center', + 'text-halign': 'center', + 'font-size': 16, + 'width': 'mapData(neuronSize, 3, 10, 30, 60)', + 'height': 'mapData(neuronSize, 3, 10, 30, 60)', + 'border-width': 2, + 'border-color': '#fff', + 'border-opacity': 0.8, + 'overlay-padding': 4, + 'z-index': 10, + 'shape': 'ellipse', + 'background-opacity': 0.85, + 'shadow-blur': 'mapData(neuronActivity, 0.3, 1, 10, 20)', + 'shadow-color': 'data(color)', + 'shadow-opacity': 0.6, + 'shadow-offset-x': 0, + 'shadow-offset-y': 0 + }) + .selector('edge') + .style({ + 'width': 'mapData(strength, 0.2, 1, 1, 3)', + 'line-color': '#a78bfa', + 'line-opacity': 'mapData(strength, 0.2, 1, 0.4, 0.8)', + 'target-arrow-color': '#a78bfa', + 'target-arrow-shape': 'none', + 'curve-style': 'bezier', + 'control-point-distances': [20, -20], + 'control-point-weights': [0.5, 0.5], + 'edge-distances': 'intersection', + 'loop-direction': '-45deg', + 'loop-sweep': '-90deg', + 'line-style': function(ele) { + const strength = ele.data('strength'); + if (strength <= 0.4) return 'dotted'; + if (strength <= 0.6) return 'dashed'; + return 'solid'; + } + }) + .update(); + + // Starte neuronale Aktivitätssimulation + startNeuralActivitySimulation(cy); +} + +// Modifiziere die updateMindmap Funktion function updateMindmap() { - if (!cy) return; - - // Bestehende Elemente entfernen - cy.elements().remove(); - - // Neue Knoten hinzufügen - mindmapData.nodes.forEach(node => { - cy.add({ - group: 'nodes', - data: { - id: node.id, - label: node.label, - category: node.category, - description: node.description, - color: categoryColors[node.category] || '#60a5fa', - hasChildren: node.hasChildren, - expanded: node.expanded - } + if (!cy) return; + + // Bestehende Elemente entfernen + cy.elements().remove(); + + // Neue Knoten hinzufügen + mindmapData.nodes.forEach(node => { + cy.add({ + group: 'nodes', + data: { + id: node.id, + label: node.label, + category: node.category, + description: node.description, + hasChildren: node.hasChildren, + expanded: node.expanded, + neuronSize: node.neuronSize, + neuronActivity: node.neuronActivity + } + }); }); - }); - - // Neue Kanten hinzufügen - mindmapData.edges.forEach(edge => { - cy.add({ - group: 'edges', - data: { - source: edge.source, - target: edge.target, - label: edge.label - } + + // Neue Kanten hinzufügen + mindmapData.edges.forEach(edge => { + cy.add({ + group: 'edges', + data: { + source: edge.source, + target: edge.target, + strength: edge.strength + } + }); }); - }); - - // Nur einfaches, klares Styling - KEINE Schatten, KEIN Glow, KEINE dynamischen Styles! - cy.style([ - { - selector: 'node', - style: { - 'label': 'data(label)', - 'text-valign': 'center', - 'text-halign': 'center', - 'text-wrap': 'wrap', - 'text-max-width': '100px', - 'font-size': '14px', - 'color': '#ffffff', - 'text-outline-color': '#0a0e19', - 'text-outline-width': 1.5, - 'text-outline-opacity': 0.9, - 'text-margin-y': 7, - 'width': 40, - 'height': 40, - 'background-color': 'data(color)', - 'background-opacity': 0.85, - 'border-width': 2, - 'shape': 'ellipse', - 'text-background-color': 'rgba(24, 28, 45, 0.7)', - 'text-background-opacity': 0.8, - 'text-background-shape': 'roundrectangle', - 'text-background-padding': '4px' - } - }, - { - selector: 'edge', - style: { - 'width': 3, - 'curve-style': 'bezier', - 'line-color': '#8a8aaa', - 'line-opacity': 0.7, - 'line-style': 'solid', - 'target-arrow-shape': 'triangle', - 'target-arrow-color': '#8a8aaa', - 'label': 'data(label)', - 'font-size': 12, - 'color': '#fff', - 'text-background-color': '#222222', - 'text-background-opacity': 0.7, - 'text-background-padding': '2px' - } - }, - { - selector: 'node:selected', - style: { - 'border-color': '#f59e42', - 'border-width': 4 - } - }, - { - selector: 'edge:selected', - style: { - 'width': 5, - 'line-color': '#f59e42', - 'target-arrow-color': '#f59e42', - 'opacity': 1 - } - } - ]); - - // Layout anwenden - cy.layout({ - name: 'cose', - animate: true, - animationDuration: 1800, - nodeDimensionsIncludeLabels: true, - padding: 100 - }).run(); + + // Neuronales Design initialisieren + initializeNeuralDesign(cy); + + // Layout anwenden + cy.layout({ + name: 'cose', + animate: true, + animationDuration: 1000, + nodeDimensionsIncludeLabels: true, + padding: 100, + spacingFactor: 1.8, + randomize: false, + fit: true, + componentSpacing: 100, + nodeRepulsion: 8000, + edgeElasticity: 100, + nestingFactor: 1.2, + gravity: 80 + }).run(); } /** @@ -756,11 +840,15 @@ async function loadSubthemes(node) { description: subtheme.description, hasChildren: subtheme.hasChildren, expanded: false, - color: categoryColors[subtheme.category] || '#60a5fa' + neuronSize: 6, + neuronActivity: 0.7 } }); }); + // Neuronales Design für die neue Mindmap initialisieren + initializeNeuralDesign(newCy); + // Event-Listener für die neue Mindmap newCy.on('tap', 'node', async function(evt) { const clickedNode = evt.target; @@ -841,5 +929,18 @@ style.textContent = ` width: 100%; height: calc(100% - 4rem); } + + /* Neuronale Effekte */ + .cy-container { + background: linear-gradient(45deg, #1a1a1a, #2a2a2a); + } + + .cy-container node { + transition: all 0.3s ease; + } + + .cy-container node:hover { + filter: brightness(1.2); + } `; document.head.appendChild(style); \ No newline at end of file From 412dabd5c13caebf4eb19ab2f0aa3c6322e2000d Mon Sep 17 00:00:00 2001 From: marwin Date: Fri, 9 May 2025 20:18:45 +0100 Subject: [PATCH 16/16] =?UTF-8?q?=E2=9C=A8=20feat(mindmap):=20f=C3=BCge=20?= =?UTF-8?q?Icons=20und=20Farben=20f=C3=BCr=20Kategorien=20hinzu,=20verbess?= =?UTF-8?q?ere=20das=20Layout=20und=20die=20Darstellung=20der=20Mindmap=20?= =?UTF-8?q?in=20update=5Fmindmap.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- static/js/update_mindmap.js | 278 ++++++++++++++++++++++-------------- 1 file changed, 168 insertions(+), 110 deletions(-) diff --git a/static/js/update_mindmap.js b/static/js/update_mindmap.js index ceb1dbc..08e6063 100644 --- a/static/js/update_mindmap.js +++ b/static/js/update_mindmap.js @@ -101,9 +101,36 @@ const subthemesDatabase = { ] }; -// Initiale Mindmap-Daten (nur oberste Ebene) +// Icon-Definitionen für Kategorien (FontAwesome oder SVG-URL) +const categoryIcons = { + 'Philosophie': 'fa-solid fa-lightbulb', + 'Wissenschaft': 'fa-solid fa-atom', + 'Technologie': 'fa-solid fa-microchip', + 'Künste': 'fa-solid fa-palette', + 'Psychologie': 'fa-solid fa-brain' +}; + +// Farben für Kategorien (wie im Bild) +const categoryColors = { + 'Philosophie': '#b71c1c', // Rot + 'Wissenschaft': '#f4b400', // Gelb + 'Technologie': '#0d47a1', // Blau + 'Künste': '#c2185b', // Pink + 'Psychologie': '#009688' // Türkis +}; + +// Initiale Mindmap-Daten (nur oberste Ebene, mit Icon und Farbe) const mindmapData = { nodes: [ + { + id: 'center', + label: 'Wissenskarte', + isCenter: true, + color: '#f5f5f5', + icon: 'fa-solid fa-circle', + fontColor: '#222', + fontSize: 22 + }, { id: 'philosophy', label: 'Philosophie', @@ -112,7 +139,11 @@ const mindmapData = { hasChildren: true, expanded: false, neuronSize: 8, - neuronActivity: 0.8 + neuronActivity: 0.8, + color: categoryColors['Philosophie'], + icon: categoryIcons['Philosophie'], + fontColor: '#fff', + fontSize: 18 }, { id: 'science', @@ -122,7 +153,11 @@ const mindmapData = { hasChildren: true, expanded: false, neuronSize: 8, - neuronActivity: 0.8 + neuronActivity: 0.8, + color: categoryColors['Wissenschaft'], + icon: categoryIcons['Wissenschaft'], + fontColor: '#fff', + fontSize: 18 }, { id: 'technology', @@ -132,7 +167,11 @@ const mindmapData = { hasChildren: true, expanded: false, neuronSize: 8, - neuronActivity: 0.8 + neuronActivity: 0.8, + color: categoryColors['Technologie'], + icon: categoryIcons['Technologie'], + fontColor: '#fff', + fontSize: 18 }, { id: 'arts', @@ -142,16 +181,18 @@ const mindmapData = { hasChildren: true, expanded: false, neuronSize: 8, - neuronActivity: 0.8 + neuronActivity: 0.8, + color: categoryColors['Künste'], + icon: categoryIcons['Künste'], + fontColor: '#fff', + fontSize: 18 } ], edges: [ - { source: 'philosophy', target: 'science', strength: 0.8 }, - { source: 'science', target: 'technology', strength: 0.8 }, - { source: 'technology', target: 'arts', strength: 0.6 }, - { source: 'arts', target: 'philosophy', strength: 0.6 }, - { source: 'philosophy', target: 'technology', strength: 0.4 }, - { source: 'science', target: 'arts', strength: 0.4 } + { source: 'center', target: 'philosophy', strength: 0.9 }, + { source: 'center', target: 'science', strength: 0.9 }, + { source: 'center', target: 'technology', strength: 0.9 }, + { source: 'center', target: 'arts', strength: 0.9 } ] }; @@ -187,7 +228,11 @@ document.addEventListener('DOMContentLoaded', function() { hasChildren: node.hasChildren, expanded: node.expanded, neuronSize: node.neuronSize, - neuronActivity: node.neuronActivity + neuronActivity: node.neuronActivity, + color: node.color, + icon: node.icon, + fontColor: node.fontColor, + fontSize: node.fontSize } })), // Kanten @@ -203,7 +248,7 @@ document.addEventListener('DOMContentLoaded', function() { console.log('Initialisiere Cytoscape...'); - // Initialisiere Cytoscape mit neuronalem Design + // Initialisiere Cytoscape mit concentric/circle Layout und Icon-Overlay window.cy = cytoscape({ container: cyContainer, elements: elements, @@ -213,90 +258,71 @@ document.addEventListener('DOMContentLoaded', function() { style: { 'background-color': 'data(color)', 'label': 'data(label)', - 'color': '#fff', - 'text-background-color': 'rgba(0, 0, 0, 0.7)', - 'text-background-opacity': 0.8, - 'text-background-padding': '4px', + 'color': 'data(fontColor)', 'text-valign': 'center', 'text-halign': 'center', - 'font-size': 16, - 'width': 'mapData(neuronSize, 3, 10, 30, 60)', - 'height': 'mapData(neuronSize, 3, 10, 30, 60)', - 'border-width': 2, + 'font-size': 'data(fontSize)', + 'width': 'mapData(neuronSize, 3, 10, 60, 110)', + 'height': 'mapData(neuronSize, 3, 10, 60, 110)', + 'border-width': 4, 'border-color': '#fff', - 'border-opacity': 0.8, + 'border-opacity': 0.9, 'overlay-padding': 4, 'z-index': 10, 'shape': 'ellipse', - 'background-opacity': 0.85, - 'shadow-blur': 'mapData(neuronActivity, 0.3, 1, 10, 20)', + 'background-opacity': 0.95, + 'shadow-blur': 20, 'shadow-color': 'data(color)', - 'shadow-opacity': 0.6, + 'shadow-opacity': 0.7, 'shadow-offset-x': 0, - 'shadow-offset-y': 0 + 'shadow-offset-y': 0, + 'text-wrap': 'wrap', + 'text-max-width': 90 } }, { - selector: 'node[!color]', - style: { - 'background-color': '#60a5fa' + selector: 'node[isCenter]','style': { + 'background-color': '#f5f5f5', + 'color': '#222', + 'font-size': 22, + 'border-width': 0, + 'width': 120, + 'height': 120 } }, { selector: 'node:selected', style: { 'border-color': '#f59e42', - 'border-width': 4, + 'border-width': 6, 'shadow-blur': 30, - 'shadow-opacity': 0.8 + 'shadow-opacity': 0.9 } }, { selector: 'edge', style: { - 'width': 'mapData(strength, 0.2, 1, 1, 3)', - 'line-color': '#a78bfa', - 'line-opacity': 'mapData(strength, 0.2, 1, 0.4, 0.8)', - 'target-arrow-color': '#a78bfa', - 'target-arrow-shape': 'none', + 'width': 'mapData(strength, 0.2, 1, 3, 7)', + 'line-color': '#bdbdbd', + 'line-opacity': 0.7, 'curve-style': 'bezier', - 'control-point-distances': [20, -20], + 'target-arrow-shape': 'none', + 'control-point-distances': [40, -40], 'control-point-weights': [0.5, 0.5], 'edge-distances': 'intersection', - 'loop-direction': '-45deg', - 'loop-sweep': '-90deg', - 'line-style': function(ele) { - const strength = ele.data('strength'); - if (strength <= 0.4) return 'dotted'; - if (strength <= 0.6) return 'dashed'; - return 'solid'; - } - } - }, - { - selector: 'edge:selected', - style: { - 'width': 5, - 'line-color': '#f59e42', - 'target-arrow-color': '#f59e42', - 'opacity': 1, 'line-style': 'solid' } } ], layout: { - name: 'cose', - animate: true, - animationDuration: 1000, - nodeDimensionsIncludeLabels: true, - padding: 100, - spacingFactor: 1.8, - randomize: false, + name: 'concentric', fit: true, - componentSpacing: 100, - nodeRepulsion: 8000, - edgeElasticity: 100, - animate: true + padding: 60, + animate: true, + concentric: function(node) { + return node.data('isCenter') ? 2 : 1; + }, + levelWidth: function() { return 1; } } }); @@ -346,16 +372,22 @@ document.addEventListener('DOMContentLoaded', function() { await loadSubthemes(node); } }); -}); -// Kategorie-Farben definieren -const categoryColors = { - 'Philosophie': '#60a5fa', - 'Wissenschaft': '#8b5cf6', - 'Technologie': '#10b981', - 'Künste': '#f59e0b', - 'Psychologie': '#ef4444' -}; + // Nach dem Rendern: Icons als HTML-Overlay einfügen + setTimeout(() => { + cy.nodes().forEach(node => { + const icon = node.data('icon'); + if (icon) { + const dom = cy.getElementById(node.id()).popperRef(); + const iconDiv = document.createElement('div'); + iconDiv.className = 'cy-node-icon'; + iconDiv.innerHTML = ``; + document.body.appendChild(iconDiv); + // Positionierung mit Popper.js oder absolut über node.position() + } + }); + }, 500); +}); // Funktion zum Initialisieren des neuronalen Designs function initializeNeuralDesign(cy) { @@ -440,49 +472,53 @@ function initializeNeuralDesign(cy) { // Modifiziere die updateMindmap Funktion function updateMindmap() { - if (!cy) return; - - // Bestehende Elemente entfernen - cy.elements().remove(); - - // Neue Knoten hinzufügen - mindmapData.nodes.forEach(node => { - cy.add({ - group: 'nodes', - data: { - id: node.id, - label: node.label, - category: node.category, - description: node.description, + if (!cy) return; + + // Bestehende Elemente entfernen + cy.elements().remove(); + + // Neue Knoten hinzufügen + mindmapData.nodes.forEach(node => { + cy.add({ + group: 'nodes', + data: { + id: node.id, + label: node.label, + category: node.category, + description: node.description, hasChildren: node.hasChildren, expanded: node.expanded, neuronSize: node.neuronSize, - neuronActivity: node.neuronActivity - } - }); + neuronActivity: node.neuronActivity, + color: node.color, + icon: node.icon, + fontColor: node.fontColor, + fontSize: node.fontSize + } }); - - // Neue Kanten hinzufügen - mindmapData.edges.forEach(edge => { - cy.add({ - group: 'edges', - data: { - source: edge.source, - target: edge.target, + }); + + // Neue Kanten hinzufügen + mindmapData.edges.forEach(edge => { + cy.add({ + group: 'edges', + data: { + source: edge.source, + target: edge.target, strength: edge.strength - } - }); + } }); - + }); + // Neuronales Design initialisieren initializeNeuralDesign(cy); - - // Layout anwenden - cy.layout({ - name: 'cose', - animate: true, + + // Layout anwenden + cy.layout({ + name: 'cose', + animate: true, animationDuration: 1000, - nodeDimensionsIncludeLabels: true, + nodeDimensionsIncludeLabels: true, padding: 100, spacingFactor: 1.8, randomize: false, @@ -492,7 +528,7 @@ function updateMindmap() { edgeElasticity: 100, nestingFactor: 1.2, gravity: 80 - }).run(); + }).run(); } /** @@ -765,7 +801,7 @@ function createFlashContainer() { container.className = 'fixed top-4 right-4 z-50 w-64'; document.body.appendChild(container); return container; -} +} // Funktion zum Laden der Subthemen async function loadSubthemes(node) { @@ -867,6 +903,20 @@ async function loadSubthemes(node) { // Erfolgsmeldung anzeigen showFlash('Subthemen erfolgreich geladen', 'success'); + // Icons für Subthemen wie oben einfügen + setTimeout(() => { + newCy.nodes().forEach(node => { + const icon = node.data('icon'); + if (icon) { + const dom = newCy.getElementById(node.id()).popperRef(); + const iconDiv = document.createElement('div'); + iconDiv.className = 'cy-node-icon'; + iconDiv.innerHTML = ``; + document.body.appendChild(iconDiv); + } + }); + }, 500); + } catch (error) { console.error('Fehler beim Laden der Subthemen:', error); showFlash('Fehler beim Laden der Subthemen', 'error'); @@ -942,5 +992,13 @@ style.textContent = ` .cy-container node:hover { filter: brightness(1.2); } + + .cy-node-icon { + position: absolute; + pointer-events: none; + z-index: 1001; + color: #fff; + text-shadow: 0 2px 8px rgba(0,0,0,0.25); + } `; document.head.appendChild(style); \ No newline at end of file