treebinding.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package binding
  2. // DataTreeRootID const is the value used as ID for the root of any tree binding.
  3. const DataTreeRootID = ""
  4. // DataTree is the base interface for all bindable data trees.
  5. //
  6. // Since: 2.4
  7. type DataTree interface {
  8. DataItem
  9. GetItem(id string) (DataItem, error)
  10. ChildIDs(string) []string
  11. }
  12. type treeBase struct {
  13. base
  14. ids map[string][]string
  15. items map[string]DataItem
  16. }
  17. // GetItem returns the DataItem at the specified id.
  18. func (t *treeBase) GetItem(id string) (DataItem, error) {
  19. if item, ok := t.items[id]; ok {
  20. return item, nil
  21. }
  22. return nil, errOutOfBounds
  23. }
  24. // ChildIDs returns the ordered IDs of items in this data tree that are children of the specified ID.
  25. func (t *treeBase) ChildIDs(id string) []string {
  26. if ids, ok := t.ids[id]; ok {
  27. return ids
  28. }
  29. return []string{}
  30. }
  31. func (t *treeBase) appendItem(i DataItem, id, parent string) {
  32. t.items[id] = i
  33. ids, ok := t.ids[parent]
  34. if !ok {
  35. ids = make([]string, 0)
  36. }
  37. for _, in := range ids {
  38. if in == id {
  39. return
  40. }
  41. }
  42. t.ids[parent] = append(ids, id)
  43. }
  44. func (t *treeBase) deleteItem(id, parent string) {
  45. delete(t.items, id)
  46. ids, ok := t.ids[parent]
  47. if !ok {
  48. return
  49. }
  50. off := -1
  51. for i, id2 := range ids {
  52. if id2 == id {
  53. off = i
  54. break
  55. }
  56. }
  57. if off == -1 {
  58. return
  59. }
  60. t.ids[parent] = append(ids[:off], ids[off+1:]...)
  61. }
  62. func parentIDFor(id string, ids map[string][]string) string {
  63. for parent, list := range ids {
  64. for _, child := range list {
  65. if child == id {
  66. return parent
  67. }
  68. }
  69. }
  70. return ""
  71. }