kiln/html.go

77 lines
1.9 KiB
Go
Raw Normal View History

2020-10-26 19:18:26 +00:00
package main
import (
2020-11-20 17:07:38 +00:00
"bytes"
2020-10-26 19:18:26 +00:00
"fmt"
"html"
"git.sr.ht/~adnano/go-gemini"
)
// textToHTML returns the Gemini text response as HTML.
2020-11-20 17:07:38 +00:00
func textToHTML(text gemini.Text) []byte {
var b bytes.Buffer
2020-10-26 19:18:26 +00:00
var pre bool
var list bool
for _, l := range text {
if _, ok := l.(gemini.LineListItem); ok {
if !list {
list = true
2020-11-20 17:07:38 +00:00
b.WriteString("<ul>\n")
2020-10-26 19:18:26 +00:00
}
} else if list {
list = false
2020-11-20 17:07:38 +00:00
b.WriteString("</ul>\n")
2020-10-26 19:18:26 +00:00
}
switch l.(type) {
case gemini.LineLink:
link := l.(gemini.LineLink)
url := html.EscapeString(link.URL)
name := html.EscapeString(link.Name)
if name == "" {
name = url
}
fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>\n", url, name)
case gemini.LinePreformattingToggle:
pre = !pre
if pre {
2020-11-20 17:07:38 +00:00
b.WriteString("<pre>\n")
2020-10-26 19:18:26 +00:00
} else {
2020-11-20 17:07:38 +00:00
b.WriteString("</pre>\n")
2020-10-26 19:18:26 +00:00
}
case gemini.LinePreformattedText:
text := string(l.(gemini.LinePreformattedText))
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
case gemini.LineHeading1:
text := string(l.(gemini.LineHeading1))
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
case gemini.LineHeading2:
text := string(l.(gemini.LineHeading2))
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
case gemini.LineHeading3:
text := string(l.(gemini.LineHeading3))
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
case gemini.LineListItem:
text := string(l.(gemini.LineListItem))
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
case gemini.LineQuote:
text := string(l.(gemini.LineQuote))
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
case gemini.LineText:
text := string(l.(gemini.LineText))
if text == "" {
2020-11-20 17:07:38 +00:00
b.WriteString("<br>\n")
2020-10-26 19:18:26 +00:00
} else {
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
}
}
}
if pre {
2020-11-20 17:07:38 +00:00
b.WriteString("</pre>\n")
2020-10-26 19:18:26 +00:00
}
if list {
2020-11-20 17:07:38 +00:00
b.WriteString("</ul>\n")
2020-10-26 19:18:26 +00:00
}
2020-11-20 17:07:38 +00:00
return b.Bytes()
2020-10-26 19:18:26 +00:00
}