searchable-jekyll-template/_plugins/bidirectional_links_generator.rb

59 lines
1.7 KiB
Ruby
Raw Normal View History

2020-05-19 22:59:37 -04:00
# frozen_string_literal: true
class BidirectionalLinksGenerator < Jekyll::Generator
def generate(site)
2020-07-21 21:26:28 -04:00
graph_nodes = []
graph_edges = []
all_notes = site.collections['notes'].docs
all_pages = site.pages
all_docs = all_notes + all_pages
# Convert all Wiki/Roam-style double-bracket link syntax to plain HTML
# anchor tag elements (<a>) with "internal-link" CSS class
all_docs.each do |current_note|
all_docs.each do |note_potentially_linked_to|
current_note.content = current_note.content.gsub(
/\[\[#{note_potentially_linked_to.data['title']}\]\]/i,
"<a class='internal-link' href='#{note_potentially_linked_to.url}'>#{note_potentially_linked_to.data['title']}</a>"
)
end
end
2020-05-19 22:59:37 -04:00
# Identify note backlinks and add them to each note
all_notes.each do |current_note|
2020-07-21 21:26:28 -04:00
# Nodes: Jekyll
notes_linking_to_current_note = all_notes.filter do |e|
2020-05-19 22:59:37 -04:00
e.content.include?(current_note.url)
end
2020-07-21 21:26:28 -04:00
# Nodes: Graph
graph_nodes << {
id: note_id_from_note(current_note),
path: current_note.url,
2020-07-25 18:11:13 -04:00
label: current_note.data['title'],
2020-07-21 21:26:28 -04:00
} unless current_note.path.include?('_notes/index.html')
# Edges: Jekyll
2020-05-19 22:59:37 -04:00
current_note.data['backlinks'] = notes_linking_to_current_note
2020-07-21 21:26:28 -04:00
# Edges: Graph
notes_linking_to_current_note.each do |n|
graph_edges << {
source: note_id_from_note(n),
target: note_id_from_note(current_note),
}
end
2020-05-19 22:59:37 -04:00
end
2020-07-21 21:26:28 -04:00
File.write('_includes/notes_graph.json', JSON.dump({
edges: graph_edges,
nodes: graph_nodes,
}))
end
def note_id_from_note(note)
2020-07-25 18:11:13 -04:00
note.data['title'].to_i(36).to_s
2020-05-19 22:59:37 -04:00
end
end