package formatter
import (
"fmt"
"html"
"ewintr.nl/adoc/document"
"ewintr.nl/adoc/element"
"ewintr.nl/go-kit/slugify"
)
const htmlPageTemplate = `
%s
%s
`
type HTML struct{}
func NewHTML() *HTML {
return &HTML{}
}
func (h *HTML) Format(doc *document.Document) string {
return fmt.Sprintf(htmlPageTemplate, html.EscapeString(doc.Title), h.FormatFragments(doc.Content...))
}
func (h *HTML) FormatFragments(els ...element.Element) string {
var html string
for _, el := range els {
html += h.htmlElement(el)
}
return html
}
func (h *HTML) htmlElement(el element.Element) string {
switch v := el.(type) {
case element.SubTitle:
return fmt.Sprintf("%s
\n", slugify.Slugify(v.Text()), html.EscapeString(v.Text()))
case element.SubSubTitle:
return fmt.Sprintf("%s
\n", slugify.Slugify(v.Text()), html.EscapeString(v.Text()))
case element.List:
var items []element.Element
for _, i := range v {
items = append(items, i)
}
return fmt.Sprintf("\n", h.FormatFragments(items...))
case element.ListItem:
return fmt.Sprintf("%s\n", h.FormatFragments(v...))
case element.CodeBlock:
return fmt.Sprintf("%s
", html.EscapeString(v.Text()))
case element.Paragraph:
return fmt.Sprintf("%s
\n", h.FormatFragments(v.Elements...))
case element.Strong:
return fmt.Sprintf("%s", h.FormatFragments(v...))
case element.Emphasis:
return fmt.Sprintf("%s", h.FormatFragments(v...))
case element.Code:
return fmt.Sprintf("%s
", h.FormatFragments(v...))
case element.Link:
return fmt.Sprintf("%s", v.URL, html.EscapeString(v.Title))
case element.Word:
return html.EscapeString(v.Text())
case element.WhiteSpace:
return " "
default:
return ""
}
}