Form.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 : AnyObject {
  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>(
  178. _ subRange: Range<Int>,
  179. with newElements: C
  180. ) where C.Iterator.Element == Section {
  181. for i in subRange.lowerBound..<subRange.upperBound {
  182. if let section = kvoWrapper.sections.object(at: i) as? Section {
  183. section.willBeRemovedFromForm()
  184. kvoWrapper._allSections.remove(at: kvoWrapper._allSections.firstIndex(of: section)!)
  185. }
  186. }
  187. kvoWrapper.sections.replaceObjects(
  188. in: NSRange(location: subRange.lowerBound, length: subRange.upperBound - subRange.lowerBound),
  189. withObjectsFrom: newElements.map { $0 }
  190. )
  191. kvoWrapper._allSections.insert(contentsOf: newElements, at: indexForInsertion(at: subRange.lowerBound))
  192. for section in newElements {
  193. section.wasAddedTo(form: self)
  194. }
  195. }
  196. public func replaceSubrangeInAllSections<C: Collection>(
  197. _ subRange: Range<Int>,
  198. with newElements: C
  199. ) where C.Iterator.Element == Section {
  200. // Remove subrange in all sections
  201. for i in subRange.reversed() where kvoWrapper._allSections.count > i {
  202. let removed = kvoWrapper._allSections.remove(at: i)
  203. removed.willBeRemovedFromForm()
  204. }
  205. kvoWrapper._allSections.insert(contentsOf: newElements, at: indexForInsertion(at: subRange.lowerBound))
  206. // Replace all visible sections by `kvoWrapper._allSections`, as hidden ones are being removed later anyway
  207. kvoWrapper.sections.replaceObjects(
  208. in: NSRange(location: 0, length: kvoWrapper.sections.count),
  209. withObjectsFrom: kvoWrapper._allSections
  210. )
  211. for section in newElements {
  212. section.wasAddedTo(form: self)
  213. }
  214. }
  215. public func removeAll(keepingCapacity keepCapacity: Bool = false) {
  216. // not doing anything with capacity
  217. let sections = kvoWrapper._allSections
  218. kvoWrapper.removeAllSections()
  219. for section in sections {
  220. section.willBeRemovedFromForm()
  221. }
  222. }
  223. public func removeAll(where shouldBeRemoved: (Section) throws -> Bool) rethrows {
  224. let indices = try kvoWrapper._allSections.enumerated()
  225. .filter { try shouldBeRemoved($0.element)}
  226. .map { $0.offset }
  227. var removedSections = [Section]()
  228. for index in indices.reversed() {
  229. removedSections.append(kvoWrapper._allSections.remove(at: index))
  230. }
  231. kvoWrapper.sections.removeObjects(in: removedSections)
  232. removedSections.forEach { $0.willBeRemovedFromForm() }
  233. }
  234. private func indexForInsertion(at index: Int) -> Int {
  235. guard index != 0 else { return 0 }
  236. let section = kvoWrapper.sections[index-1]
  237. if let i = kvoWrapper._allSections.firstIndex(of: section as! Section) {
  238. return i + 1
  239. }
  240. return kvoWrapper._allSections.count
  241. }
  242. }
  243. extension Form {
  244. // MARK: Private Helpers
  245. class KVOWrapper: NSObject {
  246. @objc dynamic private var _sections = NSMutableArray()
  247. var sections: NSMutableArray { return mutableArrayValue(forKey: "_sections") }
  248. var _allSections = [Section]()
  249. private weak var form: Form?
  250. init(form: Form) {
  251. self.form = form
  252. super.init()
  253. addObserver(self, forKeyPath: "_sections", options: [.new, .old], context:nil)
  254. }
  255. deinit {
  256. removeObserver(self, forKeyPath: "_sections")
  257. _sections.removeAllObjects()
  258. _allSections.removeAll()
  259. }
  260. func removeAllSections() {
  261. _sections = []
  262. _allSections.removeAll()
  263. }
  264. public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  265. let newSections = change?[NSKeyValueChangeKey.newKey] as? [Section] ?? []
  266. let oldSections = change?[NSKeyValueChangeKey.oldKey] as? [Section] ?? []
  267. guard let delegateValue = form?.delegate, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey] else { return }
  268. guard keyPathValue == "_sections" else { return }
  269. switch (changeType as! NSNumber).uintValue {
  270. case NSKeyValueChange.setting.rawValue:
  271. if newSections.count == 0 {
  272. let indexSet = IndexSet(integersIn: 0..<oldSections.count)
  273. delegateValue.sectionsHaveBeenRemoved(oldSections, at: indexSet)
  274. } else {
  275. let indexSet = change![NSKeyValueChangeKey.indexesKey] as? IndexSet ?? IndexSet(integersIn: 0..<newSections.count)
  276. delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet)
  277. }
  278. case NSKeyValueChange.insertion.rawValue:
  279. let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
  280. delegateValue.sectionsHaveBeenAdded(newSections, at: indexSet)
  281. case NSKeyValueChange.removal.rawValue:
  282. let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
  283. delegateValue.sectionsHaveBeenRemoved(oldSections, at: indexSet)
  284. case NSKeyValueChange.replacement.rawValue:
  285. let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
  286. delegateValue.sectionsHaveBeenReplaced(oldSections: oldSections, newSections: newSections, at: indexSet)
  287. default:
  288. assertionFailure()
  289. }
  290. }
  291. }
  292. func dictionaryValuesToEvaluatePredicate() -> [String: Any] {
  293. return tagToValues
  294. }
  295. func addRowObservers(to taggable: Taggable, rowTags: [String], type: ConditionType) {
  296. for rowTag in rowTags {
  297. if rowObservers[rowTag] == nil {
  298. rowObservers[rowTag] = Dictionary()
  299. }
  300. if let _ = rowObservers[rowTag]?[type] {
  301. if !rowObservers[rowTag]![type]!.contains(where: { $0 === taggable }) {
  302. rowObservers[rowTag]?[type]!.append(taggable)
  303. }
  304. } else {
  305. rowObservers[rowTag]?[type] = [taggable]
  306. }
  307. }
  308. }
  309. func removeRowObservers(from taggable: Taggable, rowTags: [String], type: ConditionType) {
  310. for rowTag in rowTags {
  311. guard let arr = rowObservers[rowTag]?[type], let index = arr.firstIndex(where: { $0 === taggable }) else { continue }
  312. rowObservers[rowTag]?[type]?.remove(at: index)
  313. if rowObservers[rowTag]?[type]?.isEmpty == true {
  314. rowObservers[rowTag] = nil
  315. }
  316. }
  317. }
  318. func nextRow(for row: BaseRow) -> BaseRow? {
  319. let allRows = rows
  320. guard let index = allRows.firstIndex(of: row) else { return nil }
  321. guard index < allRows.count - 1 else { return nil }
  322. return allRows[index + 1]
  323. }
  324. func previousRow(for row: BaseRow) -> BaseRow? {
  325. let allRows = rows
  326. guard let index = allRows.firstIndex(of: row) else { return nil }
  327. guard index > 0 else { return nil }
  328. return allRows[index - 1]
  329. }
  330. func hideSection(_ section: Section) {
  331. kvoWrapper.sections.remove(section)
  332. }
  333. func showSection(_ section: Section) {
  334. guard !kvoWrapper.sections.contains(section) else { return }
  335. guard var index = kvoWrapper._allSections.firstIndex(of: section) else { return }
  336. var formIndex = NSNotFound
  337. while formIndex == NSNotFound && index > 0 {
  338. index = index - 1
  339. let previous = kvoWrapper._allSections[index]
  340. formIndex = kvoWrapper.sections.index(of: previous)
  341. }
  342. kvoWrapper.sections.insert(section, at: formIndex == NSNotFound ? 0 : formIndex + 1 )
  343. }
  344. var containsMultivaluedSection: Bool {
  345. return kvoWrapper._allSections.contains { $0 is BaseMultivaluedSection }
  346. }
  347. func getValues(for rows: [BaseRow]) -> [String: Any?] {
  348. return rows.reduce([String: Any?]()) {
  349. var result = $0
  350. result[$1.tag!] = $1.baseValue
  351. return result
  352. }
  353. }
  354. func getValues(for multivaluedSections: [BaseMultivaluedSection]?) -> [String: [Any?]] {
  355. return multivaluedSections?.reduce([String: [Any?]]()) {
  356. var result = $0
  357. result[$1.tag!] = $1.values()
  358. return result
  359. } ?? [:]
  360. }
  361. }
  362. extension Form {
  363. @discardableResult
  364. public func validate(includeHidden: Bool = false, includeDisabled: Bool = true, quietly: Bool = false) -> [ValidationError] {
  365. let rowsWithHiddenFilter = includeHidden ? allRows : rows
  366. let rowsWithDisabledFilter = includeDisabled ? rowsWithHiddenFilter : rowsWithHiddenFilter.filter { $0.isDisabled != true }
  367. return rowsWithDisabledFilter.reduce([ValidationError]()) { res, row in
  368. var res = res
  369. res.append(contentsOf: row.validate(quietly: quietly))
  370. return res
  371. }
  372. }
  373. // Reset rows validation
  374. public func cleanValidationErrors(){
  375. allRows.forEach { $0.cleanValidationErrors() }
  376. }
  377. }