SelectorViewController.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // SelectorViewController.swift
  2. // Eureka ( https://github.com/xmartlabs/Eureka )
  3. //
  4. // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
  5. //
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. import Foundation
  25. import UIKit
  26. /**
  27. * Responsible for the options passed to a selector view controller
  28. */
  29. public protocol OptionsProviderRow: TypedRowType {
  30. associatedtype OptionsProviderType: OptionsProviderConformance
  31. var optionsProvider: OptionsProviderType? { get set }
  32. var cachedOptionsData: [OptionsProviderType.Option]? { get set }
  33. }
  34. extension OptionsProviderRow where Self: BaseRow {
  35. public var options: [OptionsProviderType.Option]? {
  36. set (newValue){
  37. let optProvider = OptionsProviderType.init(array: newValue)
  38. optionsProvider = optProvider
  39. }
  40. get {
  41. return self.cachedOptionsData ?? optionsProvider?.optionsArray
  42. }
  43. }
  44. public var cachedOptionsData: [OptionsProviderType.Option]? {
  45. get {
  46. return self._cachedOptionsData as? [OptionsProviderType.Option]
  47. }
  48. set {
  49. self._cachedOptionsData = newValue
  50. }
  51. }
  52. }
  53. public protocol OptionsProviderConformance: ExpressibleByArrayLiteral {
  54. associatedtype Option: Equatable
  55. init(array: [Option]?)
  56. func options(for selectorViewController: FormViewController, completion: @escaping ([Option]?) -> Void)
  57. var optionsArray: [Option]? { get }
  58. }
  59. /// Provider of selectable options.
  60. public enum OptionsProvider<T: Equatable>: OptionsProviderConformance {
  61. /// Synchronous provider that provides array of options it was initialized with
  62. case array([T]?)
  63. /// Provider that uses closure it was initialized with to provide options. Can be synchronous or asynchronous.
  64. case lazy((FormViewController, @escaping ([T]?) -> Void) -> Void)
  65. public init(array: [T]?) {
  66. self = .array(array)
  67. }
  68. public init(arrayLiteral elements: T...) {
  69. self = .array(elements)
  70. }
  71. public func options(for selectorViewController: FormViewController, completion: @escaping ([T]?) -> Void) {
  72. switch self {
  73. case let .array(array):
  74. completion(array)
  75. case let .lazy(fetch):
  76. fetch(selectorViewController, completion)
  77. }
  78. }
  79. public var optionsArray: [T]?{
  80. switch self {
  81. case let .array(arrayData):
  82. return arrayData
  83. default:
  84. return nil
  85. }
  86. }
  87. }
  88. open class _SelectorViewController<Row: SelectableRowType, OptionsRow: OptionsProviderRow>: FormViewController, TypedRowControllerType where Row: BaseRow, Row.Cell.Value == OptionsRow.OptionsProviderType.Option {
  89. /// The row that pushed or presented this controller
  90. public var row: RowOf<Row.Cell.Value>!
  91. public var enableDeselection = true
  92. public var dismissOnSelection = true
  93. public var dismissOnChange = true
  94. public var selectableRowSetup: ((_ row: Row) -> Void)?
  95. public var selectableRowCellUpdate: ((_ cell: Row.Cell, _ row: Row) -> Void)?
  96. public var selectableRowCellSetup: ((_ cell: Row.Cell, _ row: Row) -> Void)?
  97. /// A closure to be called when the controller disappears.
  98. public var onDismissCallback: ((UIViewController) -> Void)?
  99. /// A closure that should return key for particular row value.
  100. /// This key is later used to break options by sections.
  101. public var sectionKeyForValue: ((Row.Cell.Value) -> (String))?
  102. /// A closure that returns header title for a section for particular key.
  103. /// By default returns the key itself.
  104. public var sectionHeaderTitleForKey: ((String) -> String?)? = { $0 }
  105. /// A closure that returns footer title for a section for particular key.
  106. public var sectionFooterTitleForKey: ((String) -> String?)?
  107. public var optionsProviderRow: OptionsRow {
  108. return row as! OptionsRow
  109. }
  110. override public init(style: UITableView.Style) {
  111. super.init(style: style)
  112. }
  113. override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
  114. super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
  115. }
  116. convenience public init(_ callback: ((UIViewController) -> Void)?) {
  117. self.init(nibName: nil, bundle: nil)
  118. onDismissCallback = callback
  119. }
  120. public required init?(coder aDecoder: NSCoder) {
  121. super.init(coder: aDecoder)
  122. }
  123. open override func viewDidLoad() {
  124. super.viewDidLoad()
  125. setupForm()
  126. }
  127. open func setupForm() {
  128. let optProvider = optionsProviderRow.optionsProvider
  129. optProvider?.options(for: self) { [weak self] (options: [Row.Cell.Value]?) in
  130. guard let strongSelf = self, let options = options else { return }
  131. strongSelf.optionsProviderRow.cachedOptionsData = options
  132. strongSelf.setupForm(with: options)
  133. }
  134. }
  135. open func setupForm(with options: [Row.Cell.Value]) {
  136. if let optionsBySections = optionsBySections(with: options) {
  137. for (sectionKey, options) in optionsBySections {
  138. form +++ section(with: options,
  139. header: sectionHeaderTitleForKey?(sectionKey),
  140. footer: sectionFooterTitleForKey?(sectionKey))
  141. }
  142. } else {
  143. form +++ section(with: options, header: row.title, footer: nil)
  144. }
  145. }
  146. func optionsBySections(with options: [Row.Cell.Value]) -> [(String, [Row.Cell.Value])]? {
  147. guard let sectionKeyForValue = sectionKeyForValue else { return nil }
  148. let sections = options.reduce([:]) { (reduced, option) -> [String: [Row.Cell.Value]] in
  149. var reduced = reduced
  150. let key = sectionKeyForValue(option)
  151. reduced[key] = (reduced[key] ?? []) + [option]
  152. return reduced
  153. }
  154. return sections.sorted(by: { (lhs, rhs) in lhs.0 < rhs.0 })
  155. }
  156. func section(with options: [Row.Cell.Value], header: String?, footer: String?) -> SelectableSection<Row> {
  157. let section = SelectableSection<Row>(header: header, footer: footer, selectionType: .singleSelection(enableDeselection: enableDeselection)) { section in
  158. section.onSelectSelectableRow = { [weak self] _, row in
  159. let changed = self?.row.value != row.value
  160. self?.row.value = row.value
  161. if let form = row.section?.form {
  162. for section in form where section !== row.section {
  163. let section = section as Any as! SelectableSection<Row>
  164. if let selectedRow = section.selectedRow(), selectedRow !== row {
  165. selectedRow.value = nil
  166. selectedRow.updateCell()
  167. }
  168. }
  169. }
  170. if self?.dismissOnSelection == true || (changed && self?.dismissOnChange == true) {
  171. self?.onDismissCallback?(self!)
  172. }
  173. }
  174. }
  175. for option in options {
  176. section <<< Row.init(String(describing: option)) { lrow in
  177. lrow.title = self.row.displayValueFor?(option)
  178. lrow.selectableValue = option
  179. lrow.value = self.row.value == option ? option : nil
  180. self.selectableRowSetup?(lrow)
  181. }.cellSetup { [weak self] cell, row in
  182. self?.selectableRowCellSetup?(cell, row)
  183. }.cellUpdate { [weak self] cell, row in
  184. self?.selectableRowCellUpdate?(cell, row)
  185. }
  186. }
  187. return section
  188. }
  189. }
  190. /// Selector Controller (used to select one option among a list)
  191. open class SelectorViewController<OptionsRow: OptionsProviderRow>: _SelectorViewController<ListCheckRow<OptionsRow.OptionsProviderType.Option>, OptionsRow> {
  192. }