bombadillo/page.go

108 lines
2.6 KiB
Go
Raw Normal View History

package main
2019-09-12 05:53:36 +00:00
import (
"strings"
)
//------------------------------------------------\\
// + + + T Y P E S + + + \\
//--------------------------------------------------\\
2019-11-10 19:35:52 +00:00
// Page represents a visited URL's contents; including
// the raw content, wrapped content, link slice, URL,
// and the current scroll position
type Page struct {
2019-09-12 05:53:36 +00:00
WrappedContent []string
2019-11-10 18:41:12 +00:00
RawContent string
Links []string
Location Url
ScrollPosition int
}
//------------------------------------------------\\
// + + + R E C E I V E R S + + + \\
//--------------------------------------------------\\
// ScrollPositionRange may not be in actual usage....
// TODO: find where this is being used
2019-09-12 05:53:36 +00:00
func (p *Page) ScrollPositionRange(termHeight int) (int, int) {
termHeight -= 3
2019-11-10 18:41:12 +00:00
if len(p.WrappedContent)-p.ScrollPosition < termHeight {
2019-09-12 05:53:36 +00:00
p.ScrollPosition = len(p.WrappedContent) - termHeight
}
if p.ScrollPosition < 0 {
p.ScrollPosition = 0
}
var end int
if len(p.WrappedContent) < termHeight {
end = len(p.WrappedContent)
} else {
end = p.ScrollPosition + termHeight
}
2019-09-12 05:53:36 +00:00
return p.ScrollPosition, end
}
2019-11-10 19:35:52 +00:00
// WrapContent performs a hard wrap to the requested
// width and updates the WrappedContent
// of the Page struct width a string slice
// of the wrapped data
2019-09-12 05:53:36 +00:00
func (p *Page) WrapContent(width int) {
counter := 0
var content strings.Builder
escape := false
content.Grow(len(p.RawContent))
for _, ch := range []rune(p.RawContent) {
if escape {
if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') {
escape = false
}
continue
}
if ch == '\n' {
content.WriteRune(ch)
counter = 0
} else if ch == '\t' {
2019-11-10 18:41:12 +00:00
if counter+4 < width {
content.WriteString(" ")
counter += 4
} else {
content.WriteRune('\n')
counter = 0
}
} else if ch == '\r' || ch == '\v' || ch == '\b' || ch == '\f' {
// Get rid of control characters we dont want
continue
} else if ch == 27 {
escape = true
continue
2019-09-12 05:53:36 +00:00
} else {
if counter < width {
content.WriteRune(ch)
counter++
} else {
content.WriteRune('\n')
counter = 0
if p.Location.Mime == "1" {
2019-11-10 18:41:12 +00:00
spacer := " "
content.WriteString(spacer)
counter += len(spacer)
2019-09-12 05:53:36 +00:00
}
content.WriteRune(ch)
2019-09-12 05:53:36 +00:00
}
}
}
p.WrappedContent = strings.Split(content.String(), "\n")
2019-09-12 05:53:36 +00:00
}
//------------------------------------------------\\
// + + + F U N C T I O N S + + + \\
//--------------------------------------------------\\
// MakePage returns a Page struct with default values
2019-09-12 05:53:36 +00:00
func MakePage(url Url, content string, links []string) Page {
p := Page{make([]string, 0), content, links, url, 0}
return p
}