Form.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Form.swift
  2. // Eureka ( https://github.com/xmartlabs/Eureka )
  3. //
  4. // Copyright (c) 2016 Xmartlabs ( 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. /// The delegate of the Eureka form.
  26. public protocol FormDelegate : class {
  27. func sectionsHaveBeenAdded(_ sections: [Section], at: IndexSet)
  28. func sectionsHaveBeenRemoved(_ sections: [Section], at: IndexSet)
  29. func sectionsHaveBeenReplaced(oldSections: [Section], newSections: [Section], at: IndexSet)
  30. func rowsHaveBeenAdded(_ rows: [BaseRow], at: [IndexPath])
  31. func rowsHaveBeenRemoved(_ rows: [BaseRow], at: [IndexPath])
  32. func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at: [IndexPath])
  33. func valueHasBeenChanged(for row: BaseRow, oldValue: Any?, newValue: Any?)
  34. }
  35. // MARK: Form
  36. /// The class representing the Eureka form.
  37. public final class Form {
  38. /// Defines the default options of the navigation accessory view.
  39. public static var defaultNavigationOptions = RowNavigationOptions.Enabled.union(.SkipCanNotBecomeFirstResponderRow)
  40. /// The default options that define when an inline row will be hidden. Applies only when `inlineRowHideOptions` is nil.
  41. public static var defaultInlineRowHideOptions = InlineRowHideOptions.FirstResponderChanges.union(.AnotherInlineRowIsShown)
  42. /// The options that define when an inline row will be hidden. If nil then `defaultInlineRowHideOptions` are used
  43. public var inlineRowHideOptions: InlineRowHideOptions?
  44. /// Which `UIReturnKeyType` should be used by default. Applies only when `keyboardReturnType` is nil.
  45. public static var defaultKeyboardReturnType = KeyboardReturnTypeConfiguration()
  46. /// Which `UIReturnKeyType` should be used in this form. If nil then `defaultKeyboardReturnType` is used
  47. public var keyboardReturnType: KeyboardReturnTypeConfiguration?
  48. /// This form's delegate
  49. public weak var delegate: FormDelegate?
  50. public init() {}
  51. /**
  52. Returns the row at the given indexPath
  53. */
  54. public subscript(indexPath: IndexPath) -> BaseRow {
  55. return self[indexPath.section][indexPath.row]
  56. }
  57. /**
  58. Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster
  59. */
  60. public func rowBy<T>(tag: String) -> RowOf<T>? where T: Equatable{
  61. let row: BaseRow? = rowBy(tag: tag)
  62. return row as? RowOf<T>
  63. }
  64. /**
  65. Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster
  66. */
  67. public func rowBy<Row>(tag: String) -> Row? where Row: RowType{
  68. let row: BaseRow? = rowBy(tag: tag)
  69. return row as? Row
  70. }
  71. /**
  72. Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster
  73. */
  74. public func rowBy(tag: String) -> BaseRow? {
  75. return rowsByTag[tag]
  76. }
  77. /**
  78. Returns the section whose tag is passed as parameter.
  79. */
  80. public func sectionBy(tag: String) -> Section? {
  81. return kvoWrapper._allSections.filter({ $0.tag == tag }).first
  82. }
  83. /**
  84. Method used to get all the values of all the rows of the form. Only rows with tag are included.
  85. - parameter includeHidden: If the values of hidden rows should be included.
  86. - returns: A dictionary mapping the rows tag to its value. [tag: value]
  87. */
  88. public func values(includeHidden: Bool = false) -> [String: Any?] {
  89. if includeHidden {
  90. return getValues(for: allRows.filter({ $0.tag != nil }))
  91. .merging(getValues(for: allSections.filter({ $0 is BaseMultivaluedSection && $0.tag != nil }) as? [BaseMultivaluedSection]), uniquingKeysWith: {(_, new) in new })
  92. }
  93. return getValues(for: rows.filter({ $0.tag != nil }))
  94. .merging(getValues(for: allSections.filter({ $0 is BaseMultivaluedSection && $0.tag != nil }) as? [BaseMultivaluedSection]), uniquingKeysWith: {(_, new) in new })
  95. }
  96. /**
  97. Set values to the rows of this form
  98. - parameter values: A dictionary mapping tag to value of the rows to be set. [tag: value]
  99. */
  100. public func setValues(_ values: [String: Any?]) {
  101. for (key, value) in values {
  102. let row: BaseRow? = rowBy(tag: key)
  103. row?.baseValue = value
  104. }
  105. }
  106. /// The visible rows of this form
  107. public var rows: [BaseRow] { return flatMap { $0 } }
  108. /// All the rows of this form. Includes the hidden rows.
  109. public var allRows: [BaseRow] { return kvoWrapper._allSections.map({ $0.kvoWrapper._allRows }).flatMap { $0 } }
  110. /// All the sections of this form. Includes hidden sections.
  111. public var allSections: [Section] { return kvoWrapper._allSections }
  112. /**
  113. * Hides all the inline rows of this form.
  114. */
  115. public func hideInlineRows() {
  116. for row in self.allRows {
  117. if let inlineRow = row as? BaseInlineRowType {
  118. inlineRow.collapseInlineRow()
  119. }
  120. }
  121. }
  122. // MARK: Private
  123. var rowObservers = [String: [ConditionType: [Taggable]]]()
  124. var rowsByTag = [String: BaseRow]()
  125. var tagToValues = [String: Any]()
  126. lazy var kvoWrapper: KVOWrapper = { [unowned self] in return KVOWrapper(form: self) }()
  127. }
  128. extension Form: Collection {
  129. public var startIndex: Int { return 0 }
  130. public var endIndex: Int { return kvoWrapper.sections.count }
  131. }
  132. extension Form: MutableCollection {
  133. // MARK: MutableCollectionType
  134. public subscript (_ position: Int) -> Section {
  135. get { return kvoWrapper.sections[position] as! Section }
  136. set {
  137. if position > kvoWrapper.sections.count {
  138. assertionFailure("Form: Index out of bounds")
  139. }
  140. if position < kvoWrapper.sections.count {
  141. let oldSection = kvoWrapper.sections[position]
  142. let oldSectionIndex = kvoWrapper._allSections.firstIndex(of: oldSection as! Section)!
  143. // Remove the previous section from the form
  144. kvoWrapper._allSections[oldSectionIndex].willBeRemovedFromForm()
  145. kvoWrapper._allSections[oldSectionIndex] = newValue
  146. } else {
  147. kvoWrapper._allSections.append(newValue)
  148. }
  149. kvoWrapper.sections[position] = newValue
  150. newValue.wasAddedTo(form: self)
  151. }
  152. }
  153. public func index(after i: Int) -> Int {
  154. return i+1 <= endIndex ? i+1 : endIndex
  155. }
  156. public func index(before i: Int) -> Int {
  157. return i > startIndex ? i-1 : startIndex
  158. }
  159. public var last: Section? {
  160. return reversed().first
  161. }
  162. }
  163. extension Form : RangeReplaceableCollection {
  164. // MARK: RangeReplaceableCollectionType
  165. public func append(_ formSection: Section) {
  166. kvoWrapper.sections.insert(formSection, at: kvoWrapper.sections.count)
  167. kvoWrapper._allSections.append(formSection)
  168. formSection.wasAddedTo(form: self)
  169. }
  170. public func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == Section {
  171. kvoWrapper.sections.addObjects(from: newElements.map { $0 })
  172. kvoWrapper._allSections.append(contentsOf: newElements)
  173. for section in newElements {
  174. section.wasAddedTo(form: self)
  175. }
  176. }
  177. public func replaceSubrange<C: Collection>(_ subRange: Range<Int>, with newElements: C) where C.Iterator.Element == Section {
  178. for i in subRange.lowerBound..<subRange.upperBound {
  179. if let section = kvoWrapper.sections.object(at: i) as? Section {
  180. section.willBeRemovedFromForm()
  181. kvoWrapper._allSections.remove(at: kvoWrapper._allSections.firstIndex(of: section)!)
  182. }
  183. }
  184. kvoWrapper.sections.replaceObjects(in: NSRange(location: subRange.lowerBound, length: subRange.upperBound - subRange.lowerBound),
  185. withObjectsFrom: newElements.map { $0 })
  186. kvoWrapper._allSections.insert(contentsOf: newElements, at: indexForInsertion(at: subRange.lowerBound))
  187. for section in newElements {
  188. section.wasAddedTo(form: self)
  189. }
  190. }
  191. public func removeAll(keepingCapacity keepCapacity: Bool = false) {
  192. // not doing anything with capacity
  193. let sections = kvoWrapper._allSections
  194. kvoWrapper.removeAllSections()
  195. for section in sections {
  196. section.willBeRemovedFromForm()
  197. }
  198. }
  199. private func indexForInsertion(at index: Int) -> Int {
  200. guard index != 0 else { return 0 }
  201. let section = kvoWrapper.sections[index-1]
  202. if let i = kvoWrapper._allSections.firstIndex(of: section as! Section) {
  203. return i + 1
  204. }
  205. return kvoWrapper._allSections.count
  206. }
  207. }
  208. extension Form {
  209. // MARK: Private Helpers
  210. class KVOWrapper: NSObject {
  211. @objc dynamic private var _sections = NSMutableArray()
  212. var sections: NSMutableArray { return mutableArrayValue(forKey: "_sections") }
  213. var _allSections = [Section]()
  214. private weak var form: Form?
  215. init(form: Form) {
  216. self.form = form
  217. super.init()
  218. addObserver(self, forKeyPath: "_sections", options: [.new, .old], context:nil)
  219. }
  220. deinit {
  221. removeObserver(self, forKeyPath: "_sections")
  222. _sections.removeAllObjects()
  223. _allSections.removeAll()
  224. }
  225. func removeAllSections() {
  226. _sections = []
  227. _allSections.removeAll()
  228. }
  229. public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  230. let newSections = change?[NSKeyValueChangeKey.newKey] as? [Section] ?? []
  231. let oldSections = change?[NSKeyValueChangeKey.oldKey] as? [Section] ?? []
  232. guard let delegateValue = form?.delegate, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey] else { return }
  233. guard keyPathValue == "_sections" else { return }
  234. switch (changeType as! NSNumber).uintValue {
  235. case NSKeyValueChange.setting.rawValue:
  236. if newSections.count == 0 {
  237. let indexSet = IndexSet(integersIn: 0..<oldSections.count)
  238. delegateValue.sectionsHaveBeenRemoved(oldSections, at: indexSet)
  239. } else {
  240. let indexSet = change![NSKeyValueChangeKey.indexesKey] as? IndexSet ?? IndexSet(integersIn: 0..<newSections.count)
  241. delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet)
  242. }
  243. case NSKeyValueChange.insertion.rawValue:
  244. let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
  245. delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet)
  246. case NSKeyValueChange.removal.rawValue:
  247. let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
  248. delegateValue.sectionsHaveBeenRemoved(oldSections, at: indexSet)
  249. case NSKeyValueChange.replacement.rawValue:
  250. let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
  251. delegateValue.sectionsHaveBeenReplaced(oldSections: oldSections, newSections: newSections, at: indexSet)
  252. default:
  253. assertionFailure()
  254. }
  255. }
  256. }
  257. func dictionaryValuesToEvaluatePredicate() -> [String: Any] {
  258. return tagToValues
  259. }
  260. func addRowObservers(to taggable: Taggable, rowTags: [String], type: ConditionType) {
  261. for rowTag in rowTags {
  262. if rowObservers[rowTag] == nil {
  263. rowObservers[rowTag] = Dictionary()
  264. }
  265. if let _ = rowObservers[rowTag]?[type] {
  266. if !rowObservers[rowTag]![type]!.contains(where: { $0 === taggable }) {
  267. rowObservers[rowTag]?[type]!.append(taggable)
  268. }
  269. } else {
  270. rowObservers[rowTag]?[type] = [taggable]
  271. }
  272. }
  273. }
  274. func removeRowObservers(from taggable: Taggable, rowTags: [String], type: ConditionType) {
  275. for rowTag in rowTags {
  276. guard let arr = rowObservers[rowTag]?[type], let index = arr.firstIndex(where: { $0 === taggable }) else { continue }
  277. rowObservers[rowTag]?[type]?.remove(at: index)
  278. if rowObservers[rowTag]?[type]?.isEmpty == true {
  279. rowObservers[rowTag] = nil
  280. }
  281. }
  282. }
  283. func nextRow(for row: BaseRow) -> BaseRow? {
  284. let allRows = rows
  285. guard let index = allRows.firstIndex(of: row) else { return nil }
  286. guard index < allRows.count - 1 else { return nil }
  287. return allRows[index + 1]
  288. }
  289. func previousRow(for row: BaseRow) -> BaseRow? {
  290. let allRows = rows
  291. guard let index = allRows.firstIndex(of: row) else { return nil }
  292. guard index > 0 else { return nil }
  293. return allRows[index - 1]
  294. }
  295. func hideSection(_ section: Section) {
  296. kvoWrapper.sections.remove(section)
  297. }
  298. func showSection(_ section: Section) {
  299. guard !kvoWrapper.sections.contains(section) else { return }
  300. guard var index = kvoWrapper._allSections.firstIndex(of: section) else { return }
  301. var formIndex = NSNotFound
  302. while formIndex == NSNotFound && index > 0 {
  303. index = index - 1
  304. let previous = kvoWrapper._allSections[index]
  305. formIndex = kvoWrapper.sections.index(of: previous)
  306. }
  307. kvoWrapper.sections.insert(section, at: formIndex == NSNotFound ? 0 : formIndex + 1 )
  308. }
  309. var containsMultivaluedSection: Bool {
  310. return kvoWrapper._allSections.contains { $0 is BaseMultivaluedSection }
  311. }
  312. func getValues(for rows: [BaseRow]) -> [String: Any?] {
  313. return rows.reduce([String: Any?]()) {
  314. var result = $0
  315. result[$1.tag!] = $1.baseValue
  316. return result
  317. }
  318. }
  319. func getValues(for multivaluedSections: [BaseMultivaluedSection]?) -> [String: [Any?]] {
  320. return multivaluedSections?.reduce([String: [Any?]]()) {
  321. var result = $0
  322. result[$1.tag!] = $1.values()
  323. return result
  324. } ?? [:]
  325. }
  326. }
  327. extension Form {
  328. @discardableResult
  329. public func validate(includeHidden: Bool = false, includeDisabled: Bool = true, quietly: Bool = false) -> [ValidationError] {
  330. let rowsWithHiddenFilter = includeHidden ? allRows : rows
  331. let rowsWithDisabledFilter = includeDisabled ? rowsWithHiddenFilter : rowsWithHiddenFilter.filter { $0.isDisabled != true }
  332. return rowsWithDisabledFilter.reduce([ValidationError]()) { res, row in
  333. var res = res
  334. res.append(contentsOf: row.validate(quietly: quietly))
  335. return res
  336. }
  337. }
  338. // Reset rows validation
  339. public func cleanValidationErrors(){
  340. allRows.forEach { $0.cleanValidationErrors() }
  341. }
  342. }