text.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package app
  2. import (
  3. "context"
  4. "html"
  5. "io"
  6. "github.com/maxence-charriere/go-app/v9/pkg/errors"
  7. )
  8. // Text creates a simple text element.
  9. func Text(v any) UI {
  10. return &text{value: toString(v)}
  11. }
  12. type text struct {
  13. disp Dispatcher
  14. jsvalue Value
  15. parentElem UI
  16. value string
  17. }
  18. func (t *text) Kind() Kind {
  19. return SimpleText
  20. }
  21. func (t *text) JSValue() Value {
  22. return t.jsvalue
  23. }
  24. func (t *text) Mounted() bool {
  25. return t.jsvalue != nil && t.getDispatcher() != nil
  26. }
  27. func (t *text) name() string {
  28. return "text"
  29. }
  30. func (t *text) self() UI {
  31. return t
  32. }
  33. func (t *text) setSelf(n UI) {
  34. }
  35. func (t *text) getContext() context.Context {
  36. return context.TODO()
  37. }
  38. func (t *text) getDispatcher() Dispatcher {
  39. return t.disp
  40. }
  41. func (t *text) getAttributes() attributes {
  42. return nil
  43. }
  44. func (t *text) getEventHandlers() eventHandlers {
  45. return nil
  46. }
  47. func (t *text) getParent() UI {
  48. return t.parentElem
  49. }
  50. func (t *text) setParent(p UI) {
  51. t.parentElem = p
  52. }
  53. func (t *text) getChildren() []UI {
  54. return nil
  55. }
  56. func (t *text) mount(d Dispatcher) error {
  57. if t.Mounted() {
  58. return errors.New("mounting ui element failed").
  59. Tag("reason", "already mounted").
  60. Tag("kind", t.Kind()).
  61. Tag("name", t.name()).
  62. Tag("value", t.value)
  63. }
  64. t.disp = d
  65. t.jsvalue = Window().createTextNode(t.value)
  66. return nil
  67. }
  68. func (t *text) dismount() {
  69. t.jsvalue = nil
  70. }
  71. func (t *text) canUpdateWith(n UI) bool {
  72. _, ok := n.(*text)
  73. return ok
  74. }
  75. func (t *text) updateWith(n UI) error {
  76. if !t.Mounted() {
  77. return nil
  78. }
  79. o, _ := n.(*text)
  80. if t.value != o.value {
  81. t.value = o.value
  82. t.JSValue().setNodeValue(o.value)
  83. }
  84. return nil
  85. }
  86. func (t *text) preRender(Page) {
  87. }
  88. func (t *text) onComponentEvent(any) {
  89. }
  90. func (t *text) html(w io.Writer) {
  91. w.Write([]byte(html.EscapeString(t.value)))
  92. }
  93. func (t *text) htmlWithIndent(w io.Writer, indent int) {
  94. writeIndent(w, indent)
  95. w.Write([]byte(html.EscapeString(t.value)))
  96. }