rizaldy.club/assets/js/graph.js

282 lines
7.2 KiB
JavaScript
Raw Normal View History

2022-05-02 12:06:33 +07:00
async function drawGraph(
url,
baseUrl,
pathColors,
depth,
enableDrag,
enableLegend,
enableZoom
) {
const container = document.getElementById('graph-container');
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const { index, links, content } = await fetchData;
const curPage = url.replace(baseUrl, '');
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const parseIdsFromLinks = (links) => [
...new Set(links.flatMap((link) => [link.source, link.target])),
];
// links is mutated by d3
// we want to use links later on, so we make a copy and pass
// that one to d3
const copyLinks = JSON.parse(JSON.stringify(links));
const neighbours = new Set();
const wl = [curPage || '/', '__SENTINEL'];
2022-03-08 01:25:02 +07:00
if (depth >= 0) {
while (depth >= 0 && wl.length > 0) {
// compute neighbours
2022-05-02 12:06:33 +07:00
const cur = wl.shift();
if (cur === '__SENTINEL') {
depth--;
wl.push('__SENTINEL');
2022-03-08 01:25:02 +07:00
} else {
2022-05-02 12:06:33 +07:00
neighbours.add(cur);
const outgoing = index.links[cur] || [];
const incoming = index.backlinks[cur] || [];
wl.push(
...outgoing.map((l) => l.target),
...incoming.map((l) => l.source)
);
}
}
2022-03-08 01:25:02 +07:00
} else {
2022-05-02 12:06:33 +07:00
parseIdsFromLinks(copyLinks).forEach((id) => neighbours.add(id));
2022-03-08 01:25:02 +07:00
}
const data = {
2022-05-02 12:06:33 +07:00
nodes: [...neighbours].map((id) => ({ id })),
links: copyLinks.filter(
(l) => neighbours.has(l.source) && neighbours.has(l.target)
),
};
2022-03-08 01:25:02 +07:00
const color = (d) => {
2022-05-02 12:06:33 +07:00
if (d.id === curPage || (d.id === '/' && curPage === '')) {
return 'var(--g-node-active)';
}
2022-03-08 01:25:02 +07:00
for (const pathColor of pathColors) {
2022-05-02 12:06:33 +07:00
const path = Object.keys(pathColor)[0];
const colour = pathColor[path];
2022-03-08 01:25:02 +07:00
if (d.id.startsWith(path)) {
2022-05-02 12:06:33 +07:00
return colour;
}
}
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
return 'var(--g-node)';
};
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const drag = (simulation) => {
2022-03-08 01:25:02 +07:00
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(1).restart();
d.fx = d.x;
d.fy = d.y;
}
2022-03-08 01:25:02 +07:00
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
2022-03-08 01:25:02 +07:00
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const noop = () => {};
return d3
.drag()
.on('start', enableDrag ? dragstarted : noop)
.on('drag', enableDrag ? dragged : noop)
.on('end', enableDrag ? dragended : noop);
};
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const height = Math.max(container.offsetHeight, 250);
const width = container.offsetWidth;
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const simulation = d3
.forceSimulation(data.nodes)
.force('charge', d3.forceManyBody().strength(-30))
.force(
'link',
d3
.forceLink(data.links)
.id((d) => d.id)
.distance(40)
)
.force('center', d3.forceCenter());
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const svg = d3
.select('#graph-container')
2022-03-08 01:25:02 +07:00
.append('svg')
.attr('width', width)
.attr('height', height)
2022-05-02 12:06:33 +07:00
.attr('viewBox', [-width / 2, -height / 2, width, height]);
2022-03-08 01:25:02 +07:00
if (enableLegend) {
const legend = [
2022-05-02 12:06:33 +07:00
{ Current: 'var(--g-node-active)' },
{ Note: 'var(--g-node)' },
...pathColors,
];
2022-03-08 01:25:02 +07:00
legend.forEach((legendEntry, i) => {
2022-05-02 12:06:33 +07:00
const key = Object.keys(legendEntry)[0];
const colour = legendEntry[key];
svg
.append('circle')
.attr('cx', -width / 2 + 20)
.attr('cy', height / 2 - 30 * (i + 1))
.attr('r', 6)
.style('fill', colour);
svg
.append('text')
.attr('x', -width / 2 + 40)
.attr('y', height / 2 - 30 * (i + 1))
.text(key)
.style('font-size', '15px')
.attr('alignment-baseline', 'middle');
});
2022-03-08 01:25:02 +07:00
}
// draw links between nodes
2022-05-02 12:06:33 +07:00
const link = svg
.append('g')
.selectAll('line')
2022-03-08 01:25:02 +07:00
.data(data.links)
2022-05-02 12:06:33 +07:00
.join('line')
.attr('class', 'link')
.attr('stroke', 'var(--g-link)')
.attr('stroke-width', 2)
.attr('data-source', (d) => d.source.id)
.attr('data-target', (d) => d.target.id);
2022-03-08 01:25:02 +07:00
// svg groups
2022-05-02 12:06:33 +07:00
const graphNode = svg
.append('g')
.selectAll('g')
2022-03-08 01:25:02 +07:00
.data(data.nodes)
2022-05-02 12:06:33 +07:00
.enter()
.append('g');
2022-03-08 01:25:02 +07:00
// calculate radius
const nodeRadius = (d) => {
2022-05-02 12:06:33 +07:00
const numOut = index.links[d.id]?.length || 0;
const numIn = index.backlinks[d.id]?.length || 0;
return 3 + (numOut + numIn) / 4;
};
2022-03-08 01:25:02 +07:00
// draw individual nodes
2022-05-02 12:06:33 +07:00
const node = graphNode
.append('circle')
.attr('class', 'node')
.attr('id', (d) => d.id)
.attr('r', nodeRadius)
.attr('fill', color)
.style('cursor', 'pointer')
.on('click', (_, d) => {
window.navigate(
new URL(`${baseUrl}${decodeURI(d.id).replace(/\s+/g, '-')}/`),
'.singlePage'
);
2022-03-08 01:25:02 +07:00
})
2022-05-02 12:06:33 +07:00
.on('mouseover', function (_, d) {
d3.selectAll('.node')
2022-03-08 01:25:02 +07:00
.transition()
.duration(100)
2022-05-02 12:06:33 +07:00
.attr('fill', 'var(--g-node-inactive)');
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const neighbours = parseIdsFromLinks([
...(index.links[d.id] || []),
...(index.backlinks[d.id] || []),
]);
const neighbourNodes = d3
.selectAll('.node')
.filter((d) => neighbours.includes(d.id));
const currentId = d.id;
const linkNodes = d3
.selectAll('.link')
.filter((d) => d.source.id === currentId || d.target.id === currentId);
2022-03-08 01:25:02 +07:00
// highlight neighbour nodes
2022-05-02 12:06:33 +07:00
neighbourNodes.transition().duration(200).attr('fill', color);
2022-03-08 01:25:02 +07:00
// highlight links
linkNodes
.transition()
.duration(200)
2022-05-02 12:06:33 +07:00
.attr('stroke', 'var(--g-link-active)');
2022-03-08 01:25:02 +07:00
// show text for self
d3.select(this.parentNode)
.raise()
2022-05-02 12:06:33 +07:00
.select('text')
2022-03-08 01:25:02 +07:00
.transition()
.duration(200)
2022-05-02 12:06:33 +07:00
.style('opacity', 1);
})
.on('mouseleave', function (_, d) {
d3.selectAll('.node').transition().duration(200).attr('fill', color);
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
const currentId = d.id;
const linkNodes = d3
.selectAll('.link')
.filter((d) => d.source.id === currentId || d.target.id === currentId);
2022-03-08 01:25:02 +07:00
2022-05-02 12:06:33 +07:00
linkNodes.transition().duration(200).attr('stroke', 'var(--g-link)');
2022-03-08 01:25:02 +07:00
d3.select(this.parentNode)
2022-05-02 12:06:33 +07:00
.select('text')
2022-03-08 01:25:02 +07:00
.transition()
.duration(200)
2022-05-02 12:06:33 +07:00
.style('opacity', 0);
2022-03-08 01:25:02 +07:00
})
.call(drag(simulation));
// draw labels
2022-05-02 12:06:33 +07:00
const labels = graphNode
.append('text')
.attr('dx', 0)
.attr('dy', (d) => nodeRadius(d) + 8 + 'px')
.attr('text-anchor', 'middle')
.text((d) => content[d.id]?.title || d.id.replace('-', ' '))
.style('opacity', 0)
.style('pointer-events', 'none')
.style('font-size', '0.4em')
.raise()
2022-03-08 01:25:02 +07:00
.call(drag(simulation));
// set panning
if (enableZoom) {
2022-05-02 12:06:33 +07:00
svg.call(
d3
.zoom()
.extent([
[0, 0],
[width, height],
])
.scaleExtent([0.25, 4])
.on('zoom', ({ transform }) => {
link.attr('transform', transform);
node.attr('transform', transform);
const scale = transform.k;
const scaledOpacity = Math.max((scale - 1) / 3.75, 0);
labels.attr('transform', transform).style('opacity', scaledOpacity);
})
);
}
2022-03-08 01:25:02 +07:00
// progress the simulation
2022-05-02 12:06:33 +07:00
simulation.on('tick', () => {
2022-03-08 01:25:02 +07:00
link
2022-05-02 12:06:33 +07:00
.attr('x1', (d) => d.source.x)
.attr('y1', (d) => d.source.y)
.attr('x2', (d) => d.target.x)
.attr('y2', (d) => d.target.y);
node.attr('cx', (d) => d.x).attr('cy', (d) => d.y);
labels.attr('x', (d) => d.x).attr('y', (d) => d.y);
2022-03-08 01:25:02 +07:00
});
}