summaryrefslogtreecommitdiff
path: root/gopher/gophermap/htmlconv/convert.go
blob: a6696016d12e1c437577f99ef4b346739c31766e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package htmlconv

import (
	"bytes"
	"html/template"
	"io"
	"strings"

	"tildegit.org/tjp/sliderule/gopher"
	"tildegit.org/tjp/sliderule/internal/types"
)

// Convert writes html to a writer  from the provided gophermap document.
//
// Templates can be provided to override the output for different line types.
// The supported templates are:
//   - "header' is called before any lines and is passed the full document.
//   - "footer" is called after all lines and is passed the full document.
//   - "message" is called for every group of consecutive info-message lines. It is
//     passed a string of all the display components of the included lines, joined by
//     newline characters.
//   - "image" is called for all lines of any of the following types: GifFileType,
//     ImageFileType, BitmapType, PngImageFileType. It is passed the gopher.MapItem.
//   - "link" is called for all lines of any other type not yet mentioned, and is passed
//     the gopher.MapItem.
//
// There are already default implementations of each of these templates, so the "overrides"
// argument can be nil or include just a subset of the supported templates.
func Convert(wr io.Writer, doc gopher.MapDocument, overrides *template.Template) error {
	tmpl, err := baseTmpl.Clone()
	if err != nil {
		return err
	}

	tmpl, err = addOverrides(tmpl, overrides)
	if err != nil {
		return err
	}

	for _, item := range renderItems(doc) {
		if err := tmpl.ExecuteTemplate(wr, item.template, item.object); err != nil {
			return err
		}
	}

	return nil
}

type renderItem struct {
	template string
	object   any
}

type renderRef struct {
	Type     types.Status
	Display  string
	Selector template.URL
	Hostname string
	Port     string
}

func refItem(item gopher.MapItem) renderRef {
	return renderRef{
		Type:     item.Type,
		Display:  item.Display,
		Selector: template.URL(item.Selector),
		Hostname: item.Hostname,
		Port:     item.Port,
	}
}

func renderItems(doc gopher.MapDocument) []renderItem {
	out := make([]renderItem, 0, len(doc))
	out = append(out, renderItem{
		template: "header",
		object:   doc,
	})
	inMsg := false
	msg := &bytes.Buffer{}
	var currentHost, currentPort string

	for _, mapItem := range doc {
		switch mapItem.Type {
		case gopher.InfoMessageType:
			if inMsg {
				_, _ = msg.WriteString("\n")
			} else {
				msg.Reset()
			}
			_, _ = msg.WriteString(mapItem.Display)
			inMsg = true

			if currentHost == "" {
				currentHost = mapItem.Hostname
			}
			if currentPort == "" {
				currentPort = mapItem.Port
			}
		case gopher.GifFileType, gopher.ImageFileType, gopher.BitmapType, gopher.PngImageFileType:
			if inMsg {
				out = append(out, renderItem{
					template: "message",
					object:   msg.String(),
				})
				inMsg = false
			}
			out = append(out, renderItem{
				template: "image",
				object:   refItem(mapItem),
			})
		default:
			if inMsg {
				out = append(out, renderItem{
					template: "message",
					object:   msg.String(),
				})
				inMsg = false
			}
			out = append(out, renderItem{
				template: "link",
				object:   refItem(mapItem),
			})
		}
	}

	if inMsg {
		out = append(out, renderItem{
			template: "message",
			object:   msg.String(),
		})
	}

	simplifyLinks(out, currentHost, currentPort)

	return append(out, renderItem{
		template: "footer",
		object:   doc,
	})
}

func simplifyLinks(items []renderItem, currentHost, currentPort string) {
	for i, item := range items {
		if item.template != "link" && item.template != "image" {
			continue
		}

		m := item.object.(renderRef)
		if m.Hostname == currentHost && m.Port == currentPort {
			m.Hostname = ""
			m.Port = ""
			m.Selector = template.URL(strings.TrimPrefix(string(m.Selector), "URL:"))
			items[i].object = m
		}
	}
}

func addOverrides(base *template.Template, overrides *template.Template) (*template.Template, error) {
	if overrides == nil {
		return base, nil
	}

	tmpl := base
	var err error
	for _, override := range overrides.Templates() {
		tmpl, err = tmpl.AddParseTree(override.Name(), override.Tree)
		if err != nil {
			return nil, err
		}
	}

	return tmpl, nil
}

var baseTmpl = template.Must(template.New("htmlconv").Parse(`
{{ define "header" -}}
<!DOCTYPE html>
<html><body class="gophermap">
{{- end }}

{{ define "message" -}}
<pre class="gophermap">{{.}}
</pre>
{{- end }}

{{ define "link" -}}
<p class="gophermap"><a class="gophermap" {{ if .Hostname | and .Port }}href="gopher://{{.Hostname}}:{{.Port}}{{.Selector}}"{{ else }}href="{{.Selector}}"{{ end }}>{{.Display}}</a></p>
{{- end }}

{{ define "image" -}}
<p class="gophermap"><img class="gophermap" {{ if .Hostname | and .Port }}src="gopher://{{.Hostname}}:{{.Port}}{{.Selector}}"{{ else }}src="{{.Selector}}"{{ end }} alt="{{.Display}}"/></p>
{{- end }}

{{ define "footer" -}}
</body></html>
{{ end }}
`))