This commit is contained in:
2026-10-24 19:13:05 +02:00
parent 28855f7043
commit 673324e7be
+312 -55
View File
@@ -5,74 +5,285 @@ use std::path::{Path, PathBuf};
use std::collections::HashMap;
use eframe::egui::{self, Align2, Color32, FontId, Pos2, Sense, Stroke, Vec2};
use std::f32::consts::PI;
use std::collections::BTreeMap;
#[derive(Default)]
struct Dir {
dirs: BTreeMap<String, Dir>,
files: Vec<usize>, // note indices
}
impl Dir {
fn build(notes: &[Note]) -> Self {
let mut root = Dir::default();
for (i, note) in notes.iter().enumerate() {
let mut cur = &mut root;
for part in &note.tags {
cur = cur.dirs.entry(part.clone()).or_default();
}
cur.files.push(i);
}
root
}
}
fn show_dir(ui: &mut egui::Ui, dir: &Dir, notes: &[Note], open: &mut Option<usize>) {
for (name, sub) in &dir.dirs {
egui::CollapsingHeader::new(name).show(ui, |ui| {
show_dir(ui, sub, notes, open);
});
}
for &i in &dir.files {
if ui.selectable_label(*open == Some(i), &notes[i].title).clicked() {
*open = Some(i);
}
}
}
type V3 = [f32; 3];
struct App {
vault: Vault,
pos: Vec<Pos2>, // node positions in "world" space
pan: Vec2,
pos: Vec<V3>,
vel: Vec<V3>,
edges: Vec<(usize, usize)>,
yaw: f32,
pitch: f32,
zoom: f32,
heat: f32, // simulation energy, cools over time
auto_spin: bool,
tree: Dir,
open: Option<usize>, // None = show the graph
}
impl App {
fn graph_ui(&mut self, ui: &mut egui::Ui) {
let (resp, painter) =
ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
// camera: drag = orbit, scroll = zoom, double-click = toggle spin
let d = resp.drag_delta();
self.yaw += d.x * 0.01;
self.pitch = (self.pitch + d.y * 0.01).clamp(-1.5, 1.5);
if resp.hovered() {
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
self.zoom = (self.zoom * (1.0 + scroll * 0.002)).clamp(0.2, 5.0);
}
if resp.double_clicked() {
self.auto_spin = !self.auto_spin;
}
if self.auto_spin {
self.yaw += 0.003;
}
self.step();
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(33)); // ~30 fps
let center = resp.rect.center();
let n = self.pos.len();
let proj: Vec<(Pos2, f32, f32)> =
(0..n).map(|i| self.project(self.pos[i], center)).collect();
// 1. edges (dimmer when far away)
for &(a, b) in &self.edges {
let (pa, sa, _) = proj[a];
let (pb, sb, _) = proj[b];
let s = (sa + sb) * 0.5;
let alpha = (s * 140.0).clamp(30.0, 200.0) as u8;
painter.line_segment(
[pa, pb],
Stroke::new(1.2 * s, Color32::from_rgba_unmultiplied(160, 160, 160, alpha)),
);
}
// 2. nodes, far to near
let mut order: Vec<usize> = (0..n).collect();
order.sort_by(|&a, &b| proj[b].2.partial_cmp(&proj[a].2).unwrap());
let hover = resp.hover_pos();
for &i in &order {
let (p, s, _) = proj[i];
let r = self.radius(i) * s * self.zoom;
let hovered = hover.map_or(false, |h| h.distance(p) <= r);
let (cr, cg, cb) = if self.vault.is_tag(i) { (200, 140, 70) } else { (90, 130, 200) };
let fade = s.clamp(0.4, 1.0);
let base = Color32::from_rgb(
(cr as f32 * fade) as u8,
(cg as f32 * fade) as u8,
(cb as f32 * fade) as u8,
);
let color = if hovered { Color32::LIGHT_BLUE } else { base };
painter.circle_filled(p, r, color);
/*painter.text(
p + Vec2::new(0.0, r + 3.0),
Align2::CENTER_TOP,
self.vault.label(i),
FontId::proportional((13.0 * s * self.zoom).clamp(8.0, 20.0)),
Color32::from_white_alpha((s * 255.0).clamp(80.0, 255.0) as u8),
);*/
if hovered && resp.clicked() && !self.vault.is_tag(i) {
self.open = Some(i);
}
}
}
fn editor_ui(&mut self, ui: &mut egui::Ui, i: usize) {
ui.horizontal(|ui| {
if ui.button("← Graph").clicked() {
self.open = None;
}
ui.heading(&self.vault.notes[i].title);
});
ui.separator();
egui::ScrollArea::vertical().show(ui, |ui| {
ui.add(
egui::TextEdit::multiline(&mut self.vault.notes[i].raw)
.desired_width(f32::INFINITY)
.desired_rows(30)
.code_editor(),
);
});
}
fn new(vault: Vault) -> Self {
let n = vault.notes.len();
let pos = (0..n)
let n = vault.node_count();
// evenly spread start positions on a sphere (Fibonacci sphere)
let pos: Vec<V3> = (0..n)
.map(|i| {
let a = 2.0 * PI * i as f32 / n as f32;
Pos2::new(300.0 * a.cos(), 300.0 * a.sin())
let t = (i as f32 + 0.5) / n.max(1) as f32;
let phi = (1.0 - 2.0 * t).acos();
let theta = PI * (1.0 + 5f32.sqrt()) * i as f32;
[
300.0 * phi.sin() * theta.cos(),
300.0 * phi.cos(),
300.0 * phi.sin() * theta.sin(),
]
})
.collect();
Self { vault, pos, pan: Vec2::ZERO }
let edges: Vec<(usize, usize)> = (0..n)
.flat_map(|a| vault.links.links_from(a).map(move |b| (a, b)))
.filter(|(a, b)| a != b)
.collect();
let tree = Dir::build(&vault.notes);
Self {
vault,
pos,
vel: vec![[0.0; 3]; n],
edges,
yaw: 0.0,
pitch: 0.3,
zoom: 1.0,
heat: 1.0,
auto_spin: false,
tree,
open: None,
}
}
fn radius(&self, i: usize) -> f32 {
10.0 + 4.0 * self.vault.links.in_degree(i).min(5) as f32 // the size knob
10.0 + 4.0 * self.vault.links.in_degree(i).min(5) as f32
}
/// one physics step
fn step(&mut self) {
let n = self.pos.len();
let mut f = vec![[0.0f32; 3]; n];
// repulsion between every pair
for a in 0..n {
for b in (a + 1)..n {
let d = sub(self.pos[a], self.pos[b]);
let dist2 = dot(d, d).max(1.0);
let dist = dist2.sqrt();
let u = mul(d, 20000.0 / dist2 / dist);
add_to(&mut f[a], u);
add_to(&mut f[b], mul(u, -1.0));
}
}
// springs along links
for &(a, b) in &self.edges {
let d = sub(self.pos[b], self.pos[a]);
let dist = dot(d, d).sqrt().max(0.01);
let u = mul(d, 0.02 * (dist - 120.0) / dist);
add_to(&mut f[a], u);
add_to(&mut f[b], mul(u, -1.0));
}
for i in 0..n {
let p = self.pos[i];
add_to(&mut f[i], mul(p, -0.005)); // pull to center
add_to(&mut f[i], [-p[2] * 0.002, 0.0, p[0] * 0.002]); // swirl = orbit
}
for i in 0..n {
for k in 0..3 {
let v = (self.vel[i][k] + f[i][k] * self.heat) * 0.85;
self.vel[i][k] = v;
self.pos[i][k] += v;
}
}
self.heat = (self.heat * 0.998).max(0.15); // never fully stops, so the orbit keeps going
}
/// world -> (screen pos, perspective scale, depth)
fn project(&self, p: V3, center: Pos2) -> (Pos2, f32, f32) {
let (sy, cy) = self.yaw.sin_cos();
let (sp, cp) = self.pitch.sin_cos();
let x1 = p[0] * cy + p[2] * sy;
let z1 = -p[0] * sy + p[2] * cy;
let y2 = p[1] * cp - z1 * sp;
let z2 = p[1] * sp + z1 * cp;
let cam = 900.0;
let s = cam / (cam + z2).max(50.0);
(center + Vec2::new(x1, y2) * s * self.zoom, s, z2)
}
}
fn sub(a: V3, b: V3) -> V3 { [a[0] - b[0], a[1] - b[1], a[2] - b[2]] }
fn mul(a: V3, s: f32) -> V3 { [a[0] * s, a[1] * s, a[2] * s] }
fn dot(a: V3, b: V3) -> f32 { a[0] * b[0] + a[1] * b[1] + a[2] * b[2] }
fn add_to(a: &mut V3, b: V3) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; }
impl eframe::App for App {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ui, |ui| {
let (resp, painter) =
ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
egui::Panel::left("files")
.resizable(true)
.default_size(220.0)
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.heading("Files");
if ui.button("Graph").clicked() {
self.open = None;
}
});
ui.separator();
egui::ScrollArea::vertical().show(ui, |ui| {
show_dir(ui, &self.tree, &self.vault.notes, &mut self.open);
});
});
// drag background to pan
self.pan += resp.drag_delta();
let center = resp.rect.center().to_vec2() + self.pan;
let to_screen = |p: Pos2| p + center;
// 1. edges (with arrowheads, trimmed to the node circles)
let n = self.vault.notes.len();
for a in 0..n {
for b in self.vault.links.links_from(a).filter(|&b| b != a) {
let (pa, pb) = (to_screen(self.pos[a]), to_screen(self.pos[b]));
let dir = (pb - pa).normalized();
let start = pa + dir * self.radius(a);
let end = pb - dir * self.radius(b);
painter.arrow(start, end - start, Stroke::new(1.5, Color32::GRAY));
}
}
// 2. nodes + labels
let hover = resp.hover_pos();
for i in 0..n {
let p = to_screen(self.pos[i]);
let r = self.radius(i);
let hovered = hover.map_or(false, |h| h.distance(p) <= r);
let color = if hovered { Color32::LIGHT_BLUE } else { Color32::from_rgb(90, 130, 200) };
painter.circle_filled(p, r, color);
painter.text(
p + Vec2::new(0.0, r + 4.0),
Align2::CENTER_TOP,
&self.vault.notes[i].title, // guessing `title` again
FontId::proportional(13.0),
Color32::WHITE,
);
if hovered && resp.clicked() {
println!("open note {i}");
}
}
egui::CentralPanel::default().show(ui, |ui| match self.open {
Some(i) => self.editor_ui(ui, i),
None => self.graph_ui(ui),
});
}
}
@@ -185,37 +396,83 @@ impl AdjMatrix {
struct Vault {
notes: Vec<Note>,
tags: HashMap<String, Vec<usize>>,
tag_names: Vec<String>, // sorted; tag t is graph node notes.len() + t
images: Vec<PathBuf>,
links: AdjMatrix, // links.has_edge(a, b): note a links to note b
links: AdjMatrix,
}
impl Vault {
fn node_count(&self) -> usize {
self.notes.len() + self.tag_names.len()
}
fn is_tag(&self, node: usize) -> bool {
node >= self.notes.len()
}
fn label(&self, node: usize) -> String {
if self.is_tag(node) {
format!("#{}", self.tag_names[node - self.notes.len()])
} else {
self.notes[node].title.clone()
}
}
}
fn scan_dir(root: &Path) -> io::Result<Vault> {
let mut vault = Vault::default();
walk(root, root, false, &mut vault)?;
vault.links = AdjMatrix::new(vault.notes.len());
vault.tag_names = vault.tags.keys().cloned().collect();
vault.tag_names.sort();
vault.links = AdjMatrix::new(vault.node_count());
scan_links(&mut vault)?;
Ok(vault)
}
fn scan_links(vault: &mut Vault) -> io::Result<()> {
// file stem -> note index, for resolving [[targets]]
let note_count = vault.notes.len();
// file stem -> note index
let mut by_stem: HashMap<String, usize> = HashMap::new();
for (i, n) in vault.notes.iter().enumerate() {
if let Some(stem) = n.path.file_stem().and_then(|s| s.to_str()) {
// first note wins if two folders have the same file name
by_stem.entry(stem.to_lowercase()).or_insert(i);
}
}
for from in 0..vault.notes.len() {
// lowercase tag name -> tag node index
let by_tag: HashMap<String, usize> = vault
.tag_names
.iter()
.enumerate()
.map(|(t, name)| (name.to_lowercase(), note_count + t))
.collect();
// [[...]] links inside note text
for from in 0..note_count {
for target in extract_links(&vault.notes[from].raw) {
if let Some(&to) = by_stem.get(&target.to_lowercase()) {
let key = target.to_lowercase();
if let Some(&to) = by_stem.get(&key) {
if to != from {
vault.links.add_edge(from, to);
}
} else if let Some(&tag_node) = by_tag.get(&key) {
vault.links.add_edge(from, tag_node); // [[tagname]] links to the tag node
}
}
}
// every note -> each of its tags
for (t, name) in vault.tag_names.iter().enumerate() {
let tag_node = note_count + t;
for &note in &vault.tags[name] {
vault.links.add_edge(note, tag_node);
}
}
Ok(())
}