base.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package budget2
  2. type Instance struct {
  3. ID int `json:"i"`
  4. Value map[string]interface{} `json:"v"`
  5. Cache map[string]interface{} `json:"-"`
  6. }
  7. type Interface interface {
  8. Name(context *Context) string
  9. DefaultValue() map[string]interface{}
  10. ControlNames(context *Context) []string
  11. Controls(i Interface, context *Context) []Control
  12. GetValue(i Interface, name string, context *Context) interface{}
  13. GetControl(name string, context *Context) *Control
  14. Handle(i Interface, context *Context, name string, typ string, value interface{}) error
  15. }
  16. type Object struct {
  17. }
  18. func (Object) Name(context *Context) string {
  19. return ""
  20. }
  21. func (Object) DefaultValue() map[string]interface{} {
  22. return map[string]interface{}{}
  23. }
  24. func (Object) ControlNames(context *Context) []string {
  25. return []string{}
  26. }
  27. func (Object) Controls(i Interface, context *Context) []Control {
  28. controls := make([]Control, 0)
  29. for _, name := range i.ControlNames(context) {
  30. control := i.GetControl(name, context)
  31. if control != nil {
  32. controls = append(controls, *control)
  33. }
  34. }
  35. return controls
  36. }
  37. func (Object) GetValue(i Interface, name string, context *Context) interface{} {
  38. if value, ok := context.CurrentInstance().Value[name]; ok {
  39. return value
  40. }
  41. if value, ok := i.DefaultValue()[name]; ok {
  42. context.CurrentInstance().Value[name] = value
  43. return value
  44. }
  45. if value, ok := context.CurrentInstance().Cache[name]; ok {
  46. context.CurrentInstance().Value[name] = value
  47. return value
  48. }
  49. return nil
  50. }
  51. func (Object) GetControl(name string, context *Context) *Control {
  52. return nil
  53. }
  54. func (Object) Handle(i Interface, context *Context, name string, typ string, value interface{}) error {
  55. control := i.GetControl(name, context)
  56. if control != nil {
  57. context.CurrentInstance().Value[name] = control.Handle(typ, value, context)
  58. }
  59. return nil
  60. }