Slather logo

Coverage for "StateController.swift" : 79.12%

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