text.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package element
  2. import (
  3. "golang.org/x/net/html/atom"
  4. "html"
  5. )
  6. const (
  7. TextThemeSuccess = "success"
  8. TextThemeDanger = "danger"
  9. )
  10. type (
  11. TextOption func(t *Text)
  12. Text struct {
  13. Tag atom.Atom
  14. Content string
  15. Theme string
  16. Color string
  17. Style Style
  18. }
  19. )
  20. func WithTextTheme(s string) TextOption {
  21. return func(t *Text) {
  22. t.Theme = s
  23. }
  24. }
  25. func WithTextStyle(ms map[string]string) TextOption {
  26. return func(t *Text) {
  27. t.Style = ms
  28. }
  29. }
  30. func WithTextTag(tag atom.Atom) TextOption {
  31. return func(t *Text) {
  32. t.Tag = tag
  33. }
  34. }
  35. func WithTextColor(color string) TextOption {
  36. return func(t *Text) {
  37. t.Color = color
  38. }
  39. }
  40. func (text *Text) Html() string {
  41. return text.String()
  42. }
  43. func (text *Text) String() string {
  44. var className string
  45. if text.Style == nil {
  46. text.Style = make(map[string]string)
  47. }
  48. if text.Color != "" {
  49. text.Style["color"] = text.Color
  50. }
  51. if text.Tag == 0 {
  52. text.Tag = atom.Span
  53. }
  54. if text.Theme != "" {
  55. className = "text-" + text.Theme
  56. }
  57. return renderTag(text.Tag.String(), Attrs{
  58. "class": className,
  59. "style": text.Style.String(),
  60. }, html.EscapeString(text.Content))
  61. }
  62. func NewText(s string, opts ...TextOption) *Text {
  63. txt := &Text{Content: s, Tag: atom.Span}
  64. for _, cb := range opts {
  65. cb(txt)
  66. }
  67. return txt
  68. }