uv_context.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. //go:build js && wasm
  2. package ultraviolet
  3. import (
  4. "context"
  5. "fmt"
  6. "sync"
  7. fw "git.buran.team/main/fairwind"
  8. )
  9. type UVContext struct {
  10. ctx context.Context
  11. log *fw.Log
  12. mutex sync.Mutex
  13. factory Factory
  14. state *State
  15. source *Source
  16. values []Value
  17. router *Router
  18. }
  19. func NewUVContext(ctx context.Context, log *fw.Log, platform int, routing Routing) (*UVContext, error) {
  20. this := &UVContext{
  21. ctx: ctx,
  22. factory: NewFactory(platform),
  23. state: NewStateWithOpts(ctx),
  24. values: []Value{},
  25. }
  26. router, err := NewRouter(ctx, log, this, routing)
  27. if err != nil {
  28. return nil, fmt.Errorf("can't create uv-context: %w", err)
  29. }
  30. this.router = router
  31. this.source = NewSource(ctx, this.state)
  32. return this, nil
  33. }
  34. func (this *UVContext) Start() error {
  35. err := this.state.Start()
  36. if err != nil {
  37. return fmt.Errorf("can't start context: %w", err)
  38. }
  39. err = this.source.Start()
  40. if err != nil {
  41. return fmt.Errorf("can't start context: %w", err)
  42. }
  43. return nil
  44. }
  45. func (this *UVContext) Stop() error {
  46. err := this.state.Stop()
  47. if err != nil {
  48. return fmt.Errorf("can't stop context: %w", err)
  49. }
  50. err = this.source.Stop()
  51. if err != nil {
  52. return fmt.Errorf("can't stop context: %w", err)
  53. }
  54. for _, value := range this.values {
  55. err = value.Stop()
  56. if err != nil {
  57. return fmt.Errorf("can't stop context: %w", err)
  58. }
  59. }
  60. return nil
  61. }
  62. func (this *UVContext) Update() {
  63. this.router.Update()
  64. }
  65. func (this *UVContext) Factory() Factory {
  66. return this.factory
  67. }
  68. func (this *UVContext) Router() *Router {
  69. return this.router
  70. }
  71. func (this *UVContext) State() *State {
  72. return this.state
  73. }
  74. func (this *UVContext) Value(expression string) (Value, error) {
  75. this.mutex.Lock()
  76. defer this.mutex.Unlock()
  77. result := NewValueReactive(this.ctx, this.source, ExpressionToSelector(expression))
  78. err := result.Start()
  79. if err != nil {
  80. return nil, fmt.Errorf("can't create value: %w", err)
  81. }
  82. this.values = append(this.values, result)
  83. return result, nil
  84. }