91 lines
3.0 KiB
Swift
91 lines
3.0 KiB
Swift
//
|
|
// SelectorGroupHandlerable.swift
|
|
// VDS
|
|
//
|
|
// Created by Matt Bruce on 8/23/22.
|
|
//
|
|
|
|
import Foundation
|
|
import UIKit
|
|
|
|
///MARK: Groups that allow anything selected
|
|
public protocol SelectorGroupModelHandlerable: ModelHandlerable, Disabling, Surfaceable where ModelType: SelectorGroupModelable {
|
|
associatedtype ModelHandlerType: ModelHandlerable where ModelType.SelectorModelType == ModelHandlerType.ModelType, ModelHandlerType: UIControl
|
|
var selectorViews: [ModelHandlerType] { get set }
|
|
func didSelect(_ selectedControl: ModelHandlerType)
|
|
func createModelHandler(selector: ModelHandlerType.ModelType) -> ModelHandlerType
|
|
}
|
|
|
|
extension SelectorGroupModelHandlerable {
|
|
|
|
public func findSelectorView(inputId: String?) -> ModelHandlerType? {
|
|
return selectorViews.first(where: { existingSelectorView in
|
|
return existingSelectorView.model.inputId == inputId
|
|
})
|
|
}
|
|
|
|
public func updateSelectors(){
|
|
let selectors = model.selectors.compactMap { existing in
|
|
return existing.copyWith {
|
|
$0.disabled = disabled
|
|
$0.surface = surface
|
|
}
|
|
}
|
|
model.selectors = selectors
|
|
}
|
|
|
|
public func getCachedSelector(viewModel: ModelHandlerType.ModelType) -> ModelHandlerType.ModelType? {
|
|
if let index = model.selectors.firstIndex(where: { element in
|
|
return element.inputId == viewModel.inputId
|
|
}) {
|
|
return model.selectors[index]
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
public func replace(viewModel: ModelHandlerType.ModelType){
|
|
if let index = model.selectors.firstIndex(where: { element in
|
|
return element.inputId == viewModel.inputId
|
|
}) {
|
|
model.selectors[index] = viewModel
|
|
}
|
|
}
|
|
|
|
public func createModelHandler(selector: ModelHandlerType.ModelType) -> ModelHandlerType {
|
|
//create view
|
|
let newSelectorView = ModelHandlerType(with: selector)
|
|
|
|
//add model update to the subscribers
|
|
newSelectorView.handlerPublisher()
|
|
.sink { [weak self] model in
|
|
if let cached = self?.getCachedSelector(viewModel: model), newSelectorView.shouldUpdateView(viewModel: cached) {
|
|
self?.replace(viewModel: model)
|
|
}
|
|
}
|
|
.store(in: &subscribers)
|
|
|
|
//add the selectedPublisher for the change
|
|
newSelectorView
|
|
.publisher(for: .touchUpInside)
|
|
.sink { [weak self] control in
|
|
self?.didSelect(control)
|
|
}
|
|
.store(in: &subscribers)
|
|
|
|
return newSelectorView
|
|
|
|
}
|
|
|
|
}
|
|
|
|
///MARK: Groups that allow single selections
|
|
public protocol SelectorGroupSelectedModelHandlerable: SelectorGroupModelHandlerable where ModelType: SelectorGroupSelectedModelable { }
|
|
|
|
extension SelectorGroupSelectedModelHandlerable {
|
|
|
|
public var selectedModel: ModelHandlerType.ModelType? {
|
|
return model.selectedModel
|
|
}
|
|
}
|