text.go 1.2 KB

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