Skip to content

Commit

Permalink
feat: Added wikiedia like backlink preview(js)
Browse files Browse the repository at this point in the history
- added notesindex.json generation for backlink preview
- TODO: Broken parser tests
- TODO: add backlink from child note to parent

Co-authored-by: Anirudh Sudhir <anirudh.sudhir1@gmail.com>
  • Loading branch information
bwaklog and anirudhsudhir committed Apr 12, 2024
1 parent e974175 commit 35c38b3
Show file tree
Hide file tree
Showing 12 changed files with 168 additions and 88 deletions.
4 changes: 2 additions & 2 deletions cmd/anna/anna.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package anna

import (
"fmt"
"html/template"
"log"
"os"
Expand Down Expand Up @@ -87,7 +86,8 @@ func (cmd *Cmd) VanillaRender() {
e.DeepDataMerge.Notes = p.Notes

e.GenerateLinkStore()
fmt.Println(e.DeepDataMerge.LinkStore)
// fmt.Println(e.DeepDataMerge.LinkStore)
e.RenderNotes(helpers.SiteDataPath, templ)
e.GenerateNoteRoot(helpers.SiteDataPath, templ)
e.GenerateNoteJSONIdex(helper.SiteDataPath)
}
19 changes: 19 additions & 0 deletions pkg/engine/anna_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,25 @@ func (e *Engine) RenderTags(fileOutPath string, templ *template.Template) {
wg.Wait()
}

func (e *Engine) GenerateNoteJSONIdex(outFilePath string) {
jsonFile, err := os.Create(outFilePath + "/static/noteindex.json")
if err != nil {
e.ErrorLogger.Fatal(err)
}

defer jsonFile.Close()

jsonMergedMarshaledData, err := json.Marshal(e.DeepDataMerge.Notes)
if err != nil {
e.ErrorLogger.Fatal(err)
}

_, err = jsonFile.Write(jsonMergedMarshaledData)
if err != nil {
e.ErrorLogger.Fatal(err)
}
}

func (e *Engine) GenerateJSONIndex(outFilePath string) {
// This function creates an index of the site for search
// It extracts data from the e.Templates slice
Expand Down
27 changes: 19 additions & 8 deletions pkg/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,14 @@ func (p *Parser) ParseMDDir(baseDirPath string, baseDirFS fs.FS) {
p.ErrorLogger.Fatal(err)
}

fronmatter, body, parseSuccess := p.ParseMarkdownContent(string(content))
fronmatter, body, markdownContent, parseSuccess := p.ParseMarkdownContent(string(content))
if parseSuccess {
if fronmatter.Type == "post" {
if (fronmatter.Draft && p.RenderDrafts) || !fronmatter.Draft {
p.AddFile(baseDirPath, fileName, fronmatter, body)
p.AddFile(baseDirPath, fileName, fronmatter, markdownContent, body)
}
} else {
p.AddFile(baseDirPath, fileName, fronmatter, body)
p.AddFile(baseDirPath, fileName, fronmatter, markdownContent, body)
}
}

Expand All @@ -125,7 +125,7 @@ func (p *Parser) ParseMDDir(baseDirPath string, baseDirFS fs.FS) {
})
}

func (p *Parser) AddFile(baseDirPath string, dirEntryPath string, frontmatter Frontmatter, body string) {
func (p *Parser) AddFile(baseDirPath string, dirEntryPath string, frontmatter Frontmatter, markdownContent string, body string) {
p.MdFilesName = append(p.MdFilesName, dirEntryPath)
// fmt.Println(baseDirPath, dirEntryPath)
filepath := baseDirPath + dirEntryPath
Expand Down Expand Up @@ -172,11 +172,22 @@ func (p *Parser) AddFile(baseDirPath string, dirEntryPath string, frontmatter Fr
if frontmatter.Type == "note" {
// url = "notes/" + url

markdownContent = strings.TrimFunc(markdownContent, func(r rune) bool {
return r == '\n' || r == '\t'
})

// trim the content up to n characters

if len(markdownContent) > 200 {
markdownContent = markdownContent[:200]
}

note := Note{
CompleteURL: template.URL(url),
Date: date,
Frontmatter: frontmatter,
Body: template.HTML(body),
MarkdownBody: markdownContent,
LinkedNoteURLs: []template.URL{},
}

Expand All @@ -188,7 +199,7 @@ func (p *Parser) AddFile(baseDirPath string, dirEntryPath string, frontmatter Fr

}

func (p *Parser) ParseMarkdownContent(filecontent string) (Frontmatter, string, bool) {
func (p *Parser) ParseMarkdownContent(filecontent string) (Frontmatter, string, string, bool) {
var parsedFrontmatter Frontmatter
var markdown string
/*
Expand All @@ -203,14 +214,14 @@ func (p *Parser) ParseMarkdownContent(filecontent string) (Frontmatter, string,
frontmatterSplit := ""

if len(splitContents) <= 1 {
return Frontmatter{}, "", false
return Frontmatter{}, "", "", false
}

regex := regexp.MustCompile(`title(.*): (.*)`)
match := regex.FindStringSubmatch(splitContents[1])

if match == nil {
return Frontmatter{}, "", false
return Frontmatter{}, "", "", false
}

frontmatterSplit = splitContents[1]
Expand All @@ -234,7 +245,7 @@ func (p *Parser) ParseMarkdownContent(filecontent string) (Frontmatter, string,
p.ErrorLogger.Fatal(err)
}

return parsedFrontmatter, parsedMarkdown.String(), true
return parsedFrontmatter, parsedMarkdown.String(), markdown, true
}

func (p *Parser) DateParse(date string) time.Time {
Expand Down
12 changes: 6 additions & 6 deletions pkg/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ func TestAddFileandRender(t *testing.T) {
TagsMap: make(map[template.URL][]parser.TemplateData),
ErrorLogger: got_parser.ErrorLogger,
}
sample_frontmatter, _, parseSuccess := got_parser.ParseMarkdownContent(string(inputMd))
sample_frontmatter, _, markdownContent, parseSuccess := got_parser.ParseMarkdownContent(string(inputMd))
sample_body := "sample_body"
if !parseSuccess {
return
}

filename := "testpost.md"
fileurl := "posts/testpost.html"
fileurl := "testpost.html"
want_parser.MdFilesName = append(want_parser.MdFilesName, filename)
want_parser.MdFilesPath = append(want_parser.MdFilesPath, filename)
want_page := parser.TemplateData{
Expand All @@ -56,7 +56,7 @@ func TestAddFileandRender(t *testing.T) {
}
want_parser.LayoutConfig = want_layout

want_parser.Templates[template.URL("posts/testpost.html")] = want_page
want_parser.Templates[template.URL("testpost.html")] = want_page
for _, tag := range sample_frontmatter.Tags {
want_parser.TagsMap[template.URL(tag)] = append(want_parser.TagsMap[template.URL(tag)], want_page)
}
Expand All @@ -65,7 +65,7 @@ func TestAddFileandRender(t *testing.T) {
want_parser.Posts = append(want_parser.Posts, want_page)
}

got_parser.AddFile("", filename, sample_frontmatter, sample_body)
got_parser.AddFile("", filename, sample_frontmatter, markdownContent, sample_body)

if !reflect.DeepEqual(got_parser, want_parser) {
t.Errorf("want %v; \ngot %v", want_parser, got_parser)
Expand All @@ -86,7 +86,7 @@ func TestParseMarkdownContent(t *testing.T) {
t.Errorf("%v", err)
}

_, body_got, parseSuccess := p.ParseMarkdownContent(string(inputMd))
_, body_got, _, parseSuccess := p.ParseMarkdownContent(string(inputMd))

if parseSuccess {

Expand All @@ -106,7 +106,7 @@ func TestParseMarkdownContent(t *testing.T) {
t.Errorf("%v", err)
}

frontmatter_got, _, parseSuccess := p.ParseMarkdownContent(string(inputMd))
frontmatter_got, _, _, parseSuccess := p.ParseMarkdownContent(string(inputMd))

if !parseSuccess {
frontmatter_want := parser.Frontmatter{
Expand Down
6 changes: 4 additions & 2 deletions pkg/parser/zettel_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type Note struct {
Date int64
Frontmatter Frontmatter
Body template.HTML
MarkdownBody string
LinkedNoteURLs []template.URL
}

Expand Down Expand Up @@ -44,11 +45,11 @@ func (p *Parser) BackLinkParser() {
noteTitle := strings.Trim(backlink, "[]")

referenceCompleteURL, err := p.ValidateBackLink(noteTitle)
if err != nil{
if err != nil {
p.ErrorLogger.Fatal(err)
} else {
// creating anchor tag reference for parsed markdown
anchorReference := fmt.Sprintf(`<a href="/%s">%s</a>`, referenceCompleteURL, noteTitle)
anchorReference := fmt.Sprintf(`<a id="zettel-reference" href="/%s">%s</a>`, referenceCompleteURL, noteTitle)
noteBody = strings.ReplaceAll(noteBody, backlink, anchorReference)

// fmt.Println(note.LinkedNoteURLs)
Expand All @@ -61,6 +62,7 @@ func (p *Parser) BackLinkParser() {
Date: note.Date,
Frontmatter: note.Frontmatter,
Body: template.HTML(noteBody),
MarkdownBody: note.MarkdownBody,
LinkedNoteURLs: note.LinkedNoteURLs,
}

Expand Down
97 changes: 89 additions & 8 deletions site/layout/note.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
{{template "header" .}}
<article>
<section class="body">
{{ if eq $PageData.Frontmatter.Type "post" }}
{{ if eq $PageData.Frontmatter.Type "note" }}
<div class="post-description">
<h1>{{ $PageData.Frontmatter.Title }}</h1>
<div class="authors-paceholder">
Expand All @@ -23,20 +23,16 @@ <h1>{{ $PageData.Frontmatter.Title }}</h1>
{{ end }}
</p>
</div>
<div class="tags-paceholder">
{{range $PageData.Frontmatter.Tags}}
<div class="tag">
<a href="/tags/{{.}}.html">{{.}}</a>
</div>
{{end}}
</div>
</div>
{{ else }}
{{ end }}
{{$PageData.Body}}
</section>
<hr />
<section class="posts">
{{ $CurratedNotes := index .DeepDataMerge.LinkStore .PageURL}}
{{ if eq (len $CurratedNotes ) 0 }}
{{ else }}
<h3>Related Posts</h3>
{{range index .DeepDataMerge.LinkStore .PageURL }}
<a class="post-card" href="/{{ .CompleteURL }}">
Expand All @@ -47,9 +43,94 @@ <h4>{{ .Frontmatter.Title }}</h4>
</div>
</a>
{{end}}
{{ end }}
</section>
</article>
{{template "footer" .}}

<script>
document.querySelectorAll('a:not(.post-card):not(.navitem)').forEach(function(anchor) {


var divWidth = 200; // Assume the width of the div
var divHeight = 100; // Assume the height of the div
anchor.addEventListener('mouseover', function(e) {
var div = document.createElement('div');
div.id = "hoverDiv"
div.style.position = 'fixed';

div.style.maxWidth = '25rem';
div.style.left = e.clientX + 'px';
div.style.top = e.clientY + 'px';

var left = e.clientX;
var top = e.clientY;
if (left + divWidth > document.innerWidth) {
left = window.innerWidth - divWidth;
}
if (top + divHeight > document.innerHeight) {
top = window.innerHeight - divHeight;
}

div.style.left = left + 'px';
div.style.top = top + 'px';

const url = "/static/noteindex.json"
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
// check if the value of the anchor tag <a>THIS ONE</a>
// has a match in the data.Frontmatter.Title

for (key in data) {
title = data[key]["Frontmatter"]["Title"];
if (title == anchor.innerHTML) {
// Create a new heading element
var heading = document.createElement('h4');
var mdBody = document.createElement('p');
var fileDate = document.createElement('p');
fileDate.className = "date"

heading.textContent = title;
mdBody.textContent = data[key]["MarkdownBody"];
fileDate.textContent = `Created on ${data[key]["Frontmatter"]["Date"]}`

div.appendChild(heading);
div.appendChild(mdBody);
div.appendChild(fileDate)

document.body.appendChild(div);
// Append the div to the body of the current document
}
}
})
.catch((error) => {
console.error(
"There was a problem with the fetch operation:",
error,
);
})
});

anchor.addEventListener('mouseout', function(e) {
console.log("JKSHKD")
var hoverDivs = document.querySelectorAll('#hoverDiv');
// kill all hoverDiv elements
hoverDivs.forEach(function(hoverDiv) {
hoverDiv.remove();
});
});

});



</script>
</body>

</html>
Expand Down
34 changes: 0 additions & 34 deletions site/layout/notes/note.layout

This file was deleted.

Loading

0 comments on commit 35c38b3

Please sign in to comment.