all repos — flounder @ 2e24c3a6f64f2e2f8a9e2179e8b692dd6b13de54

A small site builder for the Gemini protocol

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>\n")
20			}
21		} else if list {
22			list = false
23			fmt.Fprint(&b, "</ul>\n")
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, "<p><a href='%s'>%s</a></p>\n", url, name)
34		case gemini.LinePreformattingToggle:
35			pre = !pre
36			if pre {
37				fmt.Fprint(&b, "<pre>\n")
38			} else {
39				fmt.Fprint(&b, "</pre>\n")
40			}
41		case gemini.LinePreformattedText:
42			text := string(l.(gemini.LinePreformattedText))
43			fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
44		case gemini.LineHeading1:
45			text := string(l.(gemini.LineHeading1))
46			fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
47		case gemini.LineHeading2:
48			text := string(l.(gemini.LineHeading2))
49			fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
50		case gemini.LineHeading3:
51			text := string(l.(gemini.LineHeading3))
52			fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
53		case gemini.LineListItem:
54			text := string(l.(gemini.LineListItem))
55			fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
56		case gemini.LineQuote:
57			text := string(l.(gemini.LineQuote))
58			fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
59		case gemini.LineText:
60			text := string(l.(gemini.LineText))
61			if text == "" {
62				fmt.Fprint(&b, "<br>\n")
63			} else {
64				fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
65			}
66		}
67	}
68	if pre {
69		fmt.Fprint(&b, "</pre>\n")
70	}
71	if list {
72		fmt.Fprint(&b, "</ul>\n")
73	}
74	return b.String()
75}