InfoDisplaySettingsViewModel.swift 1017 B

123456789101112131415161718192021222324252627282930313233343536
  1. // LoopFollow
  2. // InfoDisplaySettingsViewModel.swift
  3. import Foundation
  4. import SwiftUI
  5. class InfoDisplaySettingsViewModel: ObservableObject {
  6. @Published var items: [InfoDisplayItem]
  7. init() {
  8. items = Storage.shared.infoDisplayItems.value
  9. }
  10. func move(from source: IndexSet, to destination: Int) {
  11. items.move(fromOffsets: source, toOffset: destination)
  12. persist()
  13. }
  14. /// A binding to a single item, looked up by id so it survives reordering.
  15. /// Writes persist to Storage immediately.
  16. func binding(for id: Int) -> Binding<InfoDisplayItem> {
  17. Binding(
  18. get: { self.items.first(where: { $0.id == id }) ?? self.items[0] },
  19. set: { newValue in
  20. guard let index = self.items.firstIndex(where: { $0.id == id }) else { return }
  21. self.items[index] = newValue
  22. self.persist()
  23. }
  24. )
  25. }
  26. private func persist() {
  27. Storage.shared.infoDisplayItems.value = items
  28. }
  29. }