WP19 #10

Merged
Lars merged 36 commits from WP19 into main 2025-12-14 20:50:04 +01:00
Showing only changes of commit cee8fc05c2 - Show all commits

View File

@ -7,31 +7,34 @@ from ui_callbacks import switch_to_editor_callback
def render_graph_explorer_cytoscape(graph_service): def render_graph_explorer_cytoscape(graph_service):
st.header("🕸️ Graph Explorer (Cytoscape)") st.header("🕸️ Graph Explorer (Cytoscape)")
# --- 1. STATE INITIALISIERUNG --- # ---------------------------------------------------------
# Graph Zentrum (Roter Rahmen, bestimmt die geladenen Daten) # 1. STATE MANAGEMENT
# ---------------------------------------------------------
# Das aktive Zentrum des Graphen (bestimmt welche Knoten geladen werden)
if "graph_center_id" not in st.session_state: if "graph_center_id" not in st.session_state:
st.session_state.graph_center_id = None st.session_state.graph_center_id = None
# Inspizierter Knoten (Gelber Rahmen, bestimmt Inspector & Editor) # Der aktuell inspizierte Knoten (bestimmt Inspector & Editor Inhalt)
# Getrennt vom Zentrum, damit man klicken kann ohne neu zu laden.
if "graph_inspected_id" not in st.session_state: if "graph_inspected_id" not in st.session_state:
st.session_state.graph_inspected_id = None st.session_state.graph_inspected_id = None
# Defaults für Layout-Parameter (COSE) # Layout Defaults für COSE Algorithmus
st.session_state.setdefault("cy_node_repulsion", 1000000) st.session_state.setdefault("cy_node_repulsion", 1000000)
st.session_state.setdefault("cy_ideal_edge_len", 150) st.session_state.setdefault("cy_ideal_edge_len", 150)
st.session_state.setdefault("cy_depth", 2) st.session_state.setdefault("cy_depth", 2)
# Layout Spalten
col_ctrl, col_graph = st.columns([1, 4]) col_ctrl, col_graph = st.columns([1, 4])
# --- 2. LINKES PANEL (CONTROLS) --- # ---------------------------------------------------------
# 2. LINKES PANEL (Steuerung)
# ---------------------------------------------------------
with col_ctrl: with col_ctrl:
st.subheader("Fokus") st.subheader("Fokus")
# Suchfeld # Suchfeld
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search") search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
# Suchlogik
if search_term: if search_term:
hits, _ = graph_service.client.scroll( hits, _ = graph_service.client.scroll(
collection_name=f"{COLLECTION_PREFIX}_notes", collection_name=f"{COLLECTION_PREFIX}_notes",
@ -44,7 +47,7 @@ def render_graph_explorer_cytoscape(graph_service):
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select") selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
if st.button("Laden", use_container_width=True, key="cy_load"): if st.button("Laden", use_container_width=True, key="cy_load"):
new_id = options[selected_title] new_id = options[selected_title]
# Bei Suche setzen wir beides neu # Bei neuer Suche setzen wir beides auf das Ziel
st.session_state.graph_center_id = new_id st.session_state.graph_center_id = new_id
st.session_state.graph_inspected_id = new_id st.session_state.graph_inspected_id = new_id
st.rerun() st.rerun()
@ -69,45 +72,47 @@ def render_graph_explorer_cytoscape(graph_service):
for k, v in list(GRAPH_COLORS.items())[:8]: for k, v in list(GRAPH_COLORS.items())[:8]:
st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True) st.markdown(f"<span style='color:{v}'>●</span> {k}", unsafe_allow_html=True)
# --- 3. RECHTES PANEL (GRAPH & INSPECTOR) --- # ---------------------------------------------------------
# 3. RECHTES PANEL (Graph & Tools)
# ---------------------------------------------------------
with col_graph: with col_graph:
center_id = st.session_state.graph_center_id center_id = st.session_state.graph_center_id
# Initialisierung Fallback # Fallback Init
if not center_id and st.session_state.graph_inspected_id: if not center_id and st.session_state.graph_inspected_id:
center_id = st.session_state.graph_inspected_id center_id = st.session_state.graph_inspected_id
st.session_state.graph_center_id = center_id st.session_state.graph_center_id = center_id
if center_id: if center_id:
# Sync: Wenn Inspection None ist, setze auf Center # Sync: Falls Inspektion leer ist, mit Zentrum füllen
if not st.session_state.graph_inspected_id: if not st.session_state.graph_inspected_id:
st.session_state.graph_inspected_id = center_id st.session_state.graph_inspected_id = center_id
inspected_id = st.session_state.graph_inspected_id inspected_id = st.session_state.graph_inspected_id
# --- 3.1 DATEN LADEN --- # --- DATEN LADEN ---
with st.spinner(f"Lade Graph (Tiefe {st.session_state.cy_depth})..."): with st.spinner(f"Lade Graph (Tiefe {st.session_state.cy_depth})..."):
# 1. Graph Daten für das ZENTRUM # 1. Graph Daten (Abhängig vom Zentrum)
nodes_data, edges_data = graph_service.get_ego_graph( nodes_data, edges_data = graph_service.get_ego_graph(
center_id, center_id,
depth=st.session_state.cy_depth depth=st.session_state.cy_depth
) )
# 2. Detail Daten für die INSPEKTION (Editor/Text) # 2. Detail Daten (Abhängig von der Inspektion)
# Holt Metadaten UND den gestitchten Volltext
inspected_data = graph_service.get_note_with_full_content(inspected_id) inspected_data = graph_service.get_note_with_full_content(inspected_id)
# --- 3.2 ACTION BAR & INSPECTOR --- # --- ACTION BAR ---
action_container = st.container() action_container = st.container()
with action_container: with action_container:
# Obere Zeile: Info & Buttons
c1, c2, c3 = st.columns([2, 1, 1]) c1, c2, c3 = st.columns([2, 1, 1])
with c1: with c1:
# Titel anzeigen
title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id title_show = inspected_data.get('title', inspected_id) if inspected_data else inspected_id
st.info(f"**Aktuell gewählt:** {title_show}") st.info(f"**Info:** {title_show}")
with c2: with c2:
# NAVIGATION BUTTON # NAVIGATION: Nur aktiv, wenn wir nicht schon im Zentrum sind
# Nur anzeigen, wenn wir nicht schon im Zentrum sind
if inspected_id != center_id: if inspected_id != center_id:
if st.button("🎯 Als Zentrum setzen", use_container_width=True, key="cy_nav_btn"): if st.button("🎯 Als Zentrum setzen", use_container_width=True, key="cy_nav_btn"):
st.session_state.graph_center_id = inspected_id st.session_state.graph_center_id = inspected_id
@ -116,7 +121,7 @@ def render_graph_explorer_cytoscape(graph_service):
st.caption("_(Ist aktuelles Zentrum)_") st.caption("_(Ist aktuelles Zentrum)_")
with c3: with c3:
# EDIT BUTTON # EDITIEREN: Startet den Editor mit den Daten des inspizierten Knotens
if inspected_data: if inspected_data:
st.button("📝 Bearbeiten", st.button("📝 Bearbeiten",
use_container_width=True, use_container_width=True,
@ -124,37 +129,55 @@ def render_graph_explorer_cytoscape(graph_service):
args=(inspected_data,), args=(inspected_data,),
key="cy_edit_btn") key="cy_edit_btn")
# DATA INSPECTOR (Standard: Eingeklappt) # --- DATA INSPECTOR ---
with st.expander("🕵️ Data Inspector (Details)", expanded=False): with st.expander("🕵️ Data Inspector (Details)", expanded=False):
if inspected_data: if inspected_data:
# Spalte 1: IDs und Typen
col_i1, col_i2 = st.columns(2) col_i1, col_i2 = st.columns(2)
with col_i1: with col_i1:
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`") st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
st.markdown(f"**Typ:** `{inspected_data.get('type')}`") st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
# Spalte 2: Tags und Pfad-Status
with col_i2: with col_i2:
st.markdown(f"**Tags:** {', '.join(inspected_data.get('tags', []))}") tags = inspected_data.get('tags', [])
path_check = "" if inspected_data.get('path') else "" st.markdown(f"**Tags:** {', '.join(tags) if tags else '-'}")
st.markdown(f"**Pfad:** {path_check}")
st.text_area("Inhalt (Vorschau)", inspected_data.get('fulltext', '')[:1000], height=200, disabled=True) has_path = bool(inspected_data.get('path'))
path_icon = "" if has_path else ""
st.markdown(f"**Pfad:** {path_icon}")
if has_path:
st.caption(f"_{inspected_data.get('path')}_")
st.divider()
# Content Preview
st.caption("Inhalt (Vorschau aus Stitching):")
fulltext = inspected_data.get('fulltext', '')
st.text_area("Body", fulltext[:1200] + "...", height=200, disabled=True, label_visibility="collapsed")
# Raw Data Expander
with st.expander("📄 Raw JSON anzeigen"):
st.json(inspected_data)
else: else:
st.warning("Keine Daten geladen.") st.warning("Keine Daten für diesen Knoten gefunden.")
# --- 3.3 ELEMENT VORBEREITUNG --- # ---------------------------------------------------------
# 4. GRAPH VORBEREITUNG (Elemente & Styles)
# ---------------------------------------------------------
cy_elements = [] cy_elements = []
# Nodes erstellen # Nodes erstellen
for n in nodes_data: for n in nodes_data:
# Klassenlogik für Styling (statt Selection State) # Logik für visuelle Klassen
classes = [] classes = []
if n.id == center_id: if n.id == center_id:
classes.append("center") classes.append("center")
# Wir markieren den inspizierten Knoten visuell
if n.id == inspected_id: if n.id == inspected_id:
classes.append("inspected") classes.append("inspected")
# Label kürzen für Anzeige # Label für Anzeige kürzen
tooltip_text = n.title if n.title else n.label
display_label = n.label display_label = n.label
if len(display_label) > 15 and " " in display_label: if len(display_label) > 15 and " " in display_label:
display_label = display_label.replace(" ", "\n", 1) display_label = display_label.replace(" ", "\n", 1)
@ -164,13 +187,11 @@ def render_graph_explorer_cytoscape(graph_service):
"id": n.id, "id": n.id,
"label": display_label, "label": display_label,
"bg_color": n.color, "bg_color": n.color,
# Tooltip Inhalt "tooltip": tooltip_text
"tooltip": n.title if n.title else n.label
}, },
"classes": " ".join(classes), "classes": " ".join(classes),
# WICHTIG: Wir setzen selected immer auf False beim Init, # Wir nutzen KEINE interne Selektion (:selected),
# damit wir nicht mit dem internen State des Browsers kämpfen. # sondern steuern das Aussehen über die Klasse .inspected
# Die Visualisierung passiert über die Klasse .inspected
"selected": False "selected": False
} }
cy_elements.append(cy_node) cy_elements.append(cy_node)
@ -189,68 +210,57 @@ def render_graph_explorer_cytoscape(graph_service):
} }
cy_elements.append(cy_edge) cy_elements.append(cy_edge)
# --- 3.4 STYLESHEET --- # Stylesheet (Design Definitionen)
stylesheet = [ stylesheet = [
# BASIS NODE STYLE # BASIS NODE
{ {
"selector": "node", "selector": "node",
"style": { "style": {
"label": "data(label)", "label": "data(label)",
"width": "30px", "width": "30px", "height": "30px",
"height": "30px",
"background-color": "data(bg_color)", "background-color": "data(bg_color)",
"color": "#333", "color": "#333", "font-size": "12px",
"font-size": "12px", "text-valign": "center", "text-halign": "center",
"text-valign": "center", "text-wrap": "wrap", "text-max-width": "90px",
"text-halign": "center", "border-width": 2, "border-color": "#fff",
"text-wrap": "wrap", "title": "data(tooltip)" # Hover Text
"text-max-width": "90px",
"border-width": 2,
"border-color": "#fff",
"title": "data(tooltip)"
} }
}, },
# KLASSE: INSPECTED (Gelber Rahmen) - Ersetzt :selected # INSPECTED (Gelber Rahmen)
{ {
"selector": ".inspected", "selector": ".inspected",
"style": { "style": {
"border-width": 6, "border-width": 6,
"border-color": "#FFC300", # Gelb/Gold "border-color": "#FFC300",
"width": "50px", "width": "50px", "height": "50px",
"height": "50px",
"font-weight": "bold", "font-weight": "bold",
"z-index": 999 "z-index": 999
} }
}, },
# KLASSE: CENTER (Roter Rahmen) # CENTER (Roter Rahmen)
{ {
"selector": ".center", "selector": ".center",
"style": { "style": {
"border-width": 4, "border-width": 4,
"border-color": "#FF5733", # Rot "border-color": "#FF5733",
"width": "40px", "width": "40px", "height": "40px"
"height": "40px"
} }
}, },
# KOMBINATION: Center ist auch Inspected # CENTER + INSPECTED (Kombination)
{ {
"selector": ".center.inspected", "selector": ".center.inspected",
"style": { "style": {
"border-width": 6, "border-width": 6,
"border-color": "#FF5733", # Rot gewinnt (oder Mix) "border-color": "#FF5733", # Zentrum Farbe dominiert
"width": "55px", "width": "55px", "height": "55px"
"height": "55px"
} }
}, },
# NATIVE SELEKTION (Unterdrücken/Anpassen) # SELECT STATE OVERRIDE (Verstecken des Standard-Rahmens)
# Wir machen den Standard-Selektionsrahmen unsichtbar(er),
# da wir .inspected nutzen.
{ {
"selector": "node:selected", "selector": "node:selected",
"style": { "style": {
"overlay-opacity": 0, "border-width": 0,
"border-width": 6, "overlay-opacity": 0
"border-color": "#FFC300"
} }
}, },
# EDGE STYLE # EDGE STYLE
@ -263,20 +273,18 @@ def render_graph_explorer_cytoscape(graph_service):
"target-arrow-shape": "triangle", "target-arrow-shape": "triangle",
"curve-style": "bezier", "curve-style": "bezier",
"label": "data(label)", "label": "data(label)",
"font-size": "10px", "font-size": "10px", "color": "#666",
"color": "#666", "text-background-opacity": 0.8, "text-background-color": "#fff"
"text-background-opacity": 0.8,
"text-background-color": "#fff"
} }
} }
] ]
# --- 3.5 RENDERING --- # ---------------------------------------------------------
# KEY STRATEGIE: # 5. RENDERING
# Der Key darf NICHT von 'graph_inspected_id' abhängen. # ---------------------------------------------------------
# Er hängt nur von 'center_id' und Layout-Settings ab. # Der Key bestimmt, wann der Graph komplett neu gebaut wird.
# Wenn wir eine Node anklicken, ändert sich inspected_id -> Rerun. # Wir nutzen hier center_id und settings.
# Da der Key gleich bleibt, wird der Graph NICHT neu initialisiert -> Kein Springen! # NICHT inspected_id -> Das verhindert das Springen beim Klicken!
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}" graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
clicked_elements = cytoscape( clicked_elements = cytoscape(
@ -289,7 +297,7 @@ def render_graph_explorer_cytoscape(graph_service):
"refresh": 20, "refresh": 20,
"fit": True, "fit": True,
"padding": 50, "padding": 50,
"randomize": False, # WICHTIG für Stabilität "randomize": False, # Wichtig für Stabilität
"componentSpacing": 100, "componentSpacing": 100,
"nodeRepulsion": st.session_state.cy_node_repulsion, "nodeRepulsion": st.session_state.cy_node_repulsion,
"edgeElasticity": 100, "edgeElasticity": 100,
@ -305,18 +313,23 @@ def render_graph_explorer_cytoscape(graph_service):
height="700px" height="700px"
) )
# --- 3.6 EVENT HANDLING --- # ---------------------------------------------------------
# 6. EVENT HANDLING
# ---------------------------------------------------------
if clicked_elements: if clicked_elements:
clicked_nodes = clicked_elements.get("nodes", []) clicked_nodes = clicked_elements.get("nodes", [])
if clicked_nodes: if clicked_nodes:
# Die Liste enthält die IDs der selektierten Knoten
clicked_id = clicked_nodes[0] clicked_id = clicked_nodes[0]
# Wenn wir auf einen neuen Knoten klicken, ändern wir NUR die Inspektion. # Wenn auf einen neuen Knoten geklickt wurde:
# Das triggert einen Rerun.
# Da der graph_key gleich bleibt, wird nur der Style (.inspected Klasse) geupdated.
if clicked_id != st.session_state.graph_inspected_id: if clicked_id != st.session_state.graph_inspected_id:
# 1. State aktualisieren (Inspektion verschieben)
st.session_state.graph_inspected_id = clicked_id st.session_state.graph_inspected_id = clicked_id
# 2. Rerun triggern
# Da graph_key sich NICHT ändert, bleibt der Graph stabil,
# nur die CSS-Klassen (.inspected) werden aktualisiert.
st.rerun() st.rerun()
else: else: