htmgo/htmgo-site/ui/snippet.go

48 lines
1.2 KiB
Go
Raw Normal View History

2024-10-13 11:35:27 +00:00
package ui
import (
"bytes"
"fmt"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
2024-10-28 23:47:00 +00:00
"github.com/google/uuid"
2024-10-13 11:35:27 +00:00
"github.com/maddalax/htmgo/framework/h"
"strings"
)
func FormatCode(code string, customStyles ...string) string {
var buf bytes.Buffer
lexer := lexers.Get("go")
style := styles.Get("github")
formatter := html.New(
2024-10-28 15:32:50 +00:00
html.WrapLongLines(true),
html.WithLineNumbers(true),
2024-10-13 11:35:27 +00:00
html.WithCustomCSS(map[chroma.TokenType]string{
2024-10-28 23:47:00 +00:00
chroma.PreWrapper: fmt.Sprintf("font-size: 14px; padding: 12px; overflow: auto; background-color: rgb(245, 245, 245) !important; %s", strings.Join(customStyles, ";")),
2024-10-13 11:35:27 +00:00
}))
iterator, err := lexer.Tokenise(nil, code)
if err != nil {
return ""
}
err = formatter.Format(&buf, style, iterator)
return buf.String()
}
2024-10-28 15:32:50 +00:00
func CodeSnippet(code string, customStyles ...string) *h.Element {
2024-10-28 23:47:00 +00:00
id := fmt.Sprintf("code-snippet-%s", uuid.NewString())
2024-10-13 11:35:27 +00:00
return h.Div(
2024-10-28 23:47:00 +00:00
h.Class("relative"),
h.Div(
h.UnsafeRaw(code),
h.Class("hidden"),
h.Id(id),
),
CopyButton("#"+id),
h.UnsafeRaw(
FormatCode(code, customStyles...),
),
2024-10-13 11:35:27 +00:00
)
}