Slather logo

Coverage for "StateController.swift" : 80.40%

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