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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package mailtext

// HTML-to-text conversion for the text/llm renderings.
//
// Marketing mail and forge notifications are HTML documents whose text content
// is a small fraction of their bytes: tracking pixels, ld+json blobs, layout
// tables and multi-hundred-character unsubscribe URLs make up the rest. Handing
// that to a language model wastes most of the context window on markup.
//
// The conversion keeps what carries meaning — prose, block structure, and the
// targets of links — and drops the rest. Links are the subtle part: stripping
// them entirely would lose the actual payload of a notification mail, but
// inlining every href costs more tokens than the prose it decorates. So link
// text stays in place with a reference marker, and the URLs are collected into
// a table at the end, where identical targets share one entry.

import (
	"fmt"
	"strings"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
)

// dropElements are elements whose entire subtree carries no reading value.
// head is dropped wholesale: <title> duplicates the subject line we already
// print in the header block, and everything else in there is metadata.
var dropElements = map[atom.Atom]bool{
	atom.Script:   true,
	atom.Style:    true,
	atom.Head:     true,
	atom.Noscript: true,
	atom.Template: true,
	atom.Iframe:   true,
	atom.Object:   true,
	atom.Svg:      true,
}

// blockElements introduce a line break before and after their content.
// The set is deliberately coarse: exact CSS display semantics do not matter
// once the output is plain text, only that logical blocks stay separated.
var blockElements = map[atom.Atom]bool{
	atom.P: true, atom.Div: true, atom.Section: true, atom.Article: true,
	atom.Header: true, atom.Footer: true, atom.Nav: true, atom.Aside: true,
	atom.H1: true, atom.H2: true, atom.H3: true,
	atom.H4: true, atom.H5: true, atom.H6: true,
	atom.Ul: true, atom.Ol: true, atom.Li: true,
	atom.Table: true, atom.Tr: true, atom.Thead: true, atom.Tbody: true,
	atom.Dl: true, atom.Dt: true, atom.Dd: true,
	atom.Pre: true, atom.Hr: true, atom.Form: true, atom.Fieldset: true,
}

// htmlConverter accumulates output while walking the document.
type htmlConverter struct {
	buf strings.Builder

	// links maps a URL to its reference number, so that a URL repeated
	// throughout a document (a logo linking home, say) costs one table entry.
	links     map[string]int
	linkOrder []string

	// quoteDepth > 0 while inside a <blockquote>. Quoted replies are almost
	// always text the reader has already seen, so they are summarised rather
	// than reproduced.
	quoteDepth int
}

// HTMLToText renders an HTML document as plain text with a trailing link table.
// A document that fails to parse is not an error worth propagating — the caller
// wants something readable, so the raw string is returned as a last resort.
func HTMLToText(doc string) string {
	root, err := html.Parse(strings.NewReader(doc))
	if err != nil {
		return doc
	}
	c := &htmlConverter{links: make(map[string]int)}
	c.walk(root)

	text := collapseBlankLines(c.buf.String())
	text = strings.TrimSpace(text)

	if len(c.linkOrder) == 0 {
		return text
	}
	var out strings.Builder
	out.WriteString(text)
	out.WriteString("\n\nLinks:\n")
	for i, u := range c.linkOrder {
		fmt.Fprintf(&out, "  [%d] %s\n", i+1, u)
	}
	return strings.TrimRight(out.String(), "\n")
}

// walk emits the text of n and its children.
func (c *htmlConverter) walk(n *html.Node) {
	switch n.Type {
	case html.TextNode:
		c.writeText(n.Data)
		return
	case html.ElementNode:
		if dropElements[n.DataAtom] {
			return
		}
		if n.DataAtom == atom.Img {
			c.writeImage(n)
			return
		}
		if n.DataAtom == atom.Br {
			c.buf.WriteString("\n")
			return
		}
		if n.DataAtom == atom.Blockquote {
			c.writeQuote(n)
			return
		}
		if n.DataAtom == atom.A {
			c.writeAnchor(n)
			return
		}
		if blockElements[n.DataAtom] {
			c.newline()
			c.walkChildren(n)
			c.newline()
			return
		}
	case html.CommentNode, html.DoctypeNode:
		return
	}
	c.walkChildren(n)
}

func (c *htmlConverter) walkChildren(n *html.Node) {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		c.walk(child)
	}
}

// writeText appends a text node, collapsing internal whitespace runs. HTML
// treats any run of whitespace as a single space, and email HTML is usually
// pretty-printed with generous indentation, so preserving it would add
// thousands of meaningless spaces.
func (c *htmlConverter) writeText(s string) {
	if strings.TrimSpace(s) == "" {
		// Whitespace between elements still separates words, but must not
		// accumulate into blank lines.
		if s != "" && !c.endsWithSpace() {
			c.buf.WriteString(" ")
		}
		return
	}
	c.buf.WriteString(CollapseSpaces(s))
}

// writeImage renders an image as its alt text. Tracking pixels — 1x1 images
// whose only purpose is to report that the mail was opened — carry no alt text
// and are dropped, as are purely decorative spacer images.
func (c *htmlConverter) writeImage(n *html.Node) {
	if isTrackingPixel(n) {
		return
	}
	alt := strings.TrimSpace(attr(n, "alt"))
	if alt == "" {
		return
	}
	c.buf.WriteString("[image: " + CollapseSpaces(alt) + "]")
}

// writeAnchor emits the link text followed by a reference marker.
//
// Anchors whose href is missing, or is a fragment or javascript: URI, are
// emitted as plain text: they cannot be followed outside a browser session, so
// a reference number for them would be noise.
func (c *htmlConverter) writeAnchor(n *html.Node) {
	href := strings.TrimSpace(attr(n, "href"))
	start := c.buf.Len()
	c.walkChildren(n)
	wroteText := strings.TrimSpace(c.buf.String()[start:]) != ""

	if href == "" || strings.HasPrefix(href, "#") ||
		strings.HasPrefix(strings.ToLower(href), "javascript:") {
		return
	}
	num, seen := c.links[href]
	if !seen {
		c.linkOrder = append(c.linkOrder, href)
		num = len(c.linkOrder)
		c.links[href] = num
	}
	// An anchor wrapping only an image or nothing at all still has a target
	// worth recording, so give it a visible anchor to attach the marker to.
	if !wroteText {
		c.buf.WriteString("[link]")
	}
	fmt.Fprintf(&c.buf, " [%d]", num)
}

// writeQuote replaces a quoted passage with a one-line summary. The reader of
// a thread has seen the quoted text already; what matters is that a quote was
// present and roughly how much of it, not its contents.
func (c *htmlConverter) writeQuote(n *html.Node) {
	sub := &htmlConverter{links: c.links, linkOrder: c.linkOrder,
		quoteDepth: c.quoteDepth + 1}
	sub.walkChildren(n)
	// Links found inside the quote stay registered, so that a URL mentioned
	// only in quoted text still resolves if it is referenced elsewhere.
	c.linkOrder = sub.linkOrder

	inner := strings.TrimSpace(collapseBlankLines(sub.buf.String()))
	if inner == "" {
		return
	}
	c.newline()
	lines := strings.Split(inner, "\n")
	first := strings.TrimSpace(lines[0])
	if len(first) > 70 {
		first = first[:70] + "…"
	}
	if len(lines) == 1 {
		c.buf.WriteString("> " + first)
	} else {
		fmt.Fprintf(&c.buf, "> %s […quoted, %d lines]", first, len(lines))
	}
	c.newline()
}

// newline appends a line break unless the buffer already ends with one.
func (c *htmlConverter) newline() {
	s := c.buf.String()
	if s == "" {
		return
	}
	trimmed := strings.TrimRight(s, " \t")
	if strings.HasSuffix(trimmed, "\n") {
		// Normalise away any trailing spaces before the newline.
		c.buf.Reset()
		c.buf.WriteString(trimmed)
		return
	}
	c.buf.Reset()
	c.buf.WriteString(trimmed)
	c.buf.WriteString("\n")
}

func (c *htmlConverter) endsWithSpace() bool {
	s := c.buf.String()
	if s == "" {
		return true
	}
	last := s[len(s)-1]
	return last == ' ' || last == '\n' || last == '\t'
}

// isTrackingPixel reports whether an <img> is a 1x1 (or smaller) beacon.
func isTrackingPixel(n *html.Node) bool {
	w, hasW := smallDimension(attr(n, "width"))
	h, hasH := smallDimension(attr(n, "height"))
	if hasW && hasH {
		return w && h
	}
	// A single dimension of 1 is enough of a signal; legitimate images are not
	// one pixel wide.
	return (hasW && w) || (hasH && h)
}

// smallDimension parses an HTML dimension attribute and reports whether it is
// at most one pixel. The second return distinguishes "absent or unparseable"
// from "present and large".
func smallDimension(s string) (small, present bool) {
	s = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(s), "px"))
	if s == "" {
		return false, false
	}
	var v int
	if _, err := fmt.Sscanf(s, "%d", &v); err != nil {
		return false, false
	}
	return v <= 1, true
}

func attr(n *html.Node, name string) string {
	for _, a := range n.Attr {
		if strings.EqualFold(a.Key, name) {
			return a.Val
		}
	}
	return ""
}

// CollapseSpaces replaces runs of whitespace with a single space, per the HTML
// whitespace model.
func CollapseSpaces(s string) string {
	var b strings.Builder
	b.Grow(len(s))
	space := false
	for _, r := range s {
		switch r {
		case ' ', '\t', '\n', '\r', '\f', '\v', '\u00a0':
			space = true
		default:
			if space {
				b.WriteRune(' ')
			}
			space = false
			b.WriteRune(r)
		}
	}
	if space {
		b.WriteRune(' ')
	}
	return b.String()
}

// collapseBlankLines reduces runs of blank lines to a single one and strips
// trailing whitespace from each line. Table-based email layouts otherwise
// produce dozens of consecutive empty lines.
func collapseBlankLines(s string) string {
	lines := strings.Split(s, "\n")
	out := make([]string, 0, len(lines))
	blank := 0
	for _, line := range lines {
		line = strings.TrimRight(line, " \t")
		if strings.TrimSpace(line) == "" {
			blank++
			if blank > 1 {
				continue
			}
			out = append(out, "")
			continue
		}
		blank = 0
		out = append(out, line)
	}
	return strings.Join(out, "\n")
}

// PlainToText renders a text/plain body for the text/llm views, collapsing
// quoted runs the same way HTMLToText does so that both body types read alike.
func PlainToText(body string) string {
	lines := strings.Split(body, "\n")
	var out []string
	var quote []string

	flush := func() {
		if len(quote) == 0 {
			return
		}
		first := strings.TrimSpace(strings.TrimPrefix(quote[0], ">"))
		if len(first) > 70 {
			first = first[:70] + "…"
		}
		if len(quote) == 1 {
			out = append(out, "> "+first)
		} else {
			out = append(out, fmt.Sprintf("> %s […quoted, %d lines]", first, len(quote)))
		}
		quote = nil
	}

	for _, line := range lines {
		if strings.HasPrefix(strings.TrimSpace(line), ">") {
			quote = append(quote, strings.TrimSpace(line))
			continue
		}
		flush()
		out = append(out, strings.TrimRight(line, " \t"))
	}
	flush()
	return strings.TrimSpace(collapseBlankLines(strings.Join(out, "\n")))
}

// Preview renders a body as a single line of at most n runes, for listings.
func Preview(body, mime string, n int) string {
	var text string
	if mime == "text/html" {
		text = HTMLToText(body)
		// Drop the link table: a one-line Preview has no room for it.
		if i := strings.LastIndex(text, "\n\nLinks:\n"); i >= 0 {
			text = text[:i]
		}
	} else {
		text = body
	}
	text = CollapseSpaces(strings.ReplaceAll(text, "\n", " "))
	text = strings.TrimSpace(text)
	runes := []rune(text)
	if len(runes) <= n {
		return text
	}
	return strings.TrimSpace(string(runes[:n])) + "…"
}