Merge pull request #118 from aidenybai/add-router

This commit is contained in:
Jacky Zhao 2022-05-02 12:19:26 -04:00 committed by GitHub
commit 8934617ca0
4 changed files with 434 additions and 320 deletions

View File

@ -1,51 +1,72 @@
async function drawGraph(url, baseUrl, pathColors, depth, enableDrag, enableLegend, enableZoom) { async function drawGraph(
const { index, links, content } = await fetchData url,
const curPage = url.replace(baseUrl, "") baseUrl,
pathColors,
depth,
enableDrag,
enableLegend,
enableZoom
) {
const container = document.getElementById('graph-container');
const parseIdsFromLinks = (links) => [...(new Set(links.flatMap(link => ([link.source, link.target]))))] const { index, links, content } = await fetchData;
const curPage = url.replace(baseUrl, '');
const neighbours = new Set() const parseIdsFromLinks = (links) => [
const wl = [curPage || "/", "__SENTINEL"] ...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
// Note: shallow cloning does not work because it copies over references from the original array
const copyLinks = JSON.parse(JSON.stringify(links));
const neighbours = new Set();
const wl = [curPage || '/', '__SENTINEL'];
if (depth >= 0) { if (depth >= 0) {
while (depth >= 0 && wl.length > 0) { while (depth >= 0 && wl.length > 0) {
// compute neighbours // compute neighbours
const cur = wl.shift() const cur = wl.shift();
if (cur === "__SENTINEL") { if (cur === '__SENTINEL') {
depth-- depth--;
wl.push("__SENTINEL") wl.push('__SENTINEL');
} else { } else {
neighbours.add(cur) neighbours.add(cur);
const outgoing = index.links[cur] || [] const outgoing = index.links[cur] || [];
const incoming = index.backlinks[cur] || [] const incoming = index.backlinks[cur] || [];
wl.push(...outgoing.map(l => l.target), ...incoming.map(l => l.source)) wl.push(
...outgoing.map((l) => l.target),
...incoming.map((l) => l.source)
);
} }
} }
} else { } else {
parseIdsFromLinks(links).forEach(id => neighbours.add(id)) parseIdsFromLinks(copyLinks).forEach((id) => neighbours.add(id));
} }
const data = { const data = {
nodes: [...neighbours].map(id => ({ id })), nodes: [...neighbours].map((id) => ({ id })),
links: links.filter(l => neighbours.has(l.source) && neighbours.has(l.target)), links: copyLinks.filter(
} (l) => neighbours.has(l.source) && neighbours.has(l.target)
),
};
const color = (d) => { const color = (d) => {
if (d.id === curPage || (d.id === "/" && curPage === "")) { if (d.id === curPage || (d.id === '/' && curPage === '')) {
return "var(--g-node-active)" return 'var(--g-node-active)';
} }
for (const pathColor of pathColors) { for (const pathColor of pathColors) {
const path = Object.keys(pathColor)[0] const path = Object.keys(pathColor)[0];
const colour = pathColor[path] const colour = pathColor[path];
if (d.id.startsWith(path)) { if (d.id.startsWith(path)) {
return colour return colour;
} }
} }
return "var(--g-node)" return 'var(--g-node)';
} };
const drag = simulation => { const drag = (simulation) => {
function dragstarted(event, d) { function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(1).restart(); if (!event.active) simulation.alphaTarget(1).restart();
d.fx = d.x; d.fx = d.x;
@ -63,169 +84,198 @@ async function drawGraph(url, baseUrl, pathColors, depth, enableDrag, enableLege
d.fy = null; d.fy = null;
} }
const noop = () => { } const noop = () => {};
return d3.drag() return d3
.on("start", enableDrag ? dragstarted : noop) .drag()
.on("drag", enableDrag ? dragged : noop) .on('start', enableDrag ? dragstarted : noop)
.on("end", enableDrag ? dragended : noop); .on('drag', enableDrag ? dragged : noop)
} .on('end', enableDrag ? dragended : noop);
};
const height = Math.max(document.getElementById("graph-container").offsetHeight, 250) const height = Math.max(container.offsetHeight, 250);
const width = document.getElementById("graph-container").offsetWidth const width = container.offsetWidth;
const simulation = d3.forceSimulation(data.nodes) const simulation = d3
.force("charge", d3.forceManyBody().strength(-30)) .forceSimulation(data.nodes)
.force("link", d3.forceLink(data.links).id(d => d.id).distance(40)) .force('charge', d3.forceManyBody().strength(-30))
.force("center", d3.forceCenter()); .force(
'link',
d3
.forceLink(data.links)
.id((d) => d.id)
.distance(40)
)
.force('center', d3.forceCenter());
const svg = d3.select('#graph-container') const svg = d3
.select('#graph-container')
.append('svg') .append('svg')
.attr('width', width) .attr('width', width)
.attr('height', height) .attr('height', height)
.attr("viewBox", [-width / 2, -height / 2, width, height]); .attr('viewBox', [-width / 2, -height / 2, width, height]);
if (enableLegend) { if (enableLegend) {
const legend = [ const legend = [
{ "Current": "var(--g-node-active)" }, { Current: 'var(--g-node-active)' },
{ "Note": "var(--g-node)" }, { Note: 'var(--g-node)' },
...pathColors ...pathColors,
] ];
legend.forEach((legendEntry, i) => { legend.forEach((legendEntry, i) => {
const key = Object.keys(legendEntry)[0] const key = Object.keys(legendEntry)[0];
const colour = legendEntry[key] 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
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") .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');
});
} }
// draw links between nodes // draw links between nodes
const link = svg.append("g") const link = svg
.selectAll("line") .append('g')
.selectAll('line')
.data(data.links) .data(data.links)
.join("line") .join('line')
.attr("class", "link") .attr('class', 'link')
.attr("stroke", "var(--g-link)") .attr('stroke', 'var(--g-link)')
.attr("stroke-width", 2) .attr('stroke-width', 2)
.attr("data-source", d => d.source.id) .attr('data-source', (d) => d.source.id)
.attr("data-target", d => d.target.id) .attr('data-target', (d) => d.target.id);
// svg groups // svg groups
const graphNode = svg.append("g") const graphNode = svg
.selectAll("g") .append('g')
.selectAll('g')
.data(data.nodes) .data(data.nodes)
.enter().append("g") .enter()
.append('g');
// calculate radius // calculate radius
const nodeRadius = (d) => { const nodeRadius = (d) => {
const numOut = index.links[d.id]?.length || 0 const numOut = index.links[d.id]?.length || 0;
const numIn = index.backlinks[d.id]?.length || 0 const numIn = index.backlinks[d.id]?.length || 0;
return 3 + (numOut + numIn) / 4 return 3 + (numOut + numIn) / 4;
} };
// draw individual nodes // draw individual nodes
const node = graphNode.append("circle") const node = graphNode
.attr("class", "node") .append('circle')
.attr("id", (d) => d.id) .attr('class', 'node')
.attr("r", nodeRadius) .attr('id', (d) => d.id)
.attr("fill", color) .attr('r', nodeRadius)
.style("cursor", "pointer") .attr('fill', color)
.on("click", (_, d) => { .style('cursor', 'pointer')
window.location.href = `${baseUrl}/${decodeURI(d.id).replace(/\s+/g, '-')}/` .on('click', (_, d) => {
// SPA navigation
window.navigate(
new URL(`${baseUrl}${decodeURI(d.id).replace(/\s+/g, '-')}/`),
'.singlePage'
);
}) })
.on("mouseover", function(_, d) { .on('mouseover', function (_, d) {
d3.selectAll(".node") d3.selectAll('.node')
.transition() .transition()
.duration(100) .duration(100)
.attr("fill", "var(--g-node-inactive)") .attr('fill', 'var(--g-node-inactive)');
const neighbours = parseIdsFromLinks([...(index.links[d.id] || []), ...(index.backlinks[d.id] || [])]) const neighbours = parseIdsFromLinks([
const neighbourNodes = d3.selectAll(".node").filter(d => neighbours.includes(d.id)) ...(index.links[d.id] || []),
const currentId = d.id ...(index.backlinks[d.id] || []),
const linkNodes = d3.selectAll(".link").filter(d => d.source.id === currentId || d.target.id === currentId) ]);
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);
// highlight neighbour nodes // highlight neighbour nodes
neighbourNodes neighbourNodes.transition().duration(200).attr('fill', color);
.transition()
.duration(200)
.attr("fill", color)
// highlight links // highlight links
linkNodes linkNodes
.transition() .transition()
.duration(200) .duration(200)
.attr("stroke", "var(--g-link-active)") .attr('stroke', 'var(--g-link-active)');
// show text for self // show text for self
d3.select(this.parentNode) d3.select(this.parentNode)
.raise() .raise()
.select("text") .select('text')
.transition() .transition()
.duration(200) .duration(200)
.style("opacity", 1) .style('opacity', 1);
.raise() })
}).on("mouseleave", function(_, d) { .on('mouseleave', function (_, d) {
d3.selectAll(".node") d3.selectAll('.node').transition().duration(200).attr('fill', color);
.transition()
.duration(200)
.attr("fill", color)
const currentId = d.id const currentId = d.id;
const linkNodes = d3.selectAll(".link").filter(d => d.source.id === currentId || d.target.id === currentId) const linkNodes = d3
.selectAll('.link')
.filter((d) => d.source.id === currentId || d.target.id === currentId);
linkNodes linkNodes.transition().duration(200).attr('stroke', 'var(--g-link)');
.transition()
.duration(200)
.attr("stroke", "var(--g-link)")
d3.select(this.parentNode) d3.select(this.parentNode)
.select("text") .select('text')
.transition() .transition()
.duration(200) .duration(200)
.style("opacity", 0) .style('opacity', 0);
}) })
.call(drag(simulation)); .call(drag(simulation));
// draw labels // draw labels
const labels = graphNode.append("text") const labels = graphNode
.attr("dx", 0) .append('text')
.attr("dy", d => nodeRadius(d) + 8 + "px") .attr('dx', 0)
.attr("text-anchor", "middle") .attr('dy', (d) => nodeRadius(d) + 8 + 'px')
.text((d) => content[d.id]?.title || d.id.replace("-", " ")) .attr('text-anchor', 'middle')
.style("opacity", 0) .text((d) => content[d.id]?.title || d.id.replace('-', ' '))
.style("pointer-events", "none") .style('opacity', 0)
.style("font-size", "0.4em") .style('pointer-events', 'none')
.style('font-size', '0.4em')
.raise() .raise()
.call(drag(simulation)); .call(drag(simulation));
// set panning // set panning
if (enableZoom) { if (enableZoom) {
svg.call(d3.zoom() svg.call(
.extent([[0, 0], [width, height]]) d3
.zoom()
.extent([
[0, 0],
[width, height],
])
.scaleExtent([0.25, 4]) .scaleExtent([0.25, 4])
.on("zoom", ({ transform }) => { .on('zoom', ({ transform }) => {
link.attr("transform", transform); link.attr('transform', transform);
node.attr("transform", transform); node.attr('transform', transform);
const scale = transform.k const scale = transform.k;
const scaledOpacity = Math.max((scale - 1) / 3.75, 0) const scaledOpacity = Math.max((scale - 1) / 3.75, 0);
labels labels.attr('transform', transform).style('opacity', scaledOpacity);
.attr("transform", transform) })
.style("opacity", scaledOpacity) );
}));
} }
// progress the simulation // progress the simulation
simulation.on("tick", () => { simulation.on('tick', () => {
link link
.attr("x1", d => d.source.x) .attr('x1', (d) => d.source.x)
.attr("y1", d => d.source.y) .attr('y1', (d) => d.source.y)
.attr("x2", d => d.target.x) .attr('x2', (d) => d.target.x)
.attr("y2", d => d.target.y) .attr('y2', (d) => d.target.y);
node node.attr('cx', (d) => d.x).attr('cy', (d) => d.y);
.attr("cx", d => d.x) labels.attr('x', (d) => d.x).attr('y', (d) => d.y);
.attr("cy", d => d.y)
labels
.attr("x", d => d.x)
.attr("y", d => d.y)
}); });
} }

View File

@ -9,47 +9,47 @@ const removeMarkdown = (
preserveLinks: false, preserveLinks: false,
} }
) => { ) => {
let output = markdown || ""; let output = markdown || '';
output = output.replace(/^(-\s*?|\*\s*?|_\s*?){3,}\s*$/gm, ""); output = output.replace(/^(-\s*?|\*\s*?|_\s*?){3,}\s*$/gm, '');
try { try {
if (options.stripListLeaders) { if (options.stripListLeaders) {
if (options.listUnicodeChar) if (options.listUnicodeChar)
output = output.replace( output = output.replace(
/^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm, /^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm,
options.listUnicodeChar + " $1" options.listUnicodeChar + ' $1'
); );
else output = output.replace(/^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm, "$1"); else output = output.replace(/^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm, '$1');
} }
if (options.gfm) { if (options.gfm) {
output = output output = output
.replace(/\n={2,}/g, "\n") .replace(/\n={2,}/g, '\n')
.replace(/~{3}.*\n/g, "") .replace(/~{3}.*\n/g, '')
.replace(/~~/g, "") .replace(/~~/g, '')
.replace(/`{3}.*\n/g, ""); .replace(/`{3}.*\n/g, '');
} }
if (options.preserveLinks) { if (options.preserveLinks) {
output = output.replace(/\[(.*?)\][\[\(](.*?)[\]\)]/g, "$1 ($2)") output = output.replace(/\[(.*?)\][\[\(](.*?)[\]\)]/g, '$1 ($2)');
} }
output = output output = output
.replace(/<[^>]*>/g, "") .replace(/<[^>]*>/g, '')
.replace(/^[=\-]{2,}\s*$/g, "") .replace(/^[=\-]{2,}\s*$/g, '')
.replace(/\[\^.+?\](\: .*?$)?/g, "") .replace(/\[\^.+?\](\: .*?$)?/g, '')
.replace(/\s{0,2}\[.*?\]: .*?$/g, "") .replace(/\s{0,2}\[.*?\]: .*?$/g, '')
.replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, options.useImgAltText ? "$1" : "") .replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, options.useImgAltText ? '$1' : '')
.replace(/\[(.*?)\][\[\(].*?[\]\)]/g, "$1") .replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1')
.replace(/^\s{0,3}>\s?/g, "") .replace(/^\s{0,3}>\s?/g, '')
.replace(/(^|\n)\s{0,3}>\s?/g, "\n\n") .replace(/(^|\n)\s{0,3}>\s?/g, '\n\n')
.replace(/^\s{1,2}\[(.*?)\]: (\S+)( ".*?")?\s*$/g, "") .replace(/^\s{1,2}\[(.*?)\]: (\S+)( ".*?")?\s*$/g, '')
.replace( .replace(
/^(\n)?\s{0,}#{1,6}\s+| {0,}(\n)?\s{0,}#{0,} {0,}(\n)?\s{0,}$/gm, /^(\n)?\s{0,}#{1,6}\s+| {0,}(\n)?\s{0,}#{0,} {0,}(\n)?\s{0,}$/gm,
"$1$2$3" '$1$2$3'
) )
.replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, "$2") .replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, '$2')
.replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, "$2") .replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, '$2')
.replace(/(`{3,})(.*?)\1/gm, "$2") .replace(/(`{3,})(.*?)\1/gm, '$2')
.replace(/`(.+?)`/g, "$1") .replace(/`(.+?)`/g, '$1')
.replace(/\n{2,}/g, "\n\n"); .replace(/\n{2,}/g, '\n\n');
} catch (e) { } catch (e) {
console.error(e); console.error(e);
return markdown; return markdown;
@ -58,182 +58,206 @@ const removeMarkdown = (
}; };
// ----- // -----
(async function() { (async function () {
const encoder = str => str.toLowerCase().split(/([^a-z]|[^\x00-\x7F])+/) const encoder = (str) => str.toLowerCase().split(/([^a-z]|[^\x00-\x7F])+/);
const contentIndex = new FlexSearch.Document({ const contentIndex = new FlexSearch.Document({
cache: true, cache: true,
charset: "latin:extra", charset: 'latin:extra',
optimize: true, optimize: true,
index: [{ index: [
field: "content", {
tokenize: "reverse", field: 'content',
tokenize: 'reverse',
encode: encoder, encode: encoder,
}, { },
field: "title", {
tokenize: "forward", field: 'title',
tokenize: 'forward',
encode: encoder, encode: encoder,
}] },
}) ],
});
const { content } = await fetchData const { content } = await fetchData;
for (const [key, value] of Object.entries(content)) { for (const [key, value] of Object.entries(content)) {
contentIndex.add({ contentIndex.add({
id: key, id: key,
title: value.title, title: value.title,
content: removeMarkdown(value.content), content: removeMarkdown(value.content),
}) });
} }
const highlight = (content, term) => { const highlight = (content, term) => {
const highlightWindow = 20 const highlightWindow = 20;
const tokenizedTerm = term.split(/\s+/).filter(t => t !== "") const tokenizedTerm = term.split(/\s+/).filter((t) => t !== '');
const splitText = content.split(/\s+/).filter(t => t !== "") const splitText = content.split(/\s+/).filter((t) => t !== '');
const includesCheck = (token) => tokenizedTerm.some(term => token.toLowerCase().startsWith(term.toLowerCase())) const includesCheck = (token) =>
tokenizedTerm.some((term) =>
token.toLowerCase().startsWith(term.toLowerCase())
);
const occurrencesIndices = splitText const occurrencesIndices = splitText.map(includesCheck);
.map(includesCheck)
// calculate best index // calculate best index
let bestSum = 0 let bestSum = 0;
let bestIndex = 0 let bestIndex = 0;
for (let i = 0; i < Math.max(occurrencesIndices.length - highlightWindow, 0); i++) { for (
const window = occurrencesIndices.slice(i, i + highlightWindow) let i = 0;
const windowSum = window.reduce((total, cur) => total + cur, 0) i < Math.max(occurrencesIndices.length - highlightWindow, 0);
i++
) {
const window = occurrencesIndices.slice(i, i + highlightWindow);
const windowSum = window.reduce((total, cur) => total + cur, 0);
if (windowSum >= bestSum) { if (windowSum >= bestSum) {
bestSum = windowSum bestSum = windowSum;
bestIndex = i bestIndex = i;
} }
} }
const startIndex = Math.max(bestIndex - highlightWindow, 0) const startIndex = Math.max(bestIndex - highlightWindow, 0);
const endIndex = Math.min(startIndex + 2 * highlightWindow, splitText.length) const endIndex = Math.min(
startIndex + 2 * highlightWindow,
splitText.length
);
const mappedText = splitText const mappedText = splitText
.slice(startIndex, endIndex) .slice(startIndex, endIndex)
.map(token => { .map((token) => {
if (includesCheck(token)) { if (includesCheck(token)) {
return `<span class="search-highlight">${token}</span>` return `<span class="search-highlight">${token}</span>`;
} }
return token return token;
}) })
.join(" ") .join(' ')
.replaceAll('</span> <span class="search-highlight">', " ") .replaceAll('</span> <span class="search-highlight">', ' ');
return `${startIndex === 0 ? "" : "..."}${mappedText}${endIndex === splitText.length ? "" : "..."}` return `${startIndex === 0 ? '' : '...'}${mappedText}${
} endIndex === splitText.length ? '' : '...'
}`;
};
const resultToHTML = ({ url, title, content, term }) => { const resultToHTML = ({ url, title, content, term }) => {
const text = removeMarkdown(content) const text = removeMarkdown(content);
const resultTitle = highlight(title, term) const resultTitle = highlight(title, term);
const resultText = highlight(text, term) const resultText = highlight(text, term);
return `<button class="result-card" id="${url}"> return `<button class="result-card" id="${url}">
<h3>${resultTitle}</h3> <h3>${resultTitle}</h3>
<p>${resultText}</p> <p>${resultText}</p>
</button>` </button>`;
} };
const redir = (id, term) => { const redir = (id, term) => {
window.location.href = `${BASE_URL}${id}#:~:text=${encodeURIComponent(term)}/` // SPA navigation
} window.navigate(
new URL(
`${BASE_URL.slice(0, -1)}${id}#:~:text=${encodeURIComponent(term)}/`
),
'.singlePage'
);
closeSearch();
};
const formatForDisplay = id => ({ const formatForDisplay = (id) => ({
id, id,
url: id, url: id,
title: content[id].title, title: content[id].title,
content: content[id].content content: content[id].content,
}) });
const source = document.getElementById('search-bar') const source = document.getElementById('search-bar');
const results = document.getElementById("results-container") const results = document.getElementById('results-container');
let term let term;
source.addEventListener("keyup", (e) => { source.addEventListener('keyup', (e) => {
if (e.key === "Enter") { if (e.key === 'Enter') {
const anchor = document.getElementsByClassName("result-card")[0] const anchor = document.getElementsByClassName('result-card')[0];
redir(anchor.id, term) redir(anchor.id, term);
} }
}) });
source.addEventListener('input', (e) => { source.addEventListener('input', (e) => {
term = e.target.value term = e.target.value;
const searchResults = contentIndex.search(term, [ const searchResults = contentIndex.search(term, [
{ {
field: "content", field: 'content',
limit: 10, limit: 10,
}, },
{ {
field: "title", field: 'title',
limit: 5, limit: 5,
} },
]) ]);
const getByField = field => { const getByField = (field) => {
const results = searchResults.filter(x => x.field === field) const results = searchResults.filter((x) => x.field === field);
if (results.length === 0) { if (results.length === 0) {
return [] return [];
} else { } else {
return [...results[0].result] return [...results[0].result];
} }
} };
const allIds = new Set([...getByField('title'), ...getByField('content')]) const allIds = new Set([...getByField('title'), ...getByField('content')]);
const finalResults = [...allIds].map(formatForDisplay) const finalResults = [...allIds].map(formatForDisplay);
// display // display
if (finalResults.length === 0) { if (finalResults.length === 0) {
results.innerHTML = `<button class="result-card"> results.innerHTML = `<button class="result-card">
<h3>No results.</h3> <h3>No results.</h3>
<p>Try another search term?</p> <p>Try another search term?</p>
</button>` </button>`;
} else { } else {
results.innerHTML = finalResults results.innerHTML = finalResults
.map(result => resultToHTML({ .map((result) =>
resultToHTML({
...result, ...result,
term, term,
}))
.join("\n")
const anchors = document.getElementsByClassName("result-card");
[...anchors].forEach(anchor => {
anchor.onclick = () => redir(anchor.id, term)
}) })
)
.join('\n');
const anchors = document.getElementsByClassName('result-card');
[...anchors].forEach((anchor) => {
anchor.onclick = () => redir(anchor.id, term);
});
} }
}) });
const searchContainer = document.getElementById('search-container');
const searchContainer = document.getElementById("search-container")
function openSearch() { function openSearch() {
if (searchContainer.style.display === "none" || searchContainer.style.display === "") { if (
source.value = "" searchContainer.style.display === 'none' ||
results.innerHTML = "" searchContainer.style.display === ''
searchContainer.style.display = "block" ) {
source.focus() source.value = '';
results.innerHTML = '';
searchContainer.style.display = 'block';
source.focus();
} else { } else {
searchContainer.style.display = "none" searchContainer.style.display = 'none';
} }
} }
function closeSearch() { function closeSearch() {
searchContainer.style.display = "none" searchContainer.style.display = 'none';
} }
document.addEventListener('keydown', (event) => { document.addEventListener('keydown', (event) => {
if (event.key === "k" && (event.ctrlKey || event.metaKey)) { if (event.key === 'k' && (event.ctrlKey || event.metaKey)) {
event.preventDefault() event.preventDefault();
openSearch() openSearch();
} }
if (event.key === "Escape") { if (event.key === 'Escape') {
event.preventDefault() event.preventDefault();
closeSearch() closeSearch();
} }
}) });
const searchButton = document.getElementById("search-icon") const searchButton = document.getElementById('search-icon');
searchButton.addEventListener('click', (evt) => { searchButton.addEventListener('click', (evt) => {
openSearch() openSearch();
}) });
searchButton.addEventListener('keydown', (evt) => { searchButton.addEventListener('keydown', (evt) => {
openSearch() openSearch();
}) });
searchContainer.addEventListener('click', (evt) => { searchContainer.addEventListener('click', (evt) => {
closeSearch() closeSearch();
}) });
document.getElementById("search-space").addEventListener('click', (evt) => { document.getElementById('search-space').addEventListener('click', (evt) => {
evt.stopPropagation() evt.stopPropagation();
}) });
})() })();

View File

@ -1,4 +1,8 @@
<script src="https://cdn.jsdelivr.net/npm/d3@6.7.0/dist/d3.min.js" integrity="sha256-+7jaYCp29O1JusNWHaYtgUn6EhuP0VaFuswhNV06MyI=" crossorigin="anonymous"></script> <script
src="https://cdn.jsdelivr.net/npm/d3@6.7.0/dist/d3.min.js"
integrity="sha256-+7jaYCp29O1JusNWHaYtgUn6EhuP0VaFuswhNV06MyI="
crossorigin="anonymous"
></script>
<h3>Interactive Graph</h3> <h3>Interactive Graph</h3>
<div id="graph-container"></div> <div id="graph-container"></div>
<style> <style>
@ -12,14 +16,3 @@
</style> </style>
{{ $js := resources.Get "js/graph.js" | resources.Fingerprint "md5" }} {{ $js := resources.Get "js/graph.js" | resources.Fingerprint "md5" }}
<script src="{{ $js.Permalink }}"></script> <script src="{{ $js.Permalink }}"></script>
<script>
drawGraph(
{{strings.TrimRight "/" .Page.Permalink}},
{{strings.TrimRight "/" .Site.BaseURL}},
{{$.Site.Data.graphConfig.paths}},
{{$.Site.Data.graphConfig.depth}},
{{$.Site.Data.graphConfig.enableDrag}},
{{$.Site.Data.graphConfig.enableLegend}},
{{$.Site.Data.graphConfig.enableZoom}}
)
</script>

View File

@ -1,13 +1,26 @@
<head> <head>
<!-- Meta tags --> <!-- Meta tags -->
<meta charset="UTF-8"> <meta charset="UTF-8" />
<meta name="description" content="{{if .IsHome}}{{$.Site.Data.config.description}}{{else}}{{.Summary}}{{end}}"> <meta
<title>{{ if .Title }}{{ .Title }}{{ else }}{{ $.Site.Data.config.page_title }}{{ end }}</title> name="description"
<meta name="viewport" content="width=device-width, initial-scale=1"> content="{{if .IsHome}}{{$.Site.Data.config.description}}{{else}}{{.Summary}}{{end}}"
<link rel="shortcut icon" type="image/png" href="{{$.Site.BaseURL}}/icon.png" /> />
<title>
{{ if .Title }}{{ .Title }}{{ else }}{{ $.Site.Data.config.page_title }}{{
end }}
</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="shortcut icon"
type="image/png"
href="{{$.Site.BaseURL}}/icon.png"
/>
<!-- CSS Stylesheets and Fonts --> <!-- CSS Stylesheets and Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Source+Sans+Pro:wght@400;600;700&family=Fira+Code:wght@400;700&display=swap" rel="stylesheet"> <link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Source+Sans+Pro:wght@400;600;700&family=Fira+Code:wght@400;700&display=swap"
rel="stylesheet"
/>
{{$sass := resources.Match "styles/[!_]*.scss" }} {{$sass := resources.Match "styles/[!_]*.scss" }}
{{$css := slice }} {{$css := slice }}
{{range $sass}} {{range $sass}}
@ -15,15 +28,18 @@
{{$css = $css | append $scss}} {{$css = $css | append $scss}}
{{end}} {{end}}
{{$finalCss := $css | resources.Concat "styles.css" | resources.Fingerprint "md5" | resources.Minify }} {{$finalCss := $css | resources.Concat "styles.css" | resources.Fingerprint "md5" | resources.Minify }}
<link href="{{$finalCss.Permalink}}" rel="stylesheet"> <link href="{{$finalCss.Permalink}}" rel="stylesheet" />
{{ $darkMode := resources.Get "js/darkmode.js" | resources.Fingerprint "md5" | resources.Minify }} {{ $darkMode := resources.Get "js/darkmode.js" | resources.Fingerprint "md5" |
resources.Minify }}
<script src="{{$darkMode.Permalink}}"></script> <script src="{{$darkMode.Permalink}}"></script>
{{partial "katex.html" .}} {{partial "katex.html" .}}
<!-- Preload page vars --> <!-- Preload page vars -->
{{$linkIndex := resources.Get "indices/linkIndex.json" | resources.Fingerprint "md5" | resources.Minify | }} {{$linkIndex := resources.Get "indices/linkIndex.json" | resources.Fingerprint
{{$contentIndex := resources.Get "indices/contentIndex.json" | resources.Fingerprint "md5" | resources.Minify }} "md5" | resources.Minify | }} {{$contentIndex := resources.Get
"indices/contentIndex.json" | resources.Fingerprint "md5" | resources.Minify
}}
<script> <script>
const BASE_URL = {{.Site.BaseURL}} const BASE_URL = {{.Site.BaseURL}}
const fetchData = Promise.all([ const fetchData = Promise.all([
@ -42,5 +58,36 @@
content, content,
})) }))
</script> </script>
<script type="module">
import { router, navigate } from "https://unpkg.com/million/dist/router.mjs";
// SPA navigation for access later
window.navigate = navigate;
// We only mutate document.title and content within .singlePage element
router(".singlePage");
const callback = () => {
// requestAnimationFrame() delays graph draw until SPA routing is finished
const draw = () => {
const container = document.getElementById("graph-container");
// retry if the graph is not ready
if (!container) return requestAnimationFrame(draw);
// clear the graph in case there is anything within it
container.textContent = "";
drawGraph(
{{strings.TrimRight "/" .Page.Permalink}},
{{strings.TrimRight "/" .Site.BaseURL}},
{{$.Site.Data.graphConfig.paths}},
{{$.Site.Data.graphConfig.depth}},
{{$.Site.Data.graphConfig.enableDrag}},
{{$.Site.Data.graphConfig.enableLegend}},
{{$.Site.Data.graphConfig.enableZoom}}
);
};
requestAnimationFrame(draw);
};
// We need on initial load, then subsequent redirs
window.addEventListener("million:navigate", callback);
window.addEventListener("DOMContentLoaded", callback);
</script>
</head> </head>
{{ template "_internal/google_analytics.html" . }} {{ template "_internal/google_analytics.html" . }}