Slather logo

Coverage for "StateController.swift" : 78.59%

(536 of 682 relevant lines covered)

ChatLayout/Classes/Core/Model/StateController.swift

1
//
2
// ChatLayout
3
// StateController.swift
4
// https://github.com/ekazaev/ChatLayout
5
//
6
// Created by Eugene Kazaev in 2020-2022.
7
// Distributed under the MIT license.
8
//
9
// Become a sponsor:
10
// https://github.com/sponsors/ekazaev
11
//
12
13
import Foundation
14
import UIKit
15
16
/// This protocol exists only to serve an ability to unit test `StateController`.
17
protocol ChatLayoutRepresentation: AnyObject {
18
19
    var settings: ChatLayoutSettings { get }
20
21
    var viewSize: CGSize { get }
22
23
    var visibleBounds: CGRect { get }
24
25
    var layoutFrame: CGRect { get }
26
27
    var adjustedContentInset: UIEdgeInsets { get }
28
29
    var keepContentOffsetAtBottomOnBatchUpdates: Bool { get }
30
31
    func numberOfItems(in section: Int) -> Int
32
33
    func configuration(for element: ItemKind, at itemPath: ItemPath) -> ItemModel.Configuration
34
35
    func shouldPresentHeader(at sectionIndex: Int) -> Bool
36
37
    func shouldPresentFooter(at sectionIndex: Int) -> Bool
38
39
}
40
41
final class StateController {
42
43
    private enum CompensatingAction {
44
        case insert
45
        case delete
46
        case frameUpdate(previousFrame: CGRect, newFrame: CGRect)
47
    }
48
49
    // This thing exists here as `UICollectionView` calls `targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint)` only once at the
50
    // beginning of the animated updates. But we must compensate the other changes that happened during the update.
51
    var batchUpdateCompensatingOffset: CGFloat = 0
52
53
    var proposedCompensatingOffset: CGFloat = 0
54
55
    var totalProposedCompensatingOffset: CGFloat = 0
56
57
    var isAnimatedBoundsChange = false
58
59
    private(set) var storage: [ModelState: LayoutModel]
60
61
    private(set) var reloadedIndexes: Set<IndexPath> = []
23x
62
63
    private(set) var insertedIndexes: Set<IndexPath> = []
23x
64
65
    private(set) var movedIndexes: Set<IndexPath> = []
23x
66
67
    private(set) var deletedIndexes: Set<IndexPath> = []
23x
68
69
    private(set) var reloadedSectionsIndexes: Set<Int> = []
23x
70
71
    private(set) var insertedSectionsIndexes: Set<Int> = []
23x
72
73
    private(set) var deletedSectionsIndexes: Set<Int> = []
23x
74
75
    private(set) var movedSectionsIndexes: Set<Int> = []
23x
76
77
    private var cachedAttributesState: (rect: CGRect, attributes: [ChatLayoutAttributes])?
78
79
    private var cachedAttributeObjects = [ModelState: [ItemKind: [ItemPath: ChatLayoutAttributes]]]()
23x
80
81
    private unowned var layoutRepresentation: ChatLayoutRepresentation
82
83
    init(layoutRepresentation: ChatLayoutRepresentation) {
23x
84
        self.layoutRepresentation = layoutRepresentation
23x
85
        storage = [.beforeUpdate: LayoutModel(sections: [], collectionLayout: self.layoutRepresentation)]
23x
86
        resetCachedAttributeObjects()
23x
87
    }
23x
88
89
    func set(_ sections: [SectionModel], at state: ModelState) {
23x
90
        var layoutModel = LayoutModel(sections: sections, collectionLayout: layoutRepresentation)
23x
91
        layoutModel.assembleLayout()
23x
92
        storage[state] = layoutModel
23x
93
    }
23x
94
95
    func contentHeight(at state: ModelState) -> CGFloat {
96
        guard let locationHeight = storage[state]?.sections.last?.locationHeight else {
97
            return 0
10000x
98
        }
99
        return locationHeight + layoutRepresentation.settings.additionalInsets.bottom
100
    }
101
102
    func layoutAttributesForElements(in rect: CGRect,
103
                                     state: ModelState,
104
                                     ignoreCache: Bool = false) -> [ChatLayoutAttributes] {
5x
105
        let predicate: (ChatLayoutAttributes) -> ComparisonResult = { attributes in
50x
106
            if attributes.frame.intersects(rect) {
50x
107
                return .orderedSame
45x
108
            } else if attributes.frame.minY > rect.maxY {
45x
109
                return .orderedDescending
5x
110
            } else if attributes.frame.maxY < rect.minY {
5x
111
                return .orderedAscending
!
112
            }
!
113
            return .orderedSame
!
114
        }
!
115
5x
116
        if !ignoreCache,
5x
117
           let cachedAttributesState = cachedAttributesState,
5x
118
           cachedAttributesState.rect.contains(rect) {
5x
119
            return cachedAttributesState.attributes.binarySearchRange(predicate: predicate)
1x
120
        } else {
4x
121
            let totalRect: CGRect
4x
122
            switch state {
4x
123
            case .beforeUpdate:
4x
124
                totalRect = rect.inset(by: UIEdgeInsets(top: -rect.height / 2, left: -rect.width / 2, bottom: -rect.height / 2, right: -rect.width / 2))
4x
125
            case .afterUpdate:
4x
126
                totalRect = rect
!
127
            }
4x
128
            let attributes = allAttributes(at: state, visibleRect: totalRect)
4x
129
            if !ignoreCache {
4x
130
                cachedAttributesState = (rect: totalRect, attributes: attributes)
4x
131
            }
4x
132
            let visibleAttributes = rect != totalRect ? attributes.binarySearchRange(predicate: predicate) : attributes
4x
133
            return visibleAttributes
4x
134
        }
4x
135
    }
!
136
137
    func resetCachedAttributes() {
2x
138
        cachedAttributesState = nil
2x
139
    }
2x
140
141
    func resetCachedAttributeObjects() {
66x
142
        ModelState.allCases.forEach { state in
132x
143
            resetCachedAttributeObjects(at: state)
132x
144
        }
132x
145
    }
66x
146
147
    private func resetCachedAttributeObjects(at state: ModelState) {
144x
148
        cachedAttributeObjects[state] = [:]
144x
149
        ItemKind.allCases.forEach { kind in
432x
150
            cachedAttributeObjects[state]?[kind] = [:]
432x
151
        }
432x
152
    }
144x
153
154
    func itemAttributes(for itemPath: ItemPath,
155
                        kind: ItemKind,
156
                        predefinedFrame: CGRect? = nil,
157
                        at state: ModelState) -> ChatLayoutAttributes? {
368x
158
        let attributes: ChatLayoutAttributes
368x
159
        let itemIndexPath = itemPath.indexPath
368x
160
        switch kind {
368x
161
        case .header:
368x
162
            guard itemPath.section < layout(at: state).sections.count,
13x
163
                  itemPath.item == 0 else {
13x
164
                // This occurs when getting layout attributes for initial / final animations
!
165
                return nil
!
166
            }
13x
167
            guard let headerFrame = predefinedFrame ?? itemFrame(for: itemPath, kind: kind, at: state, isFinal: true),
13x
168
                  let item = item(for: itemPath, kind: kind, at: state) else {
13x
169
                return nil
!
170
            }
13x
171
            if let cachedAttributes = cachedAttributeObjects[state]?[.header]?[itemPath] {
13x
172
                attributes = cachedAttributes
3x
173
            } else {
13x
174
                attributes = ChatLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: itemIndexPath)
10x
175
                cachedAttributeObjects[state]?[.header]?[itemPath] = attributes
10x
176
            }
13x
177
            #if DEBUG
13x
178
            attributes.id = item.id
13x
179
            #endif
13x
180
            attributes.frame = headerFrame
13x
181
            attributes.indexPath = itemIndexPath
13x
182
            attributes.zIndex = 10
13x
183
            attributes.alignment = item.alignment
13x
184
        case .footer:
368x
185
            guard itemPath.section < layout(at: state).sections.count,
9x
186
                  itemPath.item == 0 else {
9x
187
                // This occurs when getting layout attributes for initial / final animations
!
188
                return nil
!
189
            }
9x
190
            guard let footerFrame = predefinedFrame ?? itemFrame(for: itemPath, kind: kind, at: state, isFinal: true),
9x
191
                  let item = item(for: itemPath, kind: kind, at: state) else {
9x
192
                return nil
!
193
            }
9x
194
            if let cachedAttributes = cachedAttributeObjects[state]?[.footer]?[itemPath] {
9x
195
                attributes = cachedAttributes
2x
196
            } else {
9x
197
                attributes = ChatLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, with: itemIndexPath)
7x
198
                cachedAttributeObjects[state]?[.footer]?[itemPath] = attributes
7x
199
            }
9x
200
            #if DEBUG
9x
201
            attributes.id = item.id
9x
202
            #endif
9x
203
            attributes.frame = footerFrame
9x
204
            attributes.indexPath = itemIndexPath
9x
205
            attributes.zIndex = 10
9x
206
            attributes.alignment = item.alignment
9x
207
        case .cell:
368x
208
            guard itemPath.section < layout(at: state).sections.count,
346x
209
                  itemPath.item < layout(at: state).sections[itemPath.section].items.count else {
346x
210
                // This occurs when getting layout attributes for initial / final animations
!
211
                return nil
!
212
            }
346x
213
            guard let itemFrame = predefinedFrame ?? itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true),
346x
214
                  let item = item(for: itemPath, kind: kind, at: state) else {
346x
215
                return nil
!
216
            }
346x
217
            if let cachedAttributes = cachedAttributeObjects[state]?[.cell]?[itemPath] {
346x
218
                attributes = cachedAttributes
13x
219
            } else {
346x
220
                attributes = ChatLayoutAttributes(forCellWith: itemIndexPath)
333x
221
                cachedAttributeObjects[state]?[.cell]?[itemPath] = attributes
333x
222
            }
346x
223
            #if DEBUG
346x
224
            attributes.id = item.id
346x
225
            #endif
346x
226
            attributes.frame = itemFrame
346x
227
            attributes.indexPath = itemIndexPath
346x
228
            attributes.zIndex = 0
346x
229
            attributes.alignment = item.alignment
346x
230
        }
368x
231
        attributes.viewSize = layoutRepresentation.viewSize
368x
232
        attributes.adjustedContentInsets = layoutRepresentation.adjustedContentInset
368x
233
        attributes.visibleBoundsSize = layoutRepresentation.visibleBounds.size
368x
234
        attributes.layoutFrame = layoutRepresentation.layoutFrame
368x
235
        attributes.additionalInsets = layoutRepresentation.settings.additionalInsets
368x
236
        return attributes
368x
237
    }
368x
238
239
    func itemFrame(for itemPath: ItemPath, kind: ItemKind, at state: ModelState, isFinal: Bool = false) -> CGRect? {
240
        guard itemPath.section < layout(at: state).sections.count else {
241
            return nil
!
242
        }
243
        guard let item = item(for: itemPath, kind: kind, at: state) else {
244
            // This occurs when getting layout attributes for initial / final animations
!
245
            return nil
!
246
        }
247
248
        let section = layout(at: state).sections[itemPath.section]
249
        var itemFrame = item.frame
250
        let dx: CGFloat
251
        let visibleBounds = layoutRepresentation.visibleBounds
252
        let additionalInsets = layoutRepresentation.settings.additionalInsets
253
254
        switch item.alignment {
255
        case .leading:
256
            dx = additionalInsets.left
2x
257
        case .trailing:
258
            dx = visibleBounds.size.width - itemFrame.width - additionalInsets.right
2x
259
        case .center:
260
            let availableWidth = visibleBounds.size.width - additionalInsets.right - additionalInsets.left
5x
261
            dx = additionalInsets.left + availableWidth / 2 - itemFrame.width / 2
5x
262
        case .fullWidth:
263
            dx = additionalInsets.left
264
            itemFrame.size.width = layoutRepresentation.layoutFrame.size.width
265
        }
266
267
        itemFrame = itemFrame.offsetBy(dx: dx, dy: section.offsetY)
268
        if isFinal {
269
            itemFrame = offsetByCompensation(frame: itemFrame, at: itemPath, for: state, backward: true)
376x
270
        }
271
        return itemFrame
272
    }
273
274
    func itemPath(by itemId: UUID, kind: ItemKind, at state: ModelState) -> ItemPath? {
10300x
275
        layout(at: state).itemPath(by: itemId, kind: kind)
10300x
276
    }
10300x
277
278
    func sectionIdentifier(for index: Int, at state: ModelState) -> UUID? {
2x
279
        guard index < layout(at: state).sections.count else {
2x
280
            // This occurs when getting layout attributes for initial / final animations
!
281
            return nil
!
282
        }
2x
283
        return layout(at: state).sections[index].id
2x
284
    }
2x
285
286
    func sectionIndex(for sectionIdentifier: UUID, at state: ModelState) -> Int? {
5x
287
        guard let sectionIndex = layout(at: state).sectionIndex(by: sectionIdentifier) else {
5x
288
            // This occurs when getting layout attributes for initial / final animations
!
289
            return nil
!
290
        }
5x
291
        return sectionIndex
5x
292
    }
5x
293
294
    func section(at index: Int, at state: ModelState) -> SectionModel {
10x
295
        guard index < layout(at: state).sections.count else {
10x
296
            preconditionFailure("Section index \(index) is bigger than the amount of sections \(layout(at: state).sections.count).")
!
297
        }
10x
298
        return layout(at: state).sections[index]
10x
299
    }
10x
300
301
    func itemIdentifier(for itemPath: ItemPath, kind: ItemKind, at state: ModelState) -> UUID? {
302
        guard itemPath.section < layout(at: state).sections.count else {
303
            // This occurs when getting layout attributes for initial / final animations
2x
304
            return nil
2x
305
        }
306
        let sectionModel = layout(at: state).sections[itemPath.section]
307
        switch kind {
308
        case .cell:
309
            guard itemPath.item < layout(at: state).sections[itemPath.section].items.count else {
310
                // This occurs when getting layout attributes for initial / final animations
3x
311
                return nil
3x
312
            }
313
            let rowModel = sectionModel.items[itemPath.item]
314
            return rowModel.id
315
        case .header, .footer:
316
            guard let item = item(for: ItemPath(item: 0, section: itemPath.section), kind: kind, at: state) else {
32x
317
                return nil
4x
318
            }
28x
319
            return item.id
28x
320
        }
321
322
    }
323
324
    func numberOfSections(at state: ModelState) -> Int {
4x
325
        layout(at: state).sections.count
4x
326
    }
4x
327
328
    func numberOfItems(in sectionIndex: Int, at state: ModelState) -> Int {
28x
329
        layout(at: state).sections[sectionIndex].items.count
28x
330
    }
28x
331
332
    func item(for itemPath: ItemPath, kind: ItemKind, at state: ModelState) -> ItemModel? {
333
        switch kind {
334
        case .header:
335
            guard itemPath.section < layout(at: state).sections.count,
61x
336
                  itemPath.item == 0 else {
61x
337
                // This occurs when getting layout attributes for initial / final animations
1x
338
                return nil
1x
339
            }
60x
340
            guard let header = layout(at: state).sections[itemPath.section].header else {
60x
341
                return nil
3x
342
            }
57x
343
            return header
57x
344
        case .footer:
345
            guard itemPath.section < layout(at: state).sections.count,
46x
346
                  itemPath.item == 0 else {
46x
347
                // This occurs when getting layout attributes for initial / final animations
1x
348
                return nil
1x
349
            }
45x
350
            guard let footer = layout(at: state).sections[itemPath.section].footer else {
45x
351
                return nil
1x
352
            }
44x
353
            return footer
44x
354
        case .cell:
355
            guard itemPath.section < layout(at: state).sections.count,
356
                  itemPath.item < layout(at: state).sections[itemPath.section].count else {
357
                // This occurs when getting layout attributes for initial / final animations
!
358
                return nil
!
359
            }
360
            return layout(at: state).sections[itemPath.section].items[itemPath.item]
361
        }
362
    }
363
364
    func update(preferredSize: CGSize, alignment: ChatItemAlignment, for itemPath: ItemPath, kind: ItemKind, at state: ModelState) {
10000x
365
        guard var item = item(for: itemPath, kind: kind, at: state) else {
10000x
366
            assertionFailure("Item at index path (\(itemPath.section) - \(itemPath.item)) does not exist.")
!
367
            return
!
368
        }
10000x
369
        var layout = layout(at: state)
10000x
370
        let previousFrame = item.frame
10000x
371
        cachedAttributesState = nil
10000x
372
        item.alignment = alignment
10000x
373
        item.calculatedSize = preferredSize
10000x
374
        item.calculatedOnce = true
10000x
375
10000x
376
        switch kind {
10000x
377
        case .header:
10000x
378
            layout.setAndAssemble(header: item, sectionIndex: itemPath.section)
3x
379
        case .footer:
10000x
380
            layout.setAndAssemble(footer: item, sectionIndex: itemPath.section)
3x
381
        case .cell:
10000x
382
            layout.setAndAssemble(item: item, sectionIndex: itemPath.section, itemIndex: itemPath.item)
10000x
383
        }
10000x
384
        storage[state] = layout
10000x
385
        let frameUpdateAction = CompensatingAction.frameUpdate(previousFrame: previousFrame, newFrame: item.frame)
10000x
386
        compensateOffsetIfNeeded(for: itemPath, kind: kind, action: frameUpdateAction)
10000x
387
    }
10000x
388
389
    func process(changeItems: [ChangeItem]) {
42x
390
        batchUpdateCompensatingOffset = 0
42x
391
        proposedCompensatingOffset = 0
42x
392
        let changeItems = changeItems.sorted()
42x
393
42x
394
        var afterUpdateModel = layout(at: .beforeUpdate)
42x
395
        resetCachedAttributeObjects()
42x
396
42x
397
        changeItems.forEach { updateItem in
398
            switch updateItem {
399
            case let .sectionInsert(sectionIndex: sectionIndex):
400
                let items = (0..<layoutRepresentation.numberOfItems(in: sectionIndex)).map { index -> ItemModel in
350x
401
                    let itemIndexPath = IndexPath(item: index, section: sectionIndex)
350x
402
                    return ItemModel(with: layoutRepresentation.configuration(for: .cell, at: itemIndexPath.itemPath))
350x
403
                }
350x
404
                let header: ItemModel?
2x
405
                if layoutRepresentation.shouldPresentHeader(at: sectionIndex) == true {
2x
406
                    let headerIndexPath = IndexPath(item: 0, section: sectionIndex)
1x
407
                    header = ItemModel(with: layoutRepresentation.configuration(for: .header, at: headerIndexPath.itemPath))
1x
408
                } else {
2x
409
                    header = nil
1x
410
                }
2x
411
                let footer: ItemModel?
2x
412
                if layoutRepresentation.shouldPresentFooter(at: sectionIndex) == true {
2x
413
                    let footerIndexPath = IndexPath(item: 0, section: sectionIndex)
2x
414
                    footer = ItemModel(with: layoutRepresentation.configuration(for: .footer, at: footerIndexPath.itemPath))
2x
415
                } else {
2x
416
                    footer = nil
!
417
                }
2x
418
                let section = SectionModel(header: header, footer: footer, items: items, collectionLayout: layoutRepresentation)
2x
419
                afterUpdateModel.insertSection(section, at: sectionIndex)
2x
420
                insertedSectionsIndexes.insert(sectionIndex)
2x
421
            case let .itemInsert(itemIndexPath: indexPath):
422
                let item = ItemModel(with: layoutRepresentation.configuration(for: .cell, at: indexPath.itemPath))
423
                insertedIndexes.insert(indexPath)
424
                afterUpdateModel.insertItem(item, at: indexPath)
425
            case let .sectionDelete(sectionIndex: sectionIndex):
426
                let section = layout(at: .beforeUpdate).sections[sectionIndex]
2x
427
                deletedSectionsIndexes.insert(sectionIndex)
2x
428
                afterUpdateModel.removeSection(by: section.id)
2x
429
            case let .itemDelete(itemIndexPath: indexPath):
430
                let itemId = itemIdentifier(for: indexPath.itemPath, kind: .cell, at: .beforeUpdate)!
431
                afterUpdateModel.removeItem(by: itemId)
432
                deletedIndexes.insert(indexPath)
433
            case let .sectionReload(sectionIndex: sectionIndex):
434
                reloadedSectionsIndexes.insert(sectionIndex)
5x
435
                var section = layout(at: .beforeUpdate).sections[sectionIndex]
5x
436
5x
437
                var header: ItemModel?
5x
438
                if layoutRepresentation.shouldPresentHeader(at: sectionIndex) == true {
5x
439
                    let headerIndexPath = IndexPath(item: 0, section: sectionIndex)
3x
440
                    header = section.header ?? ItemModel(with: layoutRepresentation.configuration(for: .header, at: headerIndexPath.itemPath))
3x
441
                    header?.resetSize()
3x
442
                } else {
5x
443
                    header = nil
2x
444
                }
5x
445
                section.set(header: header)
5x
446
5x
447
                var footer: ItemModel?
5x
448
                if layoutRepresentation.shouldPresentFooter(at: sectionIndex) == true {
5x
449
                    let footerIndexPath = IndexPath(item: 0, section: sectionIndex)
4x
450
                    footer = section.footer ?? ItemModel(with: layoutRepresentation.configuration(for: .footer, at: footerIndexPath.itemPath))
4x
451
                    footer?.resetSize()
4x
452
                } else {
5x
453
                    footer = nil
1x
454
                }
5x
455
                section.set(footer: footer)
5x
456
5x
457
                let oldItems = section.items
5x
458
                let items: [ItemModel] = (0..<layoutRepresentation.numberOfItems(in: sectionIndex)).map { index in
550x
459
                    var newItem: ItemModel
550x
460
                    if index < oldItems.count {
550x
461
                        newItem = oldItems[index]
450x
462
                    } else {
550x
463
                        let itemIndexPath = IndexPath(item: index, section: sectionIndex)
100x
464
                        newItem = ItemModel(with: layoutRepresentation.configuration(for: .cell, at: itemIndexPath.itemPath))
100x
465
                    }
550x
466
                    newItem.resetSize()
550x
467
                    return newItem
550x
468
                }
550x
469
                section.set(items: items)
5x
470
                afterUpdateModel.removeSection(for: sectionIndex)
5x
471
                afterUpdateModel.insertSection(section, at: sectionIndex)
5x
472
            case let .itemReload(itemIndexPath: indexPath):
473
                guard var item = item(for: indexPath.itemPath, kind: .cell, at: .beforeUpdate) else {
10300x
474
                    assertionFailure("Item at index path (\(indexPath.section) - \(indexPath.item)) does not exist.")
!
475
                    return
!
476
                }
10300x
477
                item.resetSize()
10300x
478
10300x
479
                afterUpdateModel.replaceItem(item, at: indexPath)
10300x
480
                reloadedIndexes.insert(indexPath)
10300x
481
            case let .sectionMove(initialSectionIndex: initialSectionIndex, finalSectionIndex: finalSectionIndex):
482
                let section = layout(at: .beforeUpdate).sections[initialSectionIndex]
2x
483
                movedSectionsIndexes.insert(finalSectionIndex)
2x
484
                afterUpdateModel.removeSection(by: section.id)
2x
485
                afterUpdateModel.insertSection(section, at: finalSectionIndex)
2x
486
            case let .itemMove(initialItemIndexPath: initialItemIndexPath, finalItemIndexPath: finalItemIndexPath):
487
                let itemId = itemIdentifier(for: initialItemIndexPath.itemPath, kind: .cell, at: .beforeUpdate)!
4x
488
                let item = layout(at: .beforeUpdate).sections[initialItemIndexPath.section].items[initialItemIndexPath.item]
4x
489
                movedIndexes.insert(initialItemIndexPath)
4x
490
                afterUpdateModel.removeItem(by: itemId)
4x
491
                afterUpdateModel.insertItem(item, at: finalItemIndexPath)
4x
492
            }
493
        }
494
42x
495
        afterUpdateModel = LayoutModel(sections: afterUpdateModel.sections.map { section -> SectionModel in
60x
496
            var section = section
60x
497
            section.assembleLayout()
60x
498
            return section
60x
499
        }, collectionLayout: layoutRepresentation)
60x
500
        afterUpdateModel.assembleLayout()
42x
501
        storage[.afterUpdate] = afterUpdateModel
42x
502
42x
503
        // Calculating potential content offset changes after the updates
42x
504
        insertedSectionsIndexes.sorted(by: { $0 < $1 }).forEach {
42x
505
            compensateOffsetOfSectionIfNeeded(for: $0, action: .insert)
2x
506
        }
2x
507
        reloadedSectionsIndexes.sorted(by: { $0 < $1 }).forEach {
42x
508
            let oldSection = section(at: $0, at: .beforeUpdate)
5x
509
            guard let newSectionIndex = sectionIndex(for: oldSection.id, at: .afterUpdate) else {
5x
510
                assertionFailure("Section with identifier \(oldSection.id) does not exist.")
!
511
                return
!
512
            }
5x
513
            let newSection = section(at: newSectionIndex, at: .afterUpdate)
5x
514
            compensateOffsetOfSectionIfNeeded(for: $0, action: .frameUpdate(previousFrame: oldSection.frame, newFrame: newSection.frame))
5x
515
        }
5x
516
        deletedSectionsIndexes.sorted(by: { $0 < $1 }).forEach {
42x
517
            compensateOffsetOfSectionIfNeeded(for: $0, action: .delete)
2x
518
        }
2x
519
42x
520
        reloadedIndexes.sorted(by: { $0 < $1 }).forEach {
521
            guard let oldItem = item(for: $0.itemPath, kind: .cell, at: .beforeUpdate),
10300x
522
                  let newItemIndexPath = itemPath(by: oldItem.id, kind: .cell, at: .afterUpdate),
10300x
523
                  let newItem = item(for: newItemIndexPath, kind: .cell, at: .afterUpdate) else {
10300x
524
                assertionFailure("Internal inconsistency.")
!
525
                return
!
526
            }
10300x
527
            compensateOffsetIfNeeded(for: $0.itemPath, kind: .cell, action: .frameUpdate(previousFrame: oldItem.frame, newFrame: newItem.frame))
10300x
528
        }
10300x
529
42x
530
        insertedIndexes.sorted(by: { $0 < $1 }).forEach {
1850000x
531
            compensateOffsetIfNeeded(for: $0.itemPath, kind: .cell, action: .insert)
532
        }
533
        deletedIndexes.sorted(by: { $0 < $1 }).forEach {
1840000x
534
            compensateOffsetIfNeeded(for: $0.itemPath, kind: .cell, action: .delete)
535
        }
536
42x
537
        totalProposedCompensatingOffset = proposedCompensatingOffset
42x
538
    }
42x
539
540
    func commitUpdates() {
12x
541
        insertedIndexes = []
12x
542
        insertedSectionsIndexes = []
12x
543
12x
544
        reloadedIndexes = []
12x
545
        reloadedSectionsIndexes = []
12x
546
12x
547
        movedIndexes = []
12x
548
        movedSectionsIndexes = []
12x
549
12x
550
        deletedIndexes = []
12x
551
        deletedSectionsIndexes = []
12x
552
12x
553
        storage[.beforeUpdate] = layout(at: .afterUpdate)
12x
554
        storage[.afterUpdate] = nil
12x
555
12x
556
        totalProposedCompensatingOffset = 0
12x
557
12x
558
        cachedAttributeObjects[.beforeUpdate] = cachedAttributeObjects[.afterUpdate]
12x
559
        resetCachedAttributeObjects(at: .afterUpdate)
12x
560
    }
12x
561
562
    func contentSize(for state: ModelState) -> CGSize {
1x
563
        let contentHeight = contentHeight(at: state)
1x
564
        guard contentHeight != 0 else {
1x
565
            return .zero
!
566
        }
1x
567
        // This is a workaround for `layoutAttributesForElementsInRect:` not getting invoked enough
1x
568
        // times if `collectionViewContentSize.width` is not smaller than the width of the collection
1x
569
        // view, minus horizontal insets. This results in visual defects when performing batch
1x
570
        // updates. To work around this, we subtract 0.0001 from our content size width calculation;
1x
571
        // this small decrease in `collectionViewContentSize.width` is enough to work around the
1x
572
        // incorrect, internal collection view `CGRect` checks, without introducing any visual
1x
573
        // differences for elements in the collection view.
1x
574
        // See https://openradar.appspot.com/radar?id=5025850143539200 for more details.
1x
575
        let contentSize = CGSize(width: layoutRepresentation.visibleBounds.size.width - 0.0001, height: contentHeight)
1x
576
        return contentSize
1x
577
    }
1x
578
579
    func offsetByTotalCompensation(attributes: UICollectionViewLayoutAttributes?, for state: ModelState, backward: Bool = false) {
!
580
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates,
!
581
              state == .afterUpdate,
!
582
              let attributes = attributes else {
!
583
            return
!
584
        }
!
585
        if backward, isLayoutBiggerThanVisibleBounds(at: .afterUpdate) {
!
586
            attributes.frame = attributes.frame.offsetBy(dx: 0, dy: totalProposedCompensatingOffset * -1)
!
587
        } else if !backward, isLayoutBiggerThanVisibleBounds(at: .afterUpdate) {
!
588
            attributes.frame = attributes.frame.offsetBy(dx: 0, dy: totalProposedCompensatingOffset)
!
589
        }
!
590
    }
!
591
592
    func layout(at state: ModelState) -> LayoutModel {
1440000x
593
        guard let layout = storage[state] else {
1440000x
594
            assertionFailure("Internal inconsistency. Layout at \(state) is missing.")
!
595
            return LayoutModel(sections: [], collectionLayout: layoutRepresentation)
!
596
        }
1440000x
597
        return layout
1440000x
598
    }
1440000x
599
600
    func isLayoutBiggerThanVisibleBounds(at state: ModelState, withFullCompensation: Bool = false) -> Bool {
601
        let visibleBoundsHeight = layoutRepresentation.visibleBounds.height + (withFullCompensation ? batchUpdateCompensatingOffset + proposedCompensatingOffset : 0)
602
        return contentHeight(at: state).rounded() > visibleBoundsHeight.rounded()
603
    }
604
605
    private func allAttributes(at state: ModelState, visibleRect: CGRect? = nil) -> [ChatLayoutAttributes] {
4x
606
        let layout = layout(at: state)
4x
607
4x
608
        if let visibleRect = visibleRect {
4x
609
            enum TraverseState {
4x
610
                case notFound
4x
611
                case found
4x
612
                case done
4x
613
            }
4x
614
4x
615
            var traverseState: TraverseState = .notFound
4x
616
4x
617
            func check(rect: CGRect) -> Bool {
60x
618
                switch traverseState {
60x
619
                case .notFound:
60x
620
                    if visibleRect.intersects(rect) {
4x
621
                        traverseState = .found
4x
622
                        return true
4x
623
                    } else {
4x
624
                        return false
!
625
                    }
60x
626
                case .found:
60x
627
                    if visibleRect.intersects(rect) {
52x
628
                        return true
48x
629
                    } else {
48x
630
                        if rect.minY > visibleRect.maxY + batchUpdateCompensatingOffset + proposedCompensatingOffset {
4x
631
                            traverseState = .done
4x
632
                        }
4x
633
                        return false
4x
634
                    }
60x
635
                case .done:
60x
636
                    return false
4x
637
                }
60x
638
            }
60x
639
4x
640
            var allRects = [(frame: CGRect, indexPath: ItemPath, kind: ItemKind)]()
4x
641
            // I dont think there can be more then a 200 elements on the screen simultaneously
4x
642
            allRects.reserveCapacity(200)
4x
643
            for sectionIndex in 0..<layout.sections.count {
12x
644
                let section = layout.sections[sectionIndex]
12x
645
                let sectionPath = ItemPath(item: 0, section: sectionIndex)
12x
646
                if let headerFrame = itemFrame(for: sectionPath, kind: .header, at: state, isFinal: true),
12x
647
                   check(rect: headerFrame) {
12x
648
                    allRects.append((frame: headerFrame, indexPath: sectionPath, kind: .header))
8x
649
                }
12x
650
                guard traverseState != .done else {
12x
651
                    break
4x
652
                }
8x
653
8x
654
                var startingIndex = 0
8x
655
                // If header is not visible
8x
656
                if traverseState == .notFound, !section.items.isEmpty {
8x
657
                    func predicate(itemIndex: Int) -> ComparisonResult {
!
658
                        let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
!
659
                        guard let itemFrame = itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true) else {
!
660
                            return .orderedDescending
!
661
                        }
!
662
                        if itemFrame.intersects(visibleRect) {
!
663
                            return .orderedSame
!
664
                        } else if itemFrame.minY > visibleRect.maxY {
!
665
                            return .orderedDescending
!
666
                        } else if itemFrame.maxX < visibleRect.minY {
!
667
                            return .orderedAscending
!
668
                        }
!
669
                        return .orderedSame
!
670
                    }
!
671
!
672
                    // Find if any of the items of the section is visible
!
673
                    if [ComparisonResult.orderedSame, .orderedDescending].contains(predicate(itemIndex: section.items.count - 1)),
!
674
                       let firstMatchingIndex = Array(0...section.items.count - 1).binarySearch(predicate: predicate) {
!
675
                        // Find first item that is visible
!
676
                        startingIndex = firstMatchingIndex
!
677
                        for itemIndex in (0..<firstMatchingIndex).reversed() {
!
678
                            let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
!
679
                            guard let itemFrame = itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true) else {
!
680
                                continue
!
681
                            }
!
682
                            guard itemFrame.maxY >= visibleRect.minY else {
!
683
                                break
!
684
                            }
!
685
                            startingIndex = itemIndex
!
686
                        }
!
687
                    } else {
!
688
                        // Otherwise we can safely skip all the items in the section and go to footer.
!
689
                        startingIndex = section.items.count
!
690
                    }
!
691
                }
8x
692
8x
693
                if startingIndex < section.items.count {
8x
694
                    for itemIndex in startingIndex..<section.items.count {
40x
695
                        let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
40x
696
                        if let itemFrame = itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true),
40x
697
                           check(rect: itemFrame) {
40x
698
                            if state == .beforeUpdate || isAnimatedBoundsChange {
40x
699
                                allRects.append((frame: itemFrame, indexPath: itemPath, kind: .cell))
40x
700
                            } else {
40x
701
                                var itemWasVisibleBefore: Bool {
!
702
                                    guard let itemIdentifier = itemIdentifier(for: itemPath, kind: .cell, at: .afterUpdate),
!
703
                                          let initialIndexPath = self.itemPath(by: itemIdentifier, kind: .cell, at: .beforeUpdate),
!
704
                                          let item = item(for: initialIndexPath, kind: .cell, at: .beforeUpdate),
!
705
                                          item.calculatedOnce == true,
!
706
                                          let itemFrame = self.itemFrame(for: initialIndexPath, kind: .cell, at: .beforeUpdate, isFinal: false),
!
707
                                          itemFrame.intersects(layoutRepresentation.visibleBounds.offsetBy(dx: 0, dy: -totalProposedCompensatingOffset)) else {
!
708
                                        return false
!
709
                                    }
!
710
                                    return true
!
711
                                }
!
712
                                var itemWillBeVisible: Bool {
!
713
                                    let offsetVisibleBounds = layoutRepresentation.visibleBounds.offsetBy(dx: 0, dy: proposedCompensatingOffset + batchUpdateCompensatingOffset)
!
714
                                    if insertedIndexes.contains(itemPath.indexPath),
!
715
                                       let itemFrame = self.itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true),
!
716
                                       itemFrame.intersects(offsetVisibleBounds) {
!
717
                                        return true
!
718
                                    }
!
719
                                    if let itemIdentifier = itemIdentifier(for: itemPath, kind: .cell, at: .afterUpdate),
!
720
                                       let initialIndexPath = self.itemPath(by: itemIdentifier, kind: .cell, at: .beforeUpdate)?.indexPath,
!
721
                                       movedIndexes.contains(initialIndexPath) || reloadedIndexes.contains(initialIndexPath),
!
722
                                       let itemFrame = self.itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true),
!
723
                                       itemFrame.intersects(offsetVisibleBounds) {
!
724
                                        return true
!
725
                                    }
!
726
                                    return false
!
727
                                }
!
728
                                if itemWillBeVisible || itemWasVisibleBefore {
!
729
                                    allRects.append((frame: itemFrame, indexPath: itemPath, kind: .cell))
!
730
                                }
!
731
                            }
40x
732
                        }
40x
733
                        guard traverseState != .done else {
40x
734
                            break
!
735
                        }
40x
736
                    }
40x
737
                }
8x
738
8x
739
                if let footerFrame = itemFrame(for: sectionPath, kind: .footer, at: state, isFinal: true),
8x
740
                   check(rect: footerFrame) {
8x
741
                    allRects.append((frame: footerFrame, indexPath: sectionPath, kind: .footer))
4x
742
                }
8x
743
            }
8x
744
4x
745
            return allRects.compactMap { frame, path, kind -> ChatLayoutAttributes? in
52x
746
                itemAttributes(for: path, kind: kind, predefinedFrame: frame, at: state)
52x
747
            }
52x
748
        } else {
4x
749
            // Debug purposes only.
!
750
            var attributes = [ChatLayoutAttributes]()
!
751
            attributes.reserveCapacity(layout.sections.count * 1000)
!
752
            layout.sections.enumerated().forEach { sectionIndex, section in
!
753
                let sectionPath = ItemPath(item: 0, section: sectionIndex)
!
754
                if let headerAttributes = itemAttributes(for: sectionPath, kind: .header, at: state) {
!
755
                    attributes.append(headerAttributes)
!
756
                }
!
757
                if let footerAttributes = itemAttributes(for: sectionPath, kind: .footer, at: state) {
!
758
                    attributes.append(footerAttributes)
!
759
                }
!
760
                section.items.enumerated().forEach { itemIndex, _ in
!
761
                    let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
!
762
                    if let itemAttributes = itemAttributes(for: itemPath, kind: .cell, at: state) {
!
763
                        attributes.append(itemAttributes)
!
764
                    }
!
765
                }
!
766
            }
!
767
!
768
            return attributes
!
769
        }
!
770
    }
!
771
772
    private func compensateOffsetIfNeeded(for itemPath: ItemPath, kind: ItemKind, action: CompensatingAction) {
773
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates else {
774
            return
!
775
        }
776
        let minY = (layoutRepresentation.visibleBounds.lowerPoint.y + batchUpdateCompensatingOffset + proposedCompensatingOffset).rounded()
777
        switch action {
778
        case .insert:
779
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate),
780
                  let itemFrame = itemFrame(for: itemPath, kind: kind, at: .afterUpdate) else {
781
                return
2x
782
            }
783
            if itemFrame.minY.rounded() - layoutRepresentation.settings.interItemSpacing <= minY {
784
                proposedCompensatingOffset += itemFrame.height + layoutRepresentation.settings.interItemSpacing
785
            }
786
        case let .frameUpdate(previousFrame, newFrame):
787
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate, withFullCompensation: true) else {
20300x
788
                return
10000x
789
            }
10300x
790
            if newFrame.minY.rounded() <= minY {
10300x
791
                batchUpdateCompensatingOffset += newFrame.height - previousFrame.height
104x
792
            }
793
        case .delete:
794
            guard isLayoutBiggerThanVisibleBounds(at: .beforeUpdate),
795
                  let deletedFrame = itemFrame(for: itemPath, kind: kind, at: .beforeUpdate) else {
796
                return
4x
797
            }
798
            if deletedFrame.minY.rounded() <= minY {
799
                // Changing content offset for deleted items using `invalidateLayout(with:) causes UI glitches.
40x
800
                // So we are using targetContentOffset(forProposedContentOffset:) which is going to be called after.
40x
801
                proposedCompensatingOffset -= (deletedFrame.height + layoutRepresentation.settings.interItemSpacing)
40x
802
            }
803
        }
804
805
    }
806
807
    private func compensateOffsetOfSectionIfNeeded(for sectionIndex: Int, action: CompensatingAction) {
9x
808
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates else {
9x
809
            return
!
810
        }
9x
811
        let minY = (layoutRepresentation.visibleBounds.lowerPoint.y + batchUpdateCompensatingOffset + proposedCompensatingOffset).rounded()
9x
812
        switch action {
9x
813
        case .insert:
9x
814
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate),
2x
815
                  sectionIndex < layout(at: .afterUpdate).sections.count else {
2x
816
                return
!
817
            }
2x
818
            let section = layout(at: .afterUpdate).sections[sectionIndex]
2x
819
2x
820
            if section.offsetY.rounded() - layoutRepresentation.settings.interSectionSpacing <= minY {
2x
821
                proposedCompensatingOffset += section.height + layoutRepresentation.settings.interSectionSpacing
!
822
            }
9x
823
        case let .frameUpdate(previousFrame, newFrame):
9x
824
            guard sectionIndex < layout(at: .afterUpdate).sections.count,
5x
825
                  isLayoutBiggerThanVisibleBounds(at: .afterUpdate, withFullCompensation: true) else {
5x
826
                return
!
827
            }
5x
828
            if newFrame.minY.rounded() <= minY {
5x
829
                batchUpdateCompensatingOffset += newFrame.height - previousFrame.height
2x
830
            }
9x
831
        case .delete:
9x
832
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate),
2x
833
                  sectionIndex < layout(at: .afterUpdate).sections.count else {
2x
834
                return
1x
835
            }
1x
836
            let section = layout(at: .beforeUpdate).sections[sectionIndex]
1x
837
            if section.locationHeight.rounded() <= minY {
1x
838
                // Changing content offset for deleted items using `invalidateLayout(with:) causes UI glitches.
!
839
                // So we are using targetContentOffset(forProposedContentOffset:) which is going to be called after.
!
840
                proposedCompensatingOffset -= (section.height + layoutRepresentation.settings.interSectionSpacing)
!
841
            }
9x
842
        }
9x
843
9x
844
    }
9x
845
846
    private func offsetByCompensation(frame: CGRect,
847
                                      at itemPath: ItemPath,
848
                                      for state: ModelState,
849
                                      backward: Bool = false) -> CGRect {
376x
850
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates,
376x
851
              state == .afterUpdate,
376x
852
              isLayoutBiggerThanVisibleBounds(at: .afterUpdate) else {
376x
853
            return frame
376x
854
        }
376x
855
        return frame.offsetBy(dx: 0, dy: proposedCompensatingOffset * (backward ? -1 : 1))
!
856
    }
376x
857
858
}
859
860
extension RandomAccessCollection where Index == Int {
861
862
    func binarySearch(predicate: (Element) -> ComparisonResult) -> Index? {
11x
863
        var lowerBound = startIndex
11x
864
        var upperBound = endIndex
11x
865
11x
866
        while lowerBound < upperBound {
15x
867
            let midIndex = lowerBound + (upperBound - lowerBound) / 2
14x
868
            if predicate(self[midIndex]) == .orderedSame {
14x
869
                return midIndex
10x
870
            } else if predicate(self[midIndex]) == .orderedAscending {
10x
871
                lowerBound = midIndex + 1
2x
872
            } else {
4x
873
                upperBound = midIndex
2x
874
            }
4x
875
        }
4x
876
        return nil
1x
877
    }
11x
878
879
    func binarySearchRange(predicate: (Element) -> ComparisonResult) -> [Element] {
11x
880
        guard let firstMatchingIndex = binarySearch(predicate: predicate) else {
11x
881
            return []
1x
882
        }
10x
883
10x
884
        var startingIndex = firstMatchingIndex
10x
885
        for index in (0..<firstMatchingIndex).reversed() {
155x
886
            let attributes = self[index]
155x
887
            guard predicate(attributes) == .orderedSame else {
155x
888
                break
2x
889
            }
153x
890
            startingIndex = index
153x
891
        }
153x
892
10x
893
        var lastIndex = firstMatchingIndex
10x
894
        for index in (firstMatchingIndex + 1)..<count {
213x
895
            let attributes = self[index]
213x
896
            guard predicate(attributes) == .orderedSame else {
213x
897
                break
6x
898
            }
207x
899
            lastIndex = index
207x
900
        }
207x
901
        return Array(self[startingIndex...lastIndex])
10x
902
    }
10x
903
904
}