Skip to content

Commit

Permalink
embed the template in the binary
Browse files Browse the repository at this point in the history
  • Loading branch information
bligneri committed Nov 11, 2024
1 parent 9fa56bb commit bbd88ef
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 36 deletions.
15 changes: 4 additions & 11 deletions cmd/zk-graph/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"os"
"path/filepath"
"strings"

"github.com/bligneri/zk-graph/pkg/graph"
)
Expand All @@ -16,6 +17,7 @@ func main() {
outputFileName := flag.String("out", "/tmp/zk-graph/output.html", "Path to the output HTML file")
serverMode := flag.Bool("server", false, "Start a web server to view output files")
highlight := flag.String("highlight", "", "Highlight title or filename (comma-separated)")
templateName := flag.String("template", "", "Name of the template")
flag.Parse()

if *serverMode {
Expand Down Expand Up @@ -52,21 +54,12 @@ func main() {
os.Exit(1)
}

idTitleDict := make(map[string][2]string)
for _, note := range data.Notes {
title := note.Title
if title == "" {
title = note.Filename
}
idTitleDict[note.Path] = [2]string{title, note.Path}
}

highlightList := []string{}
if *highlight != "" {
highlightList = append(highlightList, *highlight) // Split by commas if necessary
highlightList = strings.Split(*highlight, ",") // Split comma-separated highlights into a slice
}

err = graph.GenerateForceGraph(idTitleDict, data.Links, highlightList, *outputFileName)
err = graph.GenerateForceGraph(data.Notes, data.Links, highlightList, *outputFileName, *templateName)
if err != nil {
fmt.Printf("Error generating force graph: %v\n", err)
}
Expand Down
11 changes: 11 additions & 0 deletions pkg/assets/embed.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package assets

import _ "embed"

//go:embed template/force_graph.tmpl
var ForceGraphTemplate string

// GetForceGraphTemplate exposes the embedded template
func GetForceGraphTemplate() string {
return ForceGraphTemplate
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,34 @@

<script src="https://d3js.org/d3.v7.min.js"></script>

<script>
function showNodeInfo(event, d) {
if (!d) {
console.warn("Node data is undefined");
return;
}

var infoBox = document.getElementById('node-info');
var titleElem = document.getElementById('node-title');
var pathElem = document.getElementById('node-path');
var openFileLink = document.getElementById('open-file');

// Provide a fallback value if `title` is undefined
titleElem.textContent = d.title || d.id || "Unknown Title";
var fullPath = d.absPath || "Unknown Path"; // Provide a fallback if `absPath` is missing
pathElem.textContent = fullPath;
openFileLink.href = 'file://' + fullPath;

infoBox.style.display = 'block';
}
</script>

<script>
let data = {{.Data}};
data = JSON.parse(data);
if (!data.links) {
data.links = []; // Initialize as an empty array if null or undefined
}
let height = 800;
let width = 1200;

Expand All @@ -33,7 +58,8 @@
console.log("Zoom filter event type:", event ? event.type : "undefined");
return event && validEventTypes.includes(event.type);
})
);
)
.on("click", showNodeInfo);

// Group to hold nodes and links; applies zoom/pan transformations
const g = svg.append("g");
Expand Down
89 changes: 65 additions & 24 deletions pkg/graph/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,66 +6,100 @@ import (
"html/template"
"os"
"path/filepath"
)

const (
ForceGraphTemplateName = "template/force_graph.tmpl"
"github.com/bligneri/zk-graph/pkg/assets"
)

type Link struct {
SourcePath string `json:"sourcePath"`
TargetPath string `json:"targetPath"`
}

type LinkData struct {
Source string `json:"source"`
Target string `json:"target"`
Value string `json:"value"`
}

type Note struct {
AbsPath string `json:"absPath"`
Path string `json:"path"`
Title string `json:"title"`
Filename string `json:"filename"`
}

type Node struct {
ID string `json:"id"`
Group int `json:"group"`
ID string `json:"id"`
Group int `json:"group"`
AbsPath string `json:"absPath"`
Title string `json:"title"`
}

type GraphData struct {
Nodes []Node `json:"nodes"`
Links []map[string]string `json:"links"`
Nodes []Node `json:"nodes"`
Links []LinkData `json:"links"`
}

func GenerateForceGraph(idTitleDict map[string][2]string, links []Link, highlight []string, outputFileName string) error {
func GenerateForceGraph(notes []Note, links []Link, highlight []string, outputFileName string, templateName string) error {
nodes := []Node{}
var templateContent string
var tmpl *template.Template

highlightMap := make(map[string]bool)
for _, h := range highlight {
highlightMap[h] = true
}

for uid, val := range idTitleDict {
title := val[0]
for _, note := range notes {
title := note.Title
if title == "" {
title = note.Filename
}

group := 1
if highlightMap[uid] {
if highlightMap[note.Filename] {
group = 2
}
nodes = append(nodes, Node{ID: title, Group: group})

nodes = append(nodes, Node{
ID: title,
Group: group,
AbsPath: note.AbsPath,
Title: title,
})
}

linkList := []map[string]string{}
pathToTitle := make(map[string]string)
for path, val := range idTitleDict {
pathToTitle[path] = val[0]
for _, note := range notes {
if note.Path != "" {
pathToTitle[note.Path] = note.Title
if note.Title == "" {
pathToTitle[note.Path] = note.Filename // Fallback to filename if title is empty
}
}
}

fmt.Println(pathToTitle)

// Create the list of links
var linkList []LinkData
for _, link := range links {
sourceID, sourceOK := pathToTitle[link.SourcePath]
targetID, targetOK := pathToTitle[link.TargetPath]
if sourceOK && targetOK {
linkList = append(linkList, map[string]string{
"source": sourceID,
"target": targetID,
"value": "2",
linkList = append(linkList, LinkData{
Source: sourceID,
Target: targetID,
Value: "2",
})
} else {
fmt.Printf("Warning: Missing source or target ID for link from %s to %s\n", link.SourcePath, link.TargetPath)
// Improved error logging for missing links
if !sourceOK {
fmt.Printf("Warning: Missing source ID for link from %s\n", link.SourcePath)
}
if !targetOK {
fmt.Printf("Warning: Missing target ID for link to %s\n", link.TargetPath)
}
}
}

Expand All @@ -75,12 +109,19 @@ func GenerateForceGraph(idTitleDict map[string][2]string, links []Link, highligh
return fmt.Errorf("error marshalling graph data: %v", err)
}

templateContent, err := os.ReadFile(ForceGraphTemplateName)
if err != nil {
return fmt.Errorf("error reading template file: %v", err)
if templateName != "" {
content, err := os.ReadFile(templateName)
if err == nil {
templateContent = string(content)
} else {
fmt.Printf("Warning: Unable to read specified template file '%s', using default template. Error: %v\n", templateName, err)
templateContent = assets.GetForceGraphTemplate()
}
} else {
templateContent = assets.GetForceGraphTemplate()
}

tmpl, err := template.New("graph").Parse(string(templateContent))
tmpl, err = template.New("graph").Parse(templateContent)
if err != nil {
return fmt.Errorf("error parsing template: %v", err)
}
Expand Down

0 comments on commit bbd88ef

Please sign in to comment.