Slather logo

Coverage for "StateController.swift" : 78.90%

(561 of 711 relevant lines covered)

ChatLayout/Classes/Core/Model/StateController.swift

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