gmi2html.go (view raw)
1package main
2
3import (
4 "fmt"
5 "html"
6 "strings"
7
8 "git.sr.ht/~adnano/go-gemini"
9)
10
11func textToHTML(text gemini.Text) string {
12 var b strings.Builder
13 var pre bool
14 var list bool
15 for _, l := range text {
16 if _, ok := l.(gemini.LineListItem); ok {
17 if !list {
18 list = true
19 fmt.Fprint(&b, "<ul>")
20 }
21 } else if list {
22 list = false
23 fmt.Fprint(&b, "</ul>")
24 }
25 switch l.(type) {
26 case gemini.LineLink:
27 link := l.(gemini.LineLink)
28 url := html.EscapeString(link.URL)
29 name := html.EscapeString(link.Name)
30 if name == "" {
31 name = url
32 }
33 fmt.Fprintf(&b, "<a href='%s'>%s</a>\n", url, name)
34 case gemini.LinePreformattingToggle:
35 pre = !pre
36 if pre {
37 altText := string(l.(gemini.LinePreformattingToggle))
38 if altText != "" {
39 altText = html.EscapeString(altText)
40 fmt.Fprintf(&b, "<pre title='%s'>", altText)
41 } else {
42 fmt.Fprint(&b, "<pre>\n")
43 }
44 } else {
45 fmt.Fprint(&b, "</pre>")
46 }
47 case gemini.LinePreformattedText:
48 text := string(l.(gemini.LinePreformattedText))
49 fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
50 case gemini.LineHeading1:
51 text := string(l.(gemini.LineHeading1))
52 fmt.Fprintf(&b, "<h1>%s</h1>", html.EscapeString(text))
53 case gemini.LineHeading2:
54 text := string(l.(gemini.LineHeading2))
55 fmt.Fprintf(&b, "<h2>%s</h2>", html.EscapeString(text))
56 case gemini.LineHeading3:
57 text := string(l.(gemini.LineHeading3))
58 fmt.Fprintf(&b, "<h3>%s</h3>", html.EscapeString(text))
59 case gemini.LineListItem:
60 text := string(l.(gemini.LineListItem))
61 fmt.Fprintf(&b, "<li>%s</li>", html.EscapeString(text))
62 case gemini.LineQuote:
63 text := string(l.(gemini.LineQuote))
64 fmt.Fprintf(&b, "<blockquote>%s</blockquote>", html.EscapeString(text))
65 case gemini.LineText:
66 text := string(l.(gemini.LineText))
67 if text == "" {
68 fmt.Fprint(&b, "\n")
69 } else {
70 fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
71 }
72 }
73 }
74 if pre {
75 fmt.Fprint(&b, "</pre>")
76 }
77 if list {
78 fmt.Fprint(&b, "</ul>")
79 }
80 return b.String()
81}