mirror of
https://github.com/Dasemu/Logseq-SemiLinear-Graph.git
synced 2026-11-26 07:16:18 +00:00
Add Logseq semi-linear timeline graph visualizer
Parses a Logseq graph's journals and pages into a node/edge JSON, then renders a force-directed D3 view where journals sit on a fixed chronological line and notes float above it, weighted by link count.
This commit is contained in:
commit
9a153786ac
5 files changed
+812
No files matched your search
+10
@@ -0,0 +1,10 @@
|
||||
# Generated output — contains the actual content of a personal Logseq graph
|
||||
graph_data.json
|
||||
graph_view.html
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# OS / editor
|
||||
.DS_Store
|
||||
@@ -0,0 +1,54 @@
|
||||
# Logseq SemiLinear Graph
|
||||
|
||||
Visualización experimental para grafos de [Logseq](https://logseq.com/): los *journals*
|
||||
(notas diarias) se colocan en una única línea horizontal ordenada cronológicamente, y el
|
||||
resto de páginas ("notas") flotan por encima, posicionadas mediante una simulación de
|
||||
fuerzas (`d3-force`) según cuántos enlaces tienen y a qué journals/páginas están conectadas.
|
||||
|
||||
El resultado es una especie de línea de tiempo: cuanto más conectada está una nota, más
|
||||
cerca se queda de la línea; las notas más periféricas se dispersan hacia arriba.
|
||||
|
||||
## Cómo funciona
|
||||
|
||||
1. **`parse_graph.py`** recorre las carpetas `journals/` y `pages/` de un grafo de Logseq,
|
||||
extrae los enlaces `[[...]]` y `#tags`, resuelve los enlaces a fechas de journal
|
||||
(formato `[[Apr 27th, 2026]]`) contra los archivos `yyyy_MM_dd.md`, y vuelca todo a
|
||||
`graph_data.json` (nodos, aristas y grado de cada nodo).
|
||||
2. **`build_html.py`** toma `graph_data.json` y genera `graph_view.html`: una página
|
||||
autocontenida (D3.js vendorizado en `vendor/d3.min.js`, sin dependencias de red) con
|
||||
el visualizador interactivo.
|
||||
|
||||
## Uso
|
||||
|
||||
```bash
|
||||
python3 parse_graph.py /ruta/a/tu/graph_data.json
|
||||
python3 build_html.py
|
||||
```
|
||||
|
||||
Por defecto ambos scripts leen el grafo desde `~/Notas` (editar las constantes `NOTAS`,
|
||||
`DATA_PATH`/`OUT_PATH` al principio de cada script para apuntar a otra ruta). Abre
|
||||
`graph_view.html` en el navegador (o sírvelo con `python3 -m http.server`).
|
||||
|
||||
## Visualizador
|
||||
|
||||
- **Zoom / pan**: rueda del ratón y arrastre sobre el fondo.
|
||||
- **Arrastrar un nodo**: lo fija en esa posición.
|
||||
- **Buscador**: resalta notas por nombre.
|
||||
- **Panel "Fuerzas del layout"**: controles en vivo para ajustar la simulación —
|
||||
separación vertical, repulsión entre notas, atracción a journals, cohesión entre notas
|
||||
relacionadas, distancia a journal y margen anticolisión. Botones para reorganizar o
|
||||
restaurar los valores por defecto.
|
||||
|
||||
## Privacidad
|
||||
|
||||
`graph_data.json` y `graph_view.html` son artefactos generados que contienen el
|
||||
contenido real de tu grafo (nombres de páginas, fechas, títulos de notas) y están
|
||||
excluidos vía `.gitignore` — nunca se commitean. Solo el código generador se versiona.
|
||||
|
||||
## Requisitos
|
||||
|
||||
- Python 3 (sin dependencias externas).
|
||||
- Un navegador moderno para abrir el HTML resultante.
|
||||
|
||||
D3.js (`vendor/d3.min.js`, v7.9.0) está vendorizado bajo su licencia ISC —
|
||||
ver [d3js.org](https://d3js.org/).
|
||||
+549
@@ -0,0 +1,549 @@
|
||||
#!/usr/bin/env python3
|
||||
import json, sys, html
|
||||
|
||||
DATA_PATH = "graph_data.json"
|
||||
D3_PATH = "vendor/d3.min.js"
|
||||
OUT_PATH = "graph_view.html"
|
||||
|
||||
with open(DATA_PATH, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
with open(D3_PATH, encoding="utf-8") as f:
|
||||
d3_src = f.read()
|
||||
|
||||
data_json = json.dumps(data, ensure_ascii=False)
|
||||
|
||||
TEMPLATE = """<!doctype html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Linea temporal del grafo</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0b0d12;
|
||||
--line: #3a4050;
|
||||
--journal: #6c7688;
|
||||
--journal-active: #ffd166;
|
||||
--page: #4fb0ff;
|
||||
--page-dim: #2a3a4a;
|
||||
--edge: rgba(120,140,170,0.18);
|
||||
--edge-active: rgba(255,209,102,0.85);
|
||||
--text: #e8ecf3;
|
||||
--text-dim: #8993a6;
|
||||
--panel-bg: rgba(15,18,26,0.92);
|
||||
--accent: #ff6b6b;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin:0; padding:0; width:100%; height:100%; background:var(--bg); color:var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; overflow:hidden; }
|
||||
svg { width:100%; height:100%; display:block; cursor:grab; }
|
||||
svg:active { cursor:grabbing; }
|
||||
|
||||
.hud {
|
||||
position:fixed; top:12px; left:12px; z-index:10;
|
||||
background:var(--panel-bg); border:1px solid #262c3a; border-radius:10px;
|
||||
padding:12px 14px; max-width:340px; backdrop-filter: blur(6px);
|
||||
}
|
||||
.hud h1 { font-size:14px; margin:0 0 6px; font-weight:600; letter-spacing:.2px; }
|
||||
.hud .stats { font-size:11px; color:var(--text-dim); margin-bottom:10px; }
|
||||
.hud input[type=text] {
|
||||
width:100%; background:#141824; border:1px solid #2a3040; border-radius:6px;
|
||||
color:var(--text); padding:6px 8px; font-size:12px; outline:none;
|
||||
}
|
||||
.hud input[type=text]:focus { border-color:var(--page); }
|
||||
.hud .row { display:flex; gap:8px; align-items:center; margin-top:8px; font-size:11px; color:var(--text-dim); }
|
||||
.hud .row label { display:flex; gap:5px; align-items:center; cursor:pointer; }
|
||||
.hud button {
|
||||
background:#1a2030; border:1px solid #2a3040; color:var(--text-dim); font-size:11px;
|
||||
padding:4px 8px; border-radius:6px; cursor:pointer; margin-top:8px;
|
||||
}
|
||||
.hud button:hover { color:var(--text); border-color:var(--page); }
|
||||
|
||||
.hud .controls { margin-top:10px; border-top:1px solid #232838; padding-top:8px; }
|
||||
.hud .ctrl { margin-top:8px; }
|
||||
.hud .ctrl-label { display:flex; justify-content:space-between; font-size:11px; color:var(--text-dim); margin-bottom:3px; }
|
||||
.hud .ctrl-label span.val { color:var(--text); font-variant-numeric:tabular-nums; }
|
||||
.hud input[type=range] {
|
||||
width:100%; -webkit-appearance:none; appearance:none; height:4px; border-radius:2px;
|
||||
background:#232838; outline:none;
|
||||
}
|
||||
.hud input[type=range]::-webkit-slider-thumb {
|
||||
-webkit-appearance:none; appearance:none; width:12px; height:12px; border-radius:50%;
|
||||
background:var(--page); cursor:pointer; border:2px solid #0b0d12;
|
||||
}
|
||||
.hud input[type=range]::-moz-range-thumb {
|
||||
width:12px; height:12px; border-radius:50%; background:var(--page); cursor:pointer; border:2px solid #0b0d12;
|
||||
}
|
||||
.hud .ctrl-buttons { display:flex; gap:8px; }
|
||||
.hud .ctrl-buttons button { flex:1; margin-top:8px; }
|
||||
.hud summary { cursor:pointer; font-size:12px; color:var(--text-dim); user-select:none; }
|
||||
.hud summary:hover { color:var(--text); }
|
||||
|
||||
.tooltip {
|
||||
position:fixed; pointer-events:none; z-index:20;
|
||||
background:var(--panel-bg); border:1px solid #2a3040; border-radius:8px;
|
||||
padding:8px 10px; font-size:12px; max-width:280px; display:none;
|
||||
box-shadow:0 6px 24px rgba(0,0,0,0.5);
|
||||
}
|
||||
.tooltip .t-name { font-weight:600; margin-bottom:2px; }
|
||||
.tooltip .t-meta { color:var(--text-dim); font-size:11px; }
|
||||
|
||||
.legend {
|
||||
position:fixed; bottom:12px; left:12px; z-index:10; font-size:11px; color:var(--text-dim);
|
||||
background:var(--panel-bg); border:1px solid #262c3a; border-radius:10px; padding:10px 12px;
|
||||
display:flex; gap:16px; align-items:center;
|
||||
}
|
||||
.legend .dot { display:inline-block; width:9px; height:9px; border-radius:50%; margin-right:5px; vertical-align:middle; }
|
||||
|
||||
.node-label { fill: var(--text-dim); font-size:10px; pointer-events:none; user-select:none; }
|
||||
.journal-label { fill: var(--text-dim); font-size:9px; pointer-events:none; user-select:none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="hud">
|
||||
<h1>Linea temporal del grafo — ~/Notas</h1>
|
||||
<div class="stats" id="stats"></div>
|
||||
<input type="text" id="search" placeholder="Buscar nota por nombre...">
|
||||
<div class="row">
|
||||
<label><input type="checkbox" id="toggle-labels" checked> Etiquetas de notas</label>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label><input type="checkbox" id="toggle-jlabels"> Fechas de journals</label>
|
||||
</div>
|
||||
<button id="reset-view">Reset vista</button>
|
||||
|
||||
<details class="controls" open>
|
||||
<summary>Fuerzas del layout</summary>
|
||||
|
||||
<div class="ctrl">
|
||||
<div class="ctrl-label"><span>Separación vertical</span><span class="val" id="val-spread"></span></div>
|
||||
<input type="range" id="ctl-spread" min="150" max="1600" step="10">
|
||||
</div>
|
||||
<div class="ctrl">
|
||||
<div class="ctrl-label"><span>Repulsión entre notas</span><span class="val" id="val-charge"></span></div>
|
||||
<input type="range" id="ctl-charge" min="0" max="500" step="5">
|
||||
</div>
|
||||
<div class="ctrl">
|
||||
<div class="ctrl-label"><span>Atracción a journals</span><span class="val" id="val-jstrength"></span></div>
|
||||
<input type="range" id="ctl-jstrength" min="5" max="200" step="5">
|
||||
</div>
|
||||
<div class="ctrl">
|
||||
<div class="ctrl-label"><span>Cohesión entre notas relacionadas</span><span class="val" id="val-pstrength"></span></div>
|
||||
<input type="range" id="ctl-pstrength" min="0" max="100" step="2">
|
||||
</div>
|
||||
<div class="ctrl">
|
||||
<div class="ctrl-label"><span>Distancia a journal</span><span class="val" id="val-jdist"></span></div>
|
||||
<input type="range" id="ctl-jdist" min="20" max="250" step="5">
|
||||
</div>
|
||||
<div class="ctrl">
|
||||
<div class="ctrl-label"><span>Margen anticolisión</span><span class="val" id="val-collide"></span></div>
|
||||
<input type="range" id="ctl-collide" min="0" max="30" step="1">
|
||||
</div>
|
||||
<div class="ctrl-buttons">
|
||||
<button id="reheat">Reorganizar</button>
|
||||
<button id="reset-forces">Restaurar</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div class="legend">
|
||||
<span><span class="dot" style="background:var(--journal)"></span>Journal</span>
|
||||
<span><span class="dot" style="background:var(--page)"></span>Nota</span>
|
||||
<span>Tamaño = num. de enlaces · Rueda = zoom · Arrastra = pan · Arrastra un nodo = fijarlo</span>
|
||||
</div>
|
||||
|
||||
<div class="tooltip" id="tooltip"></div>
|
||||
|
||||
<svg id="svg"></svg>
|
||||
|
||||
<script>__D3_SOURCE__</script>
|
||||
<script>
|
||||
const GRAPH = __DATA_JSON__;
|
||||
|
||||
const journals = GRAPH.journals.slice().sort((a,b) => a.date.localeCompare(b.date));
|
||||
const pages = GRAPH.pages;
|
||||
const edges = GRAPH.edges;
|
||||
|
||||
document.getElementById('stats').textContent =
|
||||
`${journals.length} journals · ${pages.length} notas · ${edges.length} enlaces`;
|
||||
|
||||
// ---- Layout constants ----
|
||||
const JOURNAL_SPACING = 46; // px between consecutive journals (uniform, order-based)
|
||||
const MARGIN_X = 200;
|
||||
const LINE_Y = 1500; // baseline y for the journal line (lots of room above for vertical spread)
|
||||
const TOP_MARGIN = 30; // notes must stay at least this far from the top edge
|
||||
const width = MARGIN_X * 2 + (journals.length - 1) * JOURNAL_SPACING;
|
||||
const height = LINE_Y + 120;
|
||||
|
||||
const journalById = new Map();
|
||||
journals.forEach((j, i) => {
|
||||
j.x = MARGIN_X + i * JOURNAL_SPACING;
|
||||
j.y = LINE_Y;
|
||||
j.fx = j.x;
|
||||
j.fy = j.y;
|
||||
journalById.set(j.id, j);
|
||||
});
|
||||
|
||||
const degMaxEarly = Math.max(1, ...pages.map(p => p.degree));
|
||||
const pageById = new Map();
|
||||
pages.forEach((p, i) => {
|
||||
// seed position near the horizontal middle, spread out, above the line;
|
||||
// give each note a stable per-node jitter so the vertical spread reads as organic, not banded
|
||||
p.jitter = (Math.random() - 0.5) * 2;
|
||||
const norm = 1 - p.degree / degMaxEarly; // 0 = very connected (near line), 1 = barely connected (far)
|
||||
p.x = MARGIN_X + (journals.length / 2) * JOURNAL_SPACING + (Math.random() - 0.5) * 200;
|
||||
p.y = LINE_Y - 80 - norm * 500 - Math.random() * 150;
|
||||
pageById.set(p.id, p);
|
||||
});
|
||||
|
||||
const nodeById = new Map([...journalById, ...pageById]);
|
||||
|
||||
const degMax = Math.max(1, ...pages.map(p => p.degree));
|
||||
const radiusScale = d3.scaleSqrt().domain([0, degMax]).range([2.5, 22]);
|
||||
const journalDegMax = Math.max(1, ...journals.map(j => j.degree));
|
||||
const journalRadiusScale = d3.scaleSqrt().domain([0, journalDegMax]).range([3, 9]);
|
||||
|
||||
const linkData = edges.map(e => ({
|
||||
source: e.source, target: e.target, kind: e.kind
|
||||
})).filter(e => nodeById.has(e.source) && nodeById.has(e.target));
|
||||
|
||||
// ---- SVG setup ----
|
||||
const svg = d3.select('#svg');
|
||||
const root = svg.append('g');
|
||||
|
||||
const zoom = d3.zoom()
|
||||
.scaleExtent([0.05, 8])
|
||||
.on('zoom', (event) => root.attr('transform', event.transform));
|
||||
svg.call(zoom);
|
||||
|
||||
// initial view: fit the note cloud's width, anchor the baseline near the bottom of the viewport
|
||||
// so the vertical spread above it is visible. Coordinates are raw SVG pixels (no viewBox scaling).
|
||||
const initialScale = Math.min(1, (window.innerWidth - 60) / width);
|
||||
const initialTransform = () => d3.zoomIdentity
|
||||
.translate(20, window.innerHeight - 80)
|
||||
.scale(Math.max(initialScale, 0.06))
|
||||
.translate(0, -LINE_Y);
|
||||
|
||||
svg.call(zoom.transform, initialTransform());
|
||||
|
||||
document.getElementById('reset-view').addEventListener('click', () => {
|
||||
svg.transition().duration(400).call(zoom.transform, initialTransform());
|
||||
});
|
||||
|
||||
// ---- Baseline ----
|
||||
root.append('line')
|
||||
.attr('x1', journals[0].x).attr('y1', LINE_Y)
|
||||
.attr('x2', journals[journals.length - 1].x).attr('y2', LINE_Y)
|
||||
.attr('stroke', 'var(--line)').attr('stroke-width', 2);
|
||||
|
||||
// year/month tick marks along the line (based on order, labeled with real date of first journal in run)
|
||||
let lastLabel = null;
|
||||
journals.forEach(j => {
|
||||
const label = j.date.slice(0, 7); // yyyy-mm
|
||||
if (label !== lastLabel) {
|
||||
lastLabel = label;
|
||||
root.append('text')
|
||||
.attr('x', j.x).attr('y', LINE_Y + 22)
|
||||
.attr('text-anchor', 'middle')
|
||||
.attr('class', 'journal-label')
|
||||
.style('display', 'none')
|
||||
.attr('data-monthmark', '1')
|
||||
.text(label);
|
||||
root.append('line')
|
||||
.attr('x1', j.x).attr('x2', j.x)
|
||||
.attr('y1', LINE_Y - 4).attr('y2', LINE_Y + 4)
|
||||
.attr('stroke', '#556').attr('stroke-width', 1)
|
||||
.attr('data-monthtick', '1');
|
||||
}
|
||||
});
|
||||
|
||||
// ---- Edges ----
|
||||
const linkSel = root.append('g').attr('stroke-linecap', 'round')
|
||||
.selectAll('line')
|
||||
.data(linkData)
|
||||
.join('line')
|
||||
.attr('stroke', 'var(--edge)')
|
||||
.attr('stroke-width', 1);
|
||||
|
||||
// ---- Journal nodes ----
|
||||
const journalSel = root.append('g')
|
||||
.selectAll('circle.journal')
|
||||
.data(journals)
|
||||
.join('circle')
|
||||
.attr('class', 'journal')
|
||||
.attr('r', j => journalRadiusScale(j.degree))
|
||||
.attr('fill', 'var(--journal)')
|
||||
.attr('cx', j => j.x).attr('cy', j => j.y)
|
||||
.style('cursor', 'pointer')
|
||||
.on('mouseenter', (event, d) => showTooltip(event, d, true))
|
||||
.on('mousemove', moveTooltip)
|
||||
.on('mouseleave', hideTooltip)
|
||||
.on('click', (event, d) => focusNode(d));
|
||||
|
||||
const journalLabelSel = root.append('g')
|
||||
.selectAll('text.jlabel')
|
||||
.data(journals)
|
||||
.join('text')
|
||||
.attr('class', 'journal-label jlabel')
|
||||
.attr('x', j => j.x).attr('y', j => j.y + 26)
|
||||
.attr('text-anchor', 'middle')
|
||||
.style('display', 'none')
|
||||
.text(j => j.date);
|
||||
|
||||
// ---- Page (note) nodes ----
|
||||
const pageSel = root.append('g')
|
||||
.selectAll('circle.page')
|
||||
.data(pages)
|
||||
.join('circle')
|
||||
.attr('class', 'page')
|
||||
.attr('r', p => radiusScale(p.degree))
|
||||
.attr('fill', 'var(--page)')
|
||||
.attr('fill-opacity', 0.85)
|
||||
.style('cursor', 'pointer')
|
||||
.call(drag());
|
||||
|
||||
const pageLabelSel = root.append('g')
|
||||
.selectAll('text.plabel')
|
||||
.data(pages)
|
||||
.join('text')
|
||||
.attr('class', 'node-label plabel')
|
||||
.attr('text-anchor', 'middle')
|
||||
.attr('dy', p => -(radiusScale(p.degree) + 4))
|
||||
.text(p => p.name);
|
||||
|
||||
pageSel
|
||||
.on('mouseenter', (event, d) => showTooltip(event, d, false))
|
||||
.on('mousemove', moveTooltip)
|
||||
.on('mouseleave', hideTooltip)
|
||||
.on('click', (event, d) => focusNode(d));
|
||||
|
||||
// ---- Force simulation ----
|
||||
const degMax2 = degMaxEarly;
|
||||
|
||||
const DEFAULT_PARAMS = {
|
||||
spread: 500, // vertical spread range for notes, by degree (px above the "close to line" offset)
|
||||
charge: 60, // base repulsion magnitude between notes
|
||||
jstrength: 90, // attraction strength to linked journals (x100 of forceLink strength, for a nicer slider range)
|
||||
pstrength: 15, // cohesion strength between related notes (x100 of forceLink strength)
|
||||
jdist: 70, // rest distance to linked journal
|
||||
collide: 3 // extra padding added to collision radius
|
||||
};
|
||||
const params = Object.assign({}, DEFAULT_PARAMS);
|
||||
|
||||
const linkForce = d3.forceLink(linkData)
|
||||
.id(d => d.id)
|
||||
.distance(d => {
|
||||
if (d.kind === 'journal-link' || d.kind === 'journal-tag') return params.jdist;
|
||||
return params.jdist + 20;
|
||||
})
|
||||
.strength(d => {
|
||||
if (d.kind === 'journal-link' || d.kind === 'journal-tag') return params.jstrength / 100;
|
||||
return params.pstrength / 100;
|
||||
});
|
||||
|
||||
const chargeForce = d3.forceManyBody()
|
||||
.strength(d => d.date ? 0 : -(params.charge + radiusScale(d.degree) * 4));
|
||||
|
||||
const collideForce = d3.forceCollide()
|
||||
.radius(d => (d.date ? journalRadiusScale(d.degree) : radiusScale(d.degree)) + params.collide)
|
||||
.iterations(2);
|
||||
|
||||
// The vertical spread slider controls both how far weakly-linked notes drift from the line
|
||||
// AND how strongly they're pulled there, since forceLink pulls in straight-line (x+y) distance
|
||||
// and would otherwise overpower a fixed, weak y-force and flatten everything back near the line.
|
||||
function ySpreadStrength() { return 0.03 + (params.spread / 1600) * 0.5; }
|
||||
|
||||
const yForce = d3.forceY(d => {
|
||||
if (d.date) return LINE_Y;
|
||||
const norm = 1 - d.degree / degMax2; // 0 = very connected, 1 = barely connected
|
||||
return LINE_Y - 80 - norm * params.spread + d.jitter * 30;
|
||||
}).strength(d => d.date ? 1 : ySpreadStrength());
|
||||
|
||||
const xForce = d3.forceX(d => d.x).strength(d => d.date ? 1 : 0.01);
|
||||
|
||||
const simulation = d3.forceSimulation([...journals, ...pages])
|
||||
.force('link', linkForce)
|
||||
.force('charge', chargeForce)
|
||||
.force('collide', collideForce)
|
||||
.force('y', yForce)
|
||||
.force('x', xForce)
|
||||
.alpha(1)
|
||||
.alphaDecay(0.02)
|
||||
.on('tick', ticked);
|
||||
|
||||
// re-apply every force's accessor so d3 recomputes its cached per-node values from the current `params`
|
||||
function applyForces() {
|
||||
linkForce
|
||||
.distance(d => (d.kind === 'journal-link' || d.kind === 'journal-tag') ? params.jdist : params.jdist + 20)
|
||||
.strength(d => (d.kind === 'journal-link' || d.kind === 'journal-tag') ? params.jstrength / 100 : params.pstrength / 100);
|
||||
chargeForce.strength(d => d.date ? 0 : -(params.charge + radiusScale(d.degree) * 4));
|
||||
collideForce.radius(d => (d.date ? journalRadiusScale(d.degree) : radiusScale(d.degree)) + params.collide);
|
||||
yForce
|
||||
.y(d => {
|
||||
if (d.date) return LINE_Y;
|
||||
const norm = 1 - d.degree / degMax2;
|
||||
return LINE_Y - 80 - norm * params.spread + d.jitter * 30;
|
||||
})
|
||||
.strength(d => d.date ? 1 : ySpreadStrength());
|
||||
simulation.alpha(0.6).restart();
|
||||
}
|
||||
|
||||
function ticked() {
|
||||
pages.forEach(p => {
|
||||
const r = radiusScale(p.degree);
|
||||
if (p.y > LINE_Y - TOP_MARGIN / 3) p.y = LINE_Y - TOP_MARGIN / 3; // keep above the line
|
||||
if (p.y < r + TOP_MARGIN) p.y = r + TOP_MARGIN;
|
||||
});
|
||||
|
||||
linkSel
|
||||
.attr('x1', d => d.source.x).attr('y1', d => d.source.y)
|
||||
.attr('x2', d => d.target.x).attr('y2', d => d.target.y);
|
||||
|
||||
journalSel.attr('cx', d => d.x).attr('cy', d => d.y);
|
||||
journalLabelSel.attr('x', d => d.x).attr('y', d => d.y + 26);
|
||||
|
||||
pageSel.attr('cx', d => d.x).attr('cy', d => d.y);
|
||||
pageLabelSel.attr('x', d => d.x).attr('y', d => d.y);
|
||||
}
|
||||
|
||||
function drag() {
|
||||
function dragstarted(event, d) {
|
||||
if (!event.active) simulation.alphaTarget(0.1).restart();
|
||||
d.fx = d.x; d.fy = d.y;
|
||||
}
|
||||
function dragged(event, d) {
|
||||
d.fx = event.x; d.fy = event.y;
|
||||
}
|
||||
function dragended(event, d) {
|
||||
if (!event.active) simulation.alphaTarget(0);
|
||||
// keep it pinned where the user left it
|
||||
}
|
||||
return d3.drag().on('start', dragstarted).on('drag', dragged).on('end', dragended);
|
||||
}
|
||||
|
||||
// ---- Tooltip ----
|
||||
const tooltip = document.getElementById('tooltip');
|
||||
function showTooltip(event, d, isJournal) {
|
||||
tooltip.style.display = 'block';
|
||||
if (isJournal) {
|
||||
tooltip.innerHTML = `<div class="t-name">${d.date}</div><div class="t-meta">${d.degree} enlaces · ${d.file}</div>`;
|
||||
} else {
|
||||
tooltip.innerHTML = `<div class="t-name">${escapeHtml(d.name)}</div><div class="t-meta">${d.degree} enlaces · ${d.file}</div>`;
|
||||
}
|
||||
moveTooltip(event);
|
||||
highlightConnections(d.id);
|
||||
}
|
||||
function moveTooltip(event) {
|
||||
tooltip.style.left = (event.clientX + 16) + 'px';
|
||||
tooltip.style.top = (event.clientY + 12) + 'px';
|
||||
}
|
||||
function hideTooltip() {
|
||||
tooltip.style.display = 'none';
|
||||
clearHighlight();
|
||||
}
|
||||
function escapeHtml(s) {
|
||||
return s.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
}
|
||||
|
||||
const neighborIndex = new Map();
|
||||
linkData.forEach(e => {
|
||||
const s = typeof e.source === 'object' ? e.source.id : e.source;
|
||||
const t = typeof e.target === 'object' ? e.target.id : e.target;
|
||||
if (!neighborIndex.has(s)) neighborIndex.set(s, new Set());
|
||||
if (!neighborIndex.has(t)) neighborIndex.set(t, new Set());
|
||||
neighborIndex.get(s).add(t);
|
||||
neighborIndex.get(t).add(s);
|
||||
});
|
||||
|
||||
function highlightConnections(nodeId) {
|
||||
const neigh = neighborIndex.get(nodeId) || new Set();
|
||||
linkSel.attr('stroke', d => {
|
||||
const s = d.source.id, t = d.target.id;
|
||||
return (s === nodeId || t === nodeId) ? 'var(--edge-active)' : 'var(--edge)';
|
||||
}).attr('stroke-width', d => (d.source.id === nodeId || d.target.id === nodeId) ? 2 : 1);
|
||||
|
||||
pageSel.attr('fill-opacity', p => (p.id === nodeId || neigh.has(p.id)) ? 1 : 0.15);
|
||||
journalSel.attr('fill', j => (j.id === nodeId || neigh.has(j.id)) ? 'var(--journal-active)' : 'var(--journal)');
|
||||
}
|
||||
function clearHighlight() {
|
||||
linkSel.attr('stroke', 'var(--edge)').attr('stroke-width', 1);
|
||||
pageSel.attr('fill-opacity', 0.85);
|
||||
journalSel.attr('fill', 'var(--journal)');
|
||||
}
|
||||
|
||||
function focusNode(d) {
|
||||
const scale = 2.2;
|
||||
const transform = d3.zoomIdentity
|
||||
.translate(window.innerWidth / 2 - d.x * scale, window.innerHeight / 2 - d.y * scale)
|
||||
.scale(scale);
|
||||
svg.transition().duration(500).call(zoom.transform, transform);
|
||||
}
|
||||
|
||||
// ---- Search ----
|
||||
const searchInput = document.getElementById('search');
|
||||
searchInput.addEventListener('input', () => {
|
||||
const q = searchInput.value.trim().toLowerCase();
|
||||
if (!q) { clearHighlight(); return; }
|
||||
const matches = pages.filter(p => p.name.toLowerCase().includes(q));
|
||||
pageSel.attr('fill-opacity', p => matches.includes(p) ? 1 : 0.08);
|
||||
pageSel.attr('fill', p => matches.includes(p) ? 'var(--accent)' : 'var(--page)');
|
||||
if (matches.length === 1) focusNode(matches[0]);
|
||||
});
|
||||
searchInput.addEventListener('blur', () => {
|
||||
if (!searchInput.value.trim()) {
|
||||
pageSel.attr('fill', 'var(--page)');
|
||||
}
|
||||
});
|
||||
|
||||
// ---- Toggles ----
|
||||
document.getElementById('toggle-labels').addEventListener('change', (e) => {
|
||||
pageLabelSel.style('display', e.target.checked ? null : 'none');
|
||||
});
|
||||
document.getElementById('toggle-jlabels').addEventListener('change', (e) => {
|
||||
journalLabelSel.style('display', e.target.checked ? null : 'none');
|
||||
root.selectAll('[data-monthmark]').style('display', e.target.checked ? null : 'none');
|
||||
});
|
||||
|
||||
// ---- Force controls ----
|
||||
const SLIDER_IDS = {
|
||||
spread: 'ctl-spread', charge: 'ctl-charge', jstrength: 'ctl-jstrength',
|
||||
pstrength: 'ctl-pstrength', jdist: 'ctl-jdist', collide: 'ctl-collide'
|
||||
};
|
||||
function syncSlidersFromParams() {
|
||||
Object.keys(SLIDER_IDS).forEach(key => {
|
||||
document.getElementById(SLIDER_IDS[key]).value = params[key];
|
||||
document.getElementById('val-' + key).textContent = params[key];
|
||||
});
|
||||
}
|
||||
Object.keys(SLIDER_IDS).forEach(key => {
|
||||
const input = document.getElementById(SLIDER_IDS[key]);
|
||||
input.addEventListener('input', () => {
|
||||
params[key] = +input.value;
|
||||
document.getElementById('val-' + key).textContent = params[key];
|
||||
applyForces();
|
||||
});
|
||||
});
|
||||
syncSlidersFromParams();
|
||||
|
||||
document.getElementById('reheat').addEventListener('click', () => {
|
||||
simulation.alpha(1).restart();
|
||||
});
|
||||
document.getElementById('reset-forces').addEventListener('click', () => {
|
||||
Object.assign(params, DEFAULT_PARAMS);
|
||||
syncSlidersFromParams();
|
||||
applyForces();
|
||||
});
|
||||
|
||||
// hide dense page labels by default zoom-based (optional simple heuristic): nothing extra needed now.
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
html_out = TEMPLATE.replace("__D3_SOURCE__", d3_src).replace("__DATA_JSON__", data_json)
|
||||
|
||||
with open(OUT_PATH, "w", encoding="utf-8") as f:
|
||||
f.write(html_out)
|
||||
|
||||
print("wrote", OUT_PATH, len(html_out), "bytes")
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
import os, re, json, datetime, sys
|
||||
|
||||
NOTAS = os.path.expanduser("~/Notas")
|
||||
JOURNALS_DIR = os.path.join(NOTAS, "journals")
|
||||
PAGES_DIR = os.path.join(NOTAS, "pages")
|
||||
|
||||
MONTHS = {m: i+1 for i, m in enumerate(
|
||||
["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"])}
|
||||
|
||||
LINK_RE = re.compile(r"\[\[([^\[\]]+)\]\]")
|
||||
JOURNAL_LINK_RE = re.compile(
|
||||
r"^([A-Za-z]{3,9}) (\d{1,2})(?:st|nd|rd|th), (\d{4})$")
|
||||
TAG_RE = re.compile(r"(?<!\S)#([A-Za-z0-9_/\-]+)")
|
||||
|
||||
def journal_filename_to_date(fname):
|
||||
# yyyy_MM_dd.md
|
||||
m = re.match(r"(\d{4})_(\d{2})_(\d{2})\.md$", fname)
|
||||
if not m:
|
||||
return None
|
||||
y, mo, d = map(int, m.groups())
|
||||
try:
|
||||
return datetime.date(y, mo, d)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def journal_link_to_date(text):
|
||||
m = JOURNAL_LINK_RE.match(text.strip())
|
||||
if not m:
|
||||
return None
|
||||
mon, day, year = m.groups()
|
||||
mon3 = mon[:3]
|
||||
if mon3 not in MONTHS:
|
||||
return None
|
||||
try:
|
||||
return datetime.date(int(year), MONTHS[mon3], int(day))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def strip_code_blocks(text):
|
||||
# remove fenced code blocks to avoid false-positive links inside code
|
||||
text = re.sub(r"```.*?```", "", text, flags=re.S)
|
||||
text = re.sub(r"`[^`]*`", "", text)
|
||||
return text
|
||||
|
||||
def extract_links(text):
|
||||
text = strip_code_blocks(text)
|
||||
links = LINK_RE.findall(text)
|
||||
tags = TAG_RE.findall(text)
|
||||
return links, tags
|
||||
|
||||
# ---- Journals ----
|
||||
journal_by_date = {} # date -> node id
|
||||
journals = [] # list of {id, date}
|
||||
|
||||
for fname in sorted(os.listdir(JOURNALS_DIR)):
|
||||
if not fname.endswith(".md"):
|
||||
continue
|
||||
date = journal_filename_to_date(fname)
|
||||
if date is None:
|
||||
continue
|
||||
node_id = f"journal:{date.isoformat()}"
|
||||
journal_by_date[date] = node_id
|
||||
path = os.path.join(JOURNALS_DIR, fname)
|
||||
with open(path, encoding="utf-8", errors="ignore") as f:
|
||||
text = f.read()
|
||||
links, tags = extract_links(text)
|
||||
journals.append({
|
||||
"id": node_id,
|
||||
"date": date.isoformat(),
|
||||
"raw_links": links,
|
||||
"raw_tags": tags,
|
||||
"file": fname,
|
||||
})
|
||||
|
||||
journals.sort(key=lambda j: j["date"])
|
||||
|
||||
# ---- Pages ----
|
||||
pages = []
|
||||
page_name_set = set()
|
||||
|
||||
for fname in sorted(os.listdir(PAGES_DIR)):
|
||||
if not fname.endswith(".md"):
|
||||
continue
|
||||
name = fname[:-3]
|
||||
# logseq encodes some path separators; leave as-is, decode %2F etc if present
|
||||
name = name.replace("%2F", "/").replace("___", "/")
|
||||
page_name_set.add(name)
|
||||
|
||||
for fname in sorted(os.listdir(PAGES_DIR)):
|
||||
if not fname.endswith(".md"):
|
||||
continue
|
||||
name = fname[:-3].replace("%2F", "/").replace("___", "/")
|
||||
path = os.path.join(PAGES_DIR, fname)
|
||||
with open(path, encoding="utf-8", errors="ignore") as f:
|
||||
text = f.read()
|
||||
links, tags = extract_links(text)
|
||||
pages.append({
|
||||
"id": f"page:{name}",
|
||||
"name": name,
|
||||
"raw_links": links,
|
||||
"raw_tags": tags,
|
||||
"file": fname,
|
||||
})
|
||||
|
||||
page_ids_by_name = {p["name"]: p["id"] for p in pages}
|
||||
|
||||
# ---- Build edges ----
|
||||
# journal -> page (journal content links to a page)
|
||||
# journal -> journal (rare, via date link)
|
||||
# page -> journal (page links to a specific journal date, e.g. source:: [[Apr 27th, 2026]])
|
||||
# page -> page
|
||||
|
||||
edges = [] # {source, target, kind}
|
||||
edge_seen = set()
|
||||
|
||||
def add_edge(src, tgt, kind):
|
||||
if src == tgt:
|
||||
return
|
||||
key = (src, tgt)
|
||||
if key in edge_seen:
|
||||
return
|
||||
edge_seen.add(key)
|
||||
edges.append({"source": src, "target": tgt, "kind": kind})
|
||||
|
||||
def resolve_link(raw):
|
||||
raw = raw.strip()
|
||||
# could be a block ref ((uuid)) - skip
|
||||
if raw.startswith("(("):
|
||||
return None
|
||||
# strip block/alias parts after '::' or '|' just in case
|
||||
date = journal_link_to_date(raw)
|
||||
if date is not None:
|
||||
return journal_by_date.get(date)
|
||||
return page_ids_by_name.get(raw)
|
||||
|
||||
for j in journals:
|
||||
for raw in j["raw_links"]:
|
||||
tgt = resolve_link(raw)
|
||||
if tgt:
|
||||
add_edge(j["id"], tgt, "journal-link")
|
||||
for tag in j["raw_tags"]:
|
||||
tgt = page_ids_by_name.get(tag)
|
||||
if tgt:
|
||||
add_edge(j["id"], tgt, "journal-tag")
|
||||
|
||||
for p in pages:
|
||||
for raw in p["raw_links"]:
|
||||
tgt = resolve_link(raw)
|
||||
if tgt:
|
||||
add_edge(p["id"], tgt, "page-link")
|
||||
for tag in p["raw_tags"]:
|
||||
tgt = page_ids_by_name.get(tag)
|
||||
if tgt:
|
||||
add_edge(p["id"], tgt, "page-tag")
|
||||
|
||||
# ---- Degree counts ----
|
||||
degree = {}
|
||||
for e in edges:
|
||||
degree[e["source"]] = degree.get(e["source"], 0) + 1
|
||||
degree[e["target"]] = degree.get(e["target"], 0) + 1
|
||||
|
||||
out_journals = [{
|
||||
"id": j["id"], "date": j["date"], "file": j["file"],
|
||||
"degree": degree.get(j["id"], 0),
|
||||
} for j in journals]
|
||||
|
||||
out_pages = [{
|
||||
"id": p["id"], "name": p["name"], "file": p["file"],
|
||||
"degree": degree.get(p["id"], 0),
|
||||
} for p in pages if degree.get(p["id"], 0) > 0] # only pages that connect to something
|
||||
|
||||
# keep pages with 0 degree too? Include them but they'll float unattached.
|
||||
out_pages_all = [{
|
||||
"id": p["id"], "name": p["name"], "file": p["file"],
|
||||
"degree": degree.get(p["id"], 0),
|
||||
} for p in pages]
|
||||
|
||||
out_edges = [e for e in edges]
|
||||
|
||||
result = {
|
||||
"journals": out_journals,
|
||||
"pages": out_pages_all,
|
||||
"edges": out_edges,
|
||||
"stats": {
|
||||
"n_journals": len(out_journals),
|
||||
"n_pages": len(out_pages_all),
|
||||
"n_pages_connected": len(out_pages),
|
||||
"n_edges": len(out_edges),
|
||||
}
|
||||
}
|
||||
|
||||
outpath = sys.argv[1] if len(sys.argv) > 1 else "graph_data.json"
|
||||
with open(outpath, "w", encoding="utf-8") as f:
|
||||
json.dump(result, f, ensure_ascii=False, indent=1)
|
||||
|
||||
print(json.dumps(result["stats"], indent=2))
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
// https://d3js.org v7.9.0 Copyright 2010-2023 Mike Bostock
|
||||
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).d3=t.d3||{})}(this,(function(t){"use strict";function n(t,n){return null==t||null==n?NaN:t<n?-1:t>n?1:t>=n?0:NaN}function e(t,n){return null==t||null==n?NaN:n<t?-1:n>t?1:n>=t?0:NaN}function r(t){let r,o,a;function u(t,n,e=0,i=t.length){if(e<i){if(0!==r(n,n))return i;do{const r=e+i>>>1;o(t[r],n)<0?e=r+1:i=r}while(e<i)}return e}return 2!==t.length?(r=n,o=(e,r)=>n(t(e),r),a=(n,e)=>t(n)-e):(r=t===n||t===e?t:i,o=t,a=t),{left:u,center:function(t,n,e=0,r=t.length){const i=u(t,n,e,r-1);return i>e&&a(t[i-1],n)>-a(t[i],n)?i-1:i},right:function(t,n,e=0,i=t.length){if(e<i){if(0!==r(n,n))return i;do{const r=e+i>>>1;o(t[r],n)<=0?e=r+1:i=r}while(e<i)}return e}}}function i(){return 0}function o(t){return null===t?NaN:+t}const a=r(n),u=a.right,c=a.left,f=r(o).center;var s=u;const l=d(y),h=d((function(t){const n=y(t);return(t,e,r,i,o)=>{n(t,e,(r<<=2)+0,(i<<=2)+0,o<<=2),n(t,e,r+1,i+1,o),n(t,e,r+2,i+2,o),n(t,e,r+3,i+3,o)}}));function d(t){return function(n,e,r=e){if(!((e=+e)>=0))throw new RangeError("invalid rx");if(!((r=+r)>=0))throw new RangeError("invalid ry");let{data:i,width:o,height:a}=n;if(!((o=Math.floor(o))>=0))throw new RangeError("invalid width");if(!((a=Math.floor(void 0!==a?a:i.length/o))>=0))throw new RangeError("invalid height");if(!o||!a||!e&&!r)return n;const u=e&&t(e),c=r&&t(r),f=i.slice();return u&&c?(p(u,f,i,o,a),p(u,i,f,o,a),p(u,f,i,o,a),g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)):u?(p(u,i,f,o,a),p(u,f,i,o,a),p(u,i,f,o,a)):c&&(g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)),n}}function p(t,n,e,r,i){for(let o=0,a=r*i;o<a;)t(n,e,o,o+=r,1)}function g(t,n,e,r,i){for(let o=0,a=r*i;o<r;++o)t(n,e,o,o+a,r)}function y(t){const n=Math.floor(t);if(n===t)return function(t){const n=2*t+1;return(e,r,i,o,a)=>{if(!((o-=a)>=i))return;let u=t*r[i];const c=a*t;for(let t=i,n=i+c;t<n;t+=a)u+=r[Math.min(o,t)];for(let t=i,f=o;t<=f;t+=a)u+=r[Math.min(o,t+c)],e[t]=u/n,u-=r[Math.max(i,t-c)]}}(t);const e=t-n,r=2*t+1;return(t,i,o,a,u)=>{if(!((a-=u)>=o))return;let c=n*i[o];const f=u*n,s=f+u;for(let t=o,n=o+f;t<n;t+=u)c+=i[Math.min(a,t)];for(let n=o,l=a;n<=l;n+=u)c+=i[Math.min(a,n+f)],t[n]=(c+e*(i[Math.max(o,n-s)]+i[Math.min(a,n+s)]))/r,c-=i[Math.max(o,n-f)]}}function v(t,n){let e=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&++e;else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(i=+i)>=i&&++e}return e}function _(t){return 0|t.length}function b(t){return!(t>0)}function m(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function x(t,n){let e,r=0,i=0,o=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(e=n-i,i+=e/++r,o+=e*(n-i));else{let a=-1;for(let u of t)null!=(u=n(u,++a,t))&&(u=+u)>=u&&(e=u-i,i+=e/++r,o+=e*(u-i))}if(r>1)return o/(r-1)}function w(t,n){const e=x(t,n);return e?Math.sqrt(e):e}function M(t,n){let e,r;if(void 0===n)for(const n of t)null!=n&&(void 0===e?n>=n&&(e=r=n):(e>n&&(e=n),r<n&&(r=n)));else{let i=-1;for(let o of t)null!=(o=n(o,++i,t))&&(void 0===e?o>=o&&(e=r=o):(e>o&&(e=o),r<o&&(r=o)))}return[e,r]}class T{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let e=0;for(let r=0;r<this._n&&r<32;r++){const i=n[r],o=t+i,a=Math.abs(t)<Math.abs(i)?t-(o-i):i-(o-t);a&&(n[e++]=a),t=o}return n[e]=t,this._n=e+1,this}valueOf(){const t=this._partials;let n,e,r,i=this._n,o=0;if(i>0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}class InternMap extends Map{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const[n,e]of t)this.set(n,e)}get(t){return super.get(A(this,t))}has(t){return super.has(A(this,t))}set(t,n){return super.set(S(this,t),n)}delete(t){return super.delete(E(this,t))}}class InternSet extends Set{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const n of t)this.add(n)}has(t){return super.has(A(this,t))}add(t){return super.add(S(this,t))}delete(t){return super.delete(E(this,t))}}function A({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):e}function S({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):(t.set(r,e),e)}function E({_intern:t,_key:n},e){const r=n(e);return t.has(r)&&(e=t.get(r),t.delete(r)),e}function N(t){return null!==t&&"object"==typeof t?t.valueOf():t}function k(t){return t}function C(t,...n){return F(t,k,k,n)}function P(t,...n){return F(t,Array.from,k,n)}function z(t,n){for(let e=1,r=n.length;e<r;++e)t=t.flatMap((t=>t.pop().map((([n,e])=>[...t,n,e]))));return t}function $(t,n,...e){return F(t,k,n,e)}function D(t,n,...e){return F(t,Array.from,n,e)}function R(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function F(t,n,e,r){return function t(i,o){if(o>=r.length)return e(i);const a=new InternMap,u=r[o++];let c=-1;for(const t of i){Line truncated
|
||||
Reference in new issue
Block a user