You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

271 lines
7.9 KiB
JavaScript

async function drawGraph(baseUrl,isHome,pathColors,graphConfig) {
let {
depth,
enableDrag,
enableLegend,
enableZoom,
opacityScale,
scale,
repelForce,
fontSize} = graphConfig;
const container = document.getElementById("graph-container")
3 years ago
const { index, links, content } = await fetchData
// Use .pathname to remove hashes / searchParams / text fragments
const cleanUrl = window.location.origin + window.location.pathname
const curPage = cleanUrl.replace(/\/$/g, "").replace(baseUrl, "")
3 years ago
3 years ago
const parseIdsFromLinks = (links) => [
...new Set(links.flatMap((link) => [link.source, link.target])),
]
3 years ago
// Links is mutated by d3. We want to use links later on, so we make a copy and pass that one to d3
// Note: shallow cloning does not work because it copies over references from the original array
const copyLinks = JSON.parse(JSON.stringify(links))
3 years ago
const neighbours = new Set()
const wl = [curPage || "/", "__SENTINEL"]
3 years ago
if (depth >= 0) {
while (depth >= 0 && wl.length > 0) {
// compute neighbours
const cur = wl.shift()
if (cur === "__SENTINEL") {
3 years ago
depth--
wl.push("__SENTINEL")
3 years ago
} else {
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))
}
}
3 years ago
} else {
parseIdsFromLinks(copyLinks).forEach((id) => neighbours.add(id))
3 years ago
}
const data = {
3 years ago
nodes: [...neighbours].map((id) => ({ id })),
links: copyLinks.filter((l) => neighbours.has(l.source) && neighbours.has(l.target)),
3 years ago
}
const color = (d) => {
if (d.id === curPage || (d.id === "/" && curPage === "")) {
return "var(--g-node-active)"
}
3 years ago
for (const pathColor of pathColors) {
const path = Object.keys(pathColor)[0]
const colour = pathColor[path]
if (d.id.startsWith(path)) {
return colour
}
}
3 years ago
return "var(--g-node)"
3 years ago
}
3 years ago
const drag = (simulation) => {
3 years ago
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(1).restart()
d.fx = d.x
d.fy = d.y
}
3 years ago
function dragged(event, d) {
d.fx = event.x
d.fy = event.y
}
3 years ago
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0)
d.fx = null
d.fy = null
}
3 years ago
const noop = () => {}
3 years ago
return d3
.drag()
.on("start", enableDrag ? dragstarted : noop)
.on("drag", enableDrag ? dragged : noop)
.on("end", enableDrag ? dragended : noop)
3 years ago
}
const height = Math.max(container.offsetHeight, isHome ? 500 : 250)
const width = container.offsetWidth
3 years ago
3 years ago
const simulation = d3
.forceSimulation(data.nodes)
.force("charge", d3.forceManyBody().strength(-100 * repelForce))
3 years ago
.force(
"link",
3 years ago
d3
.forceLink(data.links)
.id((d) => d.id)
.distance(40),
3 years ago
)
.force("center", d3.forceCenter())
3 years ago
3 years ago
const svg = d3
.select("#graph-container")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr('viewBox', [-width / 2 * 1 / scale, -height / 2 * 1 / scale, width * 1 / scale, height * 1 / scale])
3 years ago
if (enableLegend) {
const legend = [{ Current: "var(--g-node-active)" }, { Note: "var(--g-node)" }, ...pathColors]
3 years ago
legend.forEach((legendEntry, i) => {
const key = Object.keys(legendEntry)[0]
const colour = legendEntry[key]
3 years ago
svg
.append("circle")
.attr("cx", -width / 2 + 20)
.attr("cy", height / 2 - 30 * (i + 1))
.attr("r", 6)
.style("fill", colour)
3 years ago
svg
.append("text")
.attr("x", -width / 2 + 40)
.attr("y", height / 2 - 30 * (i + 1))
3 years ago
.text(key)
.style("font-size", "15px")
.attr("alignment-baseline", "middle")
3 years ago
})
}
// draw links between nodes
3 years ago
const link = svg
.append("g")
.selectAll("line")
3 years ago
.data(data.links)
.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)
3 years ago
// svg groups
const graphNode = svg.append("g").selectAll("g").data(data.nodes).enter().append("g")
3 years ago
// calculate radius
const nodeRadius = (d) => {
const numOut = index.links[d.id]?.length || 0
const numIn = index.backlinks[d.id]?.length || 0
return 3 + (numOut + numIn) / 4
}
3 years ago
// draw individual nodes
3 years ago
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) => {
// SPA navigation
window.Million.navigate(new URL(`${baseUrl}${decodeURI(d.id).replace(/\s+/g, "-")}/`), ".singlePage")
3 years ago
})
.on("mouseover", function (_, d) {
d3.selectAll(".node").transition().duration(100).attr("fill", "var(--g-node-inactive)")
3 years ago
3 years ago
const neighbours = parseIdsFromLinks([
...(index.links[d.id] || []),
...(index.backlinks[d.id] || []),
])
const neighbourNodes = d3.selectAll(".node").filter((d) => neighbours.includes(d.id))
3 years ago
const currentId = d.id
window.Million.prefetch(new URL(`${baseUrl}${decodeURI(d.id).replace(/\s+/g, "-")}/`))
3 years ago
const linkNodes = d3
.selectAll(".link")
.filter((d) => d.source.id === currentId || d.target.id === currentId)
3 years ago
// highlight neighbour nodes
neighbourNodes.transition().duration(200).attr("fill", color)
3 years ago
// highlight links
linkNodes.transition().duration(200).attr("stroke", "var(--g-link-active)")
3 years ago
const bigFont = fontSize*1.5
3 years ago
// show text for self
d3.select(this.parentNode)
.raise()
.select("text")
3 years ago
.transition()
.duration(200)
.attr('opacityOld', d3.select(this.parentNode).select('text').style("opacity"))
.style('opacity', 1)
.style('font-size', bigFont+'em')
.attr('dy', d => nodeRadius(d) + 20 + 'px') // radius is in px
3 years ago
})
.on("mouseleave", function (_, d) {
d3.selectAll(".node").transition().duration(200).attr("fill", color)
3 years ago
const currentId = d.id
3 years ago
const linkNodes = d3
.selectAll(".link")
.filter((d) => d.source.id === currentId || d.target.id === currentId)
3 years ago
linkNodes.transition().duration(200).attr("stroke", "var(--g-link)")
3 years ago
d3.select(this.parentNode)
.select("text")
.transition()
.duration(200)
.style('opacity', d3.select(this.parentNode).select('text').attr("opacityOld"))
.style('font-size', fontSize+'em')
.attr('dy', d => nodeRadius(d) + 8 + 'px') // radius is in px
3 years ago
})
.call(drag(simulation))
3 years ago
// draw labels
3 years ago
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', (opacityScale - 1) / 3.75)
.style("pointer-events", "none")
.style('font-size', fontSize+'em')
.raise()
.call(drag(simulation))
3 years ago
// set panning
if (enableZoom) {
3 years ago
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 * opacityScale;
const scaledOpacity = Math.max((scale - 1) / 3.75, 0)
labels.attr("transform", transform).style("opacity", scaledOpacity)
}),
)
}
3 years ago
// progress the simulation
simulation.on("tick", () => {
3 years ago
link
.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)
})
3 years ago
}