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.withUnsafeBufferPointer { $0.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.withUnsafeBufferPointer { $0.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
        #if DEBUG
10x
298
        guard index < layout(at: state).sections.count else {
!
299
            preconditionFailure("Section index \(index) is bigger than the amount of sections \(layout(at: state).sections.count).")
10x
300
        }
10x
301
        #endif
10x
302
        return layout(at: state).sections[index]
303
    }
304
305
    func itemIdentifier(for itemPath: ItemPath, kind: ItemKind, at state: ModelState) -> UUID? {
2x
306
        guard itemPath.section < layout(at: state).sections.count else {
2x
307
            // This occurs when getting layout attributes for initial / final animations
308
            return nil
309
        }
310
        let sectionModel = layout(at: state).sections[itemPath.section]
311
        switch kind {
312
        case .cell:
3x
313
            guard itemPath.item < layout(at: state).sections[itemPath.section].items.count else {
3x
314
                // This occurs when getting layout attributes for initial / final animations
315
                return nil
316
            }
317
            let rowModel = sectionModel.items[itemPath.item]
318
            return rowModel.id
32x
319
        case .header, .footer:
4x
320
            guard let item = item(for: ItemPath(item: 0, section: itemPath.section), kind: kind, at: state) else {
28x
321
                return nil
28x
322
            }
323
            return item.id
324
        }
325
326
    }
4x
327
4x
328
    func numberOfSections(at state: ModelState) -> Int {
4x
329
        layout(at: state).sections.count
330
    }
28x
331
28x
332
    func numberOfItems(in sectionIndex: Int, at state: ModelState) -> Int {
28x
333
        layout(at: state).sections[sectionIndex].items.count
334
    }
335
336
    func item(for itemPath: ItemPath, kind: ItemKind, at state: ModelState) -> ItemModel? {
337
        switch kind {
61x
338
        case .header:
61x
339
            guard itemPath.section < layout(at: state).sections.count,
1x
340
                  itemPath.item == 0 else {
1x
341
                // This occurs when getting layout attributes for initial / final animations
60x
342
                return nil
60x
343
            }
3x
344
            guard let header = layout(at: state).sections[itemPath.section].header else {
57x
345
                return nil
57x
346
            }
347
            return header
46x
348
        case .footer:
46x
349
            guard itemPath.section < layout(at: state).sections.count,
1x
350
                  itemPath.item == 0 else {
1x
351
                // This occurs when getting layout attributes for initial / final animations
45x
352
                return nil
45x
353
            }
1x
354
            guard let footer = layout(at: state).sections[itemPath.section].footer else {
44x
355
                return nil
44x
356
            }
357
            return footer
358
        case .cell:
359
            guard itemPath.section < layout(at: state).sections.count,
!
360
                  itemPath.item < layout(at: state).sections[itemPath.section].items.count else {
!
361
                // This occurs when getting layout attributes for initial / final animations
362
                return nil
363
            }
364
            return layout(at: state).sections[itemPath.section].items[itemPath.item]
365
        }
366
    }
10000x
367
10000x
368
    func update(preferredSize: CGSize, alignment: ChatItemAlignment, for itemPath: ItemPath, kind: ItemKind, at state: ModelState) {
!
369
        guard var item = item(for: itemPath, kind: kind, at: state) else {
!
370
            assertionFailure("Item at index path (\(itemPath.section) - \(itemPath.item)) does not exist.")
10000x
371
            return
10000x
372
        }
10000x
373
        var layout = layout(at: state)
10000x
374
        let previousFrame = item.frame
10000x
375
        cachedAttributesState = nil
10000x
376
        item.alignment = alignment
10000x
377
        item.calculatedSize = preferredSize
10000x
378
        item.calculatedOnce = true
10000x
379
10000x
380
        switch kind {
3x
381
        case .header:
10000x
382
            layout.setAndAssemble(header: item, sectionIndex: itemPath.section)
3x
383
        case .footer:
10000x
384
            layout.setAndAssemble(footer: item, sectionIndex: itemPath.section)
10000x
385
        case .cell:
10000x
386
            layout.setAndAssemble(item: item, sectionIndex: itemPath.section, itemIndex: itemPath.item)
10000x
387
        }
10000x
388
        storage[state] = layout
10000x
389
        let frameUpdateAction = CompensatingAction.frameUpdate(previousFrame: previousFrame, newFrame: item.frame)
10000x
390
        compensateOffsetIfNeeded(for: itemPath, kind: kind, action: frameUpdateAction)
391
    }
42x
392
42x
393
    func process(changeItems: [ChangeItem]) {
42x
394
        batchUpdateCompensatingOffset = 0
42x
395
        proposedCompensatingOffset = 0
42x
396
        let changeItems = changeItems.sorted()
42x
397
42x
398
        var afterUpdateModel = layout(at: .beforeUpdate)
42x
399
        resetCachedAttributeObjects()
400
401
        changeItems.forEach { updateItem in
402
            switch updateItem {
350x
403
            case let .sectionInsert(sectionIndex: sectionIndex):
350x
404
                let items = (0..<layoutRepresentation.numberOfItems(in: sectionIndex)).map { index -> ItemModel in
350x
405
                    let itemIndexPath = IndexPath(item: index, section: sectionIndex)
350x
406
                    return ItemModel(with: layoutRepresentation.configuration(for: .cell, at: itemIndexPath.itemPath))
2x
407
                }
2x
408
                let header: ItemModel?
1x
409
                if layoutRepresentation.shouldPresentHeader(at: sectionIndex) == true {
1x
410
                    let headerIndexPath = IndexPath(item: 0, section: sectionIndex)
2x
411
                    header = ItemModel(with: layoutRepresentation.configuration(for: .header, at: headerIndexPath.itemPath))
1x
412
                } else {
2x
413
                    header = nil
2x
414
                }
2x
415
                let footer: ItemModel?
2x
416
                if layoutRepresentation.shouldPresentFooter(at: sectionIndex) == true {
2x
417
                    let footerIndexPath = IndexPath(item: 0, section: sectionIndex)
2x
418
                    footer = ItemModel(with: layoutRepresentation.configuration(for: .footer, at: footerIndexPath.itemPath))
!
419
                } else {
2x
420
                    footer = nil
2x
421
                }
2x
422
                let section = SectionModel(header: header, footer: footer, items: items, collectionLayout: layoutRepresentation)
2x
423
                afterUpdateModel.insertSection(section, at: sectionIndex)
424
                insertedSectionsIndexes.insert(sectionIndex)
425
            case let .itemInsert(itemIndexPath: indexPath):
426
                let item = ItemModel(with: layoutRepresentation.configuration(for: .cell, at: indexPath.itemPath))
427
                insertedIndexes.insert(indexPath)
428
                afterUpdateModel.insertItem(item, at: indexPath)
2x
429
            case let .sectionDelete(sectionIndex: sectionIndex):
2x
430
                let section = layout(at: .beforeUpdate).sections[sectionIndex]
2x
431
                deletedSectionsIndexes.insert(sectionIndex)
432
                afterUpdateModel.removeSection(by: section.id)
433
            case let .itemDelete(itemIndexPath: indexPath):
434
                let itemId = itemIdentifier(for: indexPath.itemPath, kind: .cell, at: .beforeUpdate)!
435
                afterUpdateModel.removeItem(by: itemId)
436
                deletedIndexes.insert(indexPath)
5x
437
            case let .sectionReload(sectionIndex: sectionIndex):
5x
438
                reloadedSectionsIndexes.insert(sectionIndex)
5x
439
                var section = layout(at: .beforeUpdate).sections[sectionIndex]
5x
440
5x
441
                var header: ItemModel?
3x
442
                if layoutRepresentation.shouldPresentHeader(at: sectionIndex) == true {
3x
443
                    let headerIndexPath = IndexPath(item: 0, section: sectionIndex)
3x
444
                    header = section.header ?? ItemModel(with: layoutRepresentation.configuration(for: .header, at: headerIndexPath.itemPath))
3x
445
                    header?.resetSize()
3x
446
                    if section.header != nil {
3x
447
                        header?.alignment = layoutRepresentation.alignment(for: .cell, at: headerIndexPath.itemPath)
5x
448
                    }
2x
449
                } else {
5x
450
                    header = nil
5x
451
                }
5x
452
                section.set(header: header)
5x
453
5x
454
                var footer: ItemModel?
4x
455
                if layoutRepresentation.shouldPresentFooter(at: sectionIndex) == true {
4x
456
                    let footerIndexPath = IndexPath(item: 0, section: sectionIndex)
4x
457
                    footer = section.footer ?? ItemModel(with: layoutRepresentation.configuration(for: .footer, at: footerIndexPath.itemPath))
4x
458
                    footer?.resetSize()
4x
459
                    if section.footer != nil {
4x
460
                        footer?.alignment = layoutRepresentation.alignment(for: .cell, at: footerIndexPath.itemPath)
5x
461
                    }
1x
462
                } else {
5x
463
                    footer = nil
5x
464
                }
5x
465
                section.set(footer: footer)
5x
466
550x
467
                let oldItems = section.items
550x
468
                let items: [ItemModel] = (0..<layoutRepresentation.numberOfItems(in: sectionIndex)).map { index in
550x
469
                    var newItem: ItemModel
550x
470
                    let itemIndexPath = IndexPath(item: index, section: sectionIndex)
450x
471
                    if index < oldItems.count {
450x
472
                        newItem = oldItems[index]
550x
473
                        newItem.alignment = layoutRepresentation.alignment(for: .cell, at: itemIndexPath.itemPath)
100x
474
                    } else {
550x
475
                        newItem = ItemModel(with: layoutRepresentation.configuration(for: .cell, at: itemIndexPath.itemPath))
550x
476
                    }
550x
477
                    newItem.resetSize()
550x
478
                    return newItem
5x
479
                }
5x
480
                section.set(items: items)
5x
481
                afterUpdateModel.removeSection(for: sectionIndex)
482
                afterUpdateModel.insertSection(section, at: sectionIndex)
10300x
483
            case let .itemReload(itemIndexPath: indexPath):
!
484
                guard var item = item(for: indexPath.itemPath, kind: .cell, at: .beforeUpdate) else {
!
485
                    assertionFailure("Item at index path (\(indexPath.section) - \(indexPath.item)) does not exist.")
10300x
486
                    return
10300x
487
                }
10300x
488
                item.resetSize()
10300x
489
                item.alignment = layoutRepresentation.alignment(for: .cell, at: indexPath.itemPath)
10300x
490
                afterUpdateModel.replaceItem(item, at: indexPath)
491
                reloadedIndexes.insert(indexPath)
2x
492
            case let .sectionMove(initialSectionIndex: initialSectionIndex, finalSectionIndex: finalSectionIndex):
2x
493
                let section = layout(at: .beforeUpdate).sections[initialSectionIndex]
2x
494
                movedSectionsIndexes.insert(finalSectionIndex)
2x
495
                afterUpdateModel.removeSection(by: section.id)
496
                afterUpdateModel.insertSection(section, at: finalSectionIndex)
4x
497
            case let .itemMove(initialItemIndexPath: initialItemIndexPath, finalItemIndexPath: finalItemIndexPath):
4x
498
                let itemId = itemIdentifier(for: initialItemIndexPath.itemPath, kind: .cell, at: .beforeUpdate)!
4x
499
                let item = layout(at: .beforeUpdate).sections[initialItemIndexPath.section].items[initialItemIndexPath.item]
4x
500
                movedIndexes.insert(initialItemIndexPath)
4x
501
                afterUpdateModel.removeItem(by: itemId)
502
                afterUpdateModel.insertItem(item, at: finalItemIndexPath)
503
            }
42x
504
        }
60x
505
60x
506
        var afterUpdateModelSections = afterUpdateModel.sections
60x
507
        afterUpdateModelSections.withUnsafeMutableBufferPointer { directlyMutableSections in
60x
508
            for index in 0..<directlyMutableSections.count {
60x
509
                directlyMutableSections[index].assembleLayout()
42x
510
            }
42x
511
        }
42x
512
        afterUpdateModel = LayoutModel(sections: afterUpdateModelSections, collectionLayout: layoutRepresentation)
42x
513
42x
514
        afterUpdateModel.assembleLayout()
2x
515
        storage[.afterUpdate] = afterUpdateModel
2x
516
42x
517
        // Calculating potential content offset changes after the updates
5x
518
        insertedSectionsIndexes.sorted(by: { $0 < $1 }).forEach {
5x
519
            compensateOffsetOfSectionIfNeeded(for: $0, action: .insert)
!
520
        }
!
521
        reloadedSectionsIndexes.sorted(by: { $0 < $1 }).forEach {
5x
522
            let oldSection = section(at: $0, at: .beforeUpdate)
5x
523
            guard let newSectionIndex = sectionIndex(for: oldSection.id, at: .afterUpdate) else {
5x
524
                assertionFailure("Section with identifier \(oldSection.id) does not exist.")
5x
525
                return
42x
526
            }
2x
527
            let newSection = section(at: newSectionIndex, at: .afterUpdate)
2x
528
            compensateOffsetOfSectionIfNeeded(for: $0, action: .frameUpdate(previousFrame: oldSection.frame, newFrame: newSection.frame))
42x
529
        }
530
        deletedSectionsIndexes.sorted(by: { $0 < $1 }).forEach {
10300x
531
            compensateOffsetOfSectionIfNeeded(for: $0, action: .delete)
10300x
532
        }
10300x
533
!
534
        reloadedIndexes.sorted(by: { $0 < $1 }).forEach {
!
535
            guard let oldItem = item(for: $0.itemPath, kind: .cell, at: .beforeUpdate),
10300x
536
                  let newItemIndexPath = itemPath(by: oldItem.id, kind: .cell, at: .afterUpdate),
10300x
537
                  let newItem = item(for: newItemIndexPath, kind: .cell, at: .afterUpdate) else {
10300x
538
                assertionFailure("Internal inconsistency.")
42x
539
                return
1850000x
540
            }
541
            compensateOffsetIfNeeded(for: $0.itemPath, kind: .cell, action: .frameUpdate(previousFrame: oldItem.frame, newFrame: newItem.frame))
542
        }
1850000x
543
544
        insertedIndexes.sorted(by: { $0 < $1 }).forEach {
545
            compensateOffsetIfNeeded(for: $0.itemPath, kind: .cell, action: .insert)
42x
546
        }
42x
547
        deletedIndexes.sorted(by: { $0 < $1 }).forEach {
42x
548
            compensateOffsetIfNeeded(for: $0.itemPath, kind: .cell, action: .delete)
549
        }
12x
550
12x
551
        totalProposedCompensatingOffset = proposedCompensatingOffset
12x
552
    }
12x
553
12x
554
    func commitUpdates() {
12x
555
        insertedIndexes = []
12x
556
        insertedSectionsIndexes = []
12x
557
12x
558
        reloadedIndexes = []
12x
559
        reloadedSectionsIndexes = []
12x
560
12x
561
        movedIndexes = []
12x
562
        movedSectionsIndexes = []
12x
563
12x
564
        deletedIndexes = []
12x
565
        deletedSectionsIndexes = []
12x
566
12x
567
        storage[.beforeUpdate] = layout(at: .afterUpdate)
12x
568
        storage[.afterUpdate] = nil
12x
569
12x
570
        totalProposedCompensatingOffset = 0
571
1x
572
        cachedAttributeObjects[.beforeUpdate] = cachedAttributeObjects[.afterUpdate]
1x
573
        resetCachedAttributeObjects(at: .afterUpdate)
1x
574
    }
!
575
1x
576
    func contentSize(for state: ModelState) -> CGSize {
1x
577
        let contentHeight = contentHeight(at: state)
1x
578
        guard contentHeight != 0 else {
1x
579
            return .zero
1x
580
        }
1x
581
        // This is a workaround for `layoutAttributesForElementsInRect:` not getting invoked enough
1x
582
        // times if `collectionViewContentSize.width` is not smaller than the width of the collection
1x
583
        // view, minus horizontal insets. This results in visual defects when performing batch
1x
584
        // updates. To work around this, we subtract 0.0001 from our content size width calculation;
1x
585
        // this small decrease in `collectionViewContentSize.width` is enough to work around the
1x
586
        // incorrect, internal collection view `CGRect` checks, without introducing any visual
1x
587
        // differences for elements in the collection view.
588
        // See https://openradar.appspot.com/radar?id=5025850143539200 for more details.
!
589
        let contentSize = CGSize(width: layoutRepresentation.visibleBounds.size.width - 0.0001, height: contentHeight)
!
590
        return contentSize
!
591
    }
!
592
!
593
    func offsetByTotalCompensation(attributes: UICollectionViewLayoutAttributes?, for state: ModelState, backward: Bool = false) {
!
594
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates,
!
595
              state == .afterUpdate,
!
596
              let attributes = attributes else {
!
597
            return
!
598
        }
!
599
        if backward, isLayoutBiggerThanVisibleBounds(at: .afterUpdate) {
!
600
            attributes.frame = attributes.frame.offsetBy(dx: 0, dy: totalProposedCompensatingOffset * -1)
601
        } else if !backward, isLayoutBiggerThanVisibleBounds(at: .afterUpdate) {
1440000x
602
            attributes.frame = attributes.frame.offsetBy(dx: 0, dy: totalProposedCompensatingOffset)
1440000x
603
        }
!
604
    }
!
605
1440000x
606
    func layout(at state: ModelState) -> LayoutModel {
1440000x
607
        guard let layout = storage[state] else {
1440000x
608
            assertionFailure("Internal inconsistency. Layout at \(state) is missing.")
609
            return LayoutModel(sections: [], collectionLayout: layoutRepresentation)
610
        }
611
        return layout
612
    }
613
614
    func isLayoutBiggerThanVisibleBounds(at state: ModelState, withFullCompensation: Bool = false) -> Bool {
4x
615
        let visibleBoundsHeight = layoutRepresentation.visibleBounds.height + (withFullCompensation ? batchUpdateCompensatingOffset + proposedCompensatingOffset : 0)
4x
616
        return contentHeight(at: state).rounded() > visibleBoundsHeight.rounded()
4x
617
    }
4x
618
4x
619
    private func allAttributes(at state: ModelState, visibleRect: CGRect? = nil) -> [ChatLayoutAttributes] {
4x
620
        let layout = layout(at: state)
4x
621
4x
622
        if let visibleRect = visibleRect {
4x
623
            enum TraverseState {
4x
624
                case notFound
4x
625
                case found
4x
626
                case done
60x
627
            }
60x
628
60x
629
            var traverseState: TraverseState = .notFound
4x
630
4x
631
            func check(rect: CGRect) -> Bool {
4x
632
                switch traverseState {
4x
633
                case .notFound:
!
634
                    if visibleRect.intersects(rect) {
60x
635
                        traverseState = .found
60x
636
                        return true
52x
637
                    } else {
48x
638
                        return false
48x
639
                    }
4x
640
                case .found:
4x
641
                    if visibleRect.intersects(rect) {
4x
642
                        return true
4x
643
                    } else {
60x
644
                        if rect.minY > visibleRect.maxY + batchUpdateCompensatingOffset + proposedCompensatingOffset {
60x
645
                            traverseState = .done
4x
646
                        }
60x
647
                        return false
60x
648
                    }
4x
649
                case .done:
4x
650
                    return false
4x
651
                }
4x
652
            }
12x
653
12x
654
            var allRects = [(frame: CGRect, indexPath: ItemPath, kind: ItemKind)]()
12x
655
            // I dont think there can be more then a 200 elements on the screen simultaneously
12x
656
            allRects.reserveCapacity(200)
12x
657
            for sectionIndex in 0..<layout.sections.count {
8x
658
                let section = layout.sections[sectionIndex]
12x
659
                let sectionPath = ItemPath(item: 0, section: sectionIndex)
12x
660
                if let headerFrame = itemFrame(for: sectionPath, kind: .header, at: state, isFinal: true),
4x
661
                   check(rect: headerFrame) {
8x
662
                    allRects.append((frame: headerFrame, indexPath: sectionPath, kind: .header))
8x
663
                }
8x
664
                guard traverseState != .done else {
8x
665
                    break
8x
666
                }
!
667
!
668
                var startingIndex = 0
!
669
                // If header is not visible
!
670
                if traverseState == .notFound, !section.items.isEmpty {
!
671
                    func predicate(itemIndex: Int) -> ComparisonResult {
!
672
                        let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
!
673
                        guard let itemFrame = itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true) else {
!
674
                            return .orderedDescending
!
675
                        }
!
676
                        if itemFrame.intersects(visibleRect) {
!
677
                            return .orderedSame
!
678
                        } else if itemFrame.minY > visibleRect.maxY {
!
679
                            return .orderedDescending
!
680
                        } else if itemFrame.maxX < visibleRect.minY {
!
681
                            return .orderedAscending
!
682
                        }
!
683
                        return .orderedSame
!
684
                    }
!
685
!
686
                    // Find if any of the items of the section is visible
!
687
                    if [ComparisonResult.orderedSame, .orderedDescending].contains(predicate(itemIndex: section.items.count - 1)),
!
688
                       let firstMatchingIndex = Array(0...section.items.count - 1).withUnsafeBufferPointer({ $0.binarySearch(predicate: predicate) }) {
!
689
                        // Find first item that is visible
!
690
                        startingIndex = firstMatchingIndex
!
691
                        for itemIndex in (0..<firstMatchingIndex).reversed() {
!
692
                            let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
!
693
                            guard let itemFrame = itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true) else {
!
694
                                continue
!
695
                            }
!
696
                            guard itemFrame.maxY >= visibleRect.minY else {
!
697
                                break
!
698
                            }
!
699
                            startingIndex = itemIndex
!
700
                        }
8x
701
                    } else {
8x
702
                        // Otherwise we can safely skip all the items in the section and go to footer.
8x
703
                        startingIndex = section.items.count
40x
704
                    }
40x
705
                }
40x
706
40x
707
                if startingIndex < section.items.count {
40x
708
                    for itemIndex in startingIndex..<section.items.count {
40x
709
                        let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
40x
710
                        if let itemFrame = itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true),
!
711
                           check(rect: itemFrame) {
!
712
                            if state == .beforeUpdate || isAnimatedBoundsChange {
!
713
                                allRects.append((frame: itemFrame, indexPath: itemPath, kind: .cell))
!
714
                            } else {
!
715
                                var itemWasVisibleBefore: Bool {
!
716
                                    guard let itemIdentifier = itemIdentifier(for: itemPath, kind: .cell, at: .afterUpdate),
!
717
                                          let initialIndexPath = self.itemPath(by: itemIdentifier, kind: .cell, at: .beforeUpdate),
!
718
                                          let item = item(for: initialIndexPath, kind: .cell, at: .beforeUpdate),
!
719
                                          item.calculatedOnce == true,
!
720
                                          let itemFrame = self.itemFrame(for: initialIndexPath, kind: .cell, at: .beforeUpdate, isFinal: false),
!
721
                                          itemFrame.intersects(layoutRepresentation.visibleBounds.offsetBy(dx: 0, dy: -totalProposedCompensatingOffset)) else {
!
722
                                        return false
!
723
                                    }
!
724
                                    return true
!
725
                                }
!
726
                                var itemWillBeVisible: Bool {
!
727
                                    let offsetVisibleBounds = layoutRepresentation.visibleBounds.offsetBy(dx: 0, dy: proposedCompensatingOffset + batchUpdateCompensatingOffset)
!
728
                                    if insertedIndexes.contains(itemPath.indexPath),
!
729
                                       let itemFrame = self.itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true),
!
730
                                       itemFrame.intersects(offsetVisibleBounds) {
!
731
                                        return true
!
732
                                    }
!
733
                                    if let itemIdentifier = itemIdentifier(for: itemPath, kind: .cell, at: .afterUpdate),
!
734
                                       let initialIndexPath = self.itemPath(by: itemIdentifier, kind: .cell, at: .beforeUpdate)?.indexPath,
!
735
                                       movedIndexes.contains(initialIndexPath) || reloadedIndexes.contains(initialIndexPath),
!
736
                                       let itemFrame = self.itemFrame(for: itemPath, kind: .cell, at: state, isFinal: true),
!
737
                                       itemFrame.intersects(offsetVisibleBounds) {
!
738
                                        return true
!
739
                                    }
!
740
                                    return false
40x
741
                                }
40x
742
                                if itemWillBeVisible || itemWasVisibleBefore {
40x
743
                                    allRects.append((frame: itemFrame, indexPath: itemPath, kind: .cell))
!
744
                                }
40x
745
                            }
40x
746
                        }
8x
747
                        guard traverseState != .done else {
8x
748
                            break
8x
749
                        }
8x
750
                    }
4x
751
                }
8x
752
8x
753
                if let footerFrame = itemFrame(for: sectionPath, kind: .footer, at: state, isFinal: true),
4x
754
                   check(rect: footerFrame) {
52x
755
                    allRects.append((frame: footerFrame, indexPath: sectionPath, kind: .footer))
52x
756
                }
52x
757
            }
4x
758
!
759
            return allRects.compactMap { frame, path, kind -> ChatLayoutAttributes? in
!
760
                itemAttributes(for: path, kind: kind, predefinedFrame: frame, at: state)
!
761
            }
!
762
        } else {
!
763
            // Debug purposes only.
!
764
            var attributes = [ChatLayoutAttributes]()
!
765
            attributes.reserveCapacity(layout.sections.count * 1000)
!
766
            layout.sections.enumerated().forEach { sectionIndex, section in
!
767
                let sectionPath = ItemPath(item: 0, section: sectionIndex)
!
768
                if let headerAttributes = itemAttributes(for: sectionPath, kind: .header, at: state) {
!
769
                    attributes.append(headerAttributes)
!
770
                }
!
771
                if let footerAttributes = itemAttributes(for: sectionPath, kind: .footer, at: state) {
!
772
                    attributes.append(footerAttributes)
!
773
                }
!
774
                section.items.enumerated().forEach { itemIndex, _ in
!
775
                    let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
!
776
                    if let itemAttributes = itemAttributes(for: itemPath, kind: .cell, at: state) {
!
777
                        attributes.append(itemAttributes)
!
778
                    }
!
779
                }
!
780
            }
781
782
            return attributes
783
        }
!
784
    }
785
786
    private func compensateOffsetIfNeeded(for itemPath: ItemPath, kind: ItemKind, action: CompensatingAction) {
787
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates else {
788
            return
789
        }
790
        let minY = (layoutRepresentation.visibleBounds.lowerPoint.y + batchUpdateCompensatingOffset + proposedCompensatingOffset).rounded()
2x
791
        switch action {
792
        case .insert:
793
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate),
794
                  let itemFrame = itemFrame(for: itemPath, kind: kind, at: .afterUpdate) else {
795
                return
796
            }
20300x
797
            if itemFrame.minY.rounded() - layoutRepresentation.settings.interItemSpacing <= minY {
10000x
798
                proposedCompensatingOffset += itemFrame.height + layoutRepresentation.settings.interItemSpacing
10300x
799
            }
10300x
800
        case let .frameUpdate(previousFrame, newFrame):
104x
801
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate, withFullCompensation: true) else {
802
                return
803
            }
804
            if newFrame.minY.rounded() <= minY {
805
                batchUpdateCompensatingOffset += newFrame.height - previousFrame.height
4x
806
            }
807
        case .delete:
808
            guard isLayoutBiggerThanVisibleBounds(at: .beforeUpdate),
40x
809
                  let deletedFrame = itemFrame(for: itemPath, kind: kind, at: .beforeUpdate) else {
40x
810
                return
40x
811
            }
812
            if deletedFrame.minY.rounded() <= minY {
813
                // Changing content offset for deleted items using `invalidateLayout(with:) causes UI glitches.
814
                // So we are using targetContentOffset(forProposedContentOffset:) which is going to be called after.
815
                proposedCompensatingOffset -= (deletedFrame.height + layoutRepresentation.settings.interItemSpacing)
816
            }
9x
817
        }
9x
818
!
819
    }
9x
820
9x
821
    private func compensateOffsetOfSectionIfNeeded(for sectionIndex: Int, action: CompensatingAction) {
9x
822
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates else {
9x
823
            return
2x
824
        }
2x
825
        let minY = (layoutRepresentation.visibleBounds.lowerPoint.y + batchUpdateCompensatingOffset + proposedCompensatingOffset).rounded()
!
826
        switch action {
2x
827
        case .insert:
2x
828
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate),
2x
829
                  sectionIndex < layout(at: .afterUpdate).sections.count else {
2x
830
                return
!
831
            }
9x
832
            let section = layout(at: .afterUpdate).sections[sectionIndex]
9x
833
5x
834
            if section.offsetY.rounded() - layoutRepresentation.settings.interSectionSpacing <= minY {
5x
835
                proposedCompensatingOffset += section.height + layoutRepresentation.settings.interSectionSpacing
!
836
            }
5x
837
        case let .frameUpdate(previousFrame, newFrame):
5x
838
            guard sectionIndex < layout(at: .afterUpdate).sections.count,
2x
839
                  isLayoutBiggerThanVisibleBounds(at: .afterUpdate, withFullCompensation: true) else {
9x
840
                return
9x
841
            }
2x
842
            if newFrame.minY.rounded() <= minY {
2x
843
                batchUpdateCompensatingOffset += newFrame.height - previousFrame.height
1x
844
            }
1x
845
        case .delete:
1x
846
            guard isLayoutBiggerThanVisibleBounds(at: .afterUpdate),
1x
847
                  sectionIndex < layout(at: .afterUpdate).sections.count else {
!
848
                return
!
849
            }
!
850
            let section = layout(at: .beforeUpdate).sections[sectionIndex]
9x
851
            if section.locationHeight.rounded() <= minY {
9x
852
                // Changing content offset for deleted items using `invalidateLayout(with:) causes UI glitches.
9x
853
                // So we are using targetContentOffset(forProposedContentOffset:) which is going to be called after.
9x
854
                proposedCompensatingOffset -= (section.height + layoutRepresentation.settings.interSectionSpacing)
855
            }
856
        }
857
858
    }
376x
859
376x
860
    private func offsetByCompensation(frame: CGRect,
376x
861
                                      at itemPath: ItemPath,
376x
862
                                      for state: ModelState,
376x
863
                                      backward: Bool = false) -> CGRect {
376x
864
        guard layoutRepresentation.keepContentOffsetAtBottomOnBatchUpdates,
!
865
              state == .afterUpdate,
376x
866
              isLayoutBiggerThanVisibleBounds(at: .afterUpdate) else {
867
            return frame
868
        }
869
        return frame.offsetBy(dx: 0, dy: proposedCompensatingOffset * (backward ? -1 : 1))
870
    }
871
1000000x
872
}
1000000x
873
1000000x
874
extension RandomAccessCollection where Index == Int {
1000000x
875
16000000x
876
    func binarySearch(predicate: (Element) -> ComparisonResult) -> Index? {
16000000x
877
        var lowerBound = startIndex
16000000x
878
        var upperBound = endIndex
1000000x
879
15000000x
880
        while lowerBound < upperBound {
6000000x
881
            let midIndex = lowerBound &+ (upperBound &- lowerBound) / 2
15000000x
882
            if predicate(self[midIndex]) == .orderedSame {
9000000x
883
                return midIndex
15000000x
884
            } else if predicate(self[midIndex]) == .orderedAscending {
15000000x
885
                lowerBound = midIndex &+ 1
5x
886
            } else {
1000000x
887
                upperBound = midIndex
888
            }
1000000x
889
        }
1000000x
890
        return nil
1000000x
891
    }
1000000x
892
1000000x
893
    func binarySearchRange(predicate: (Element) -> ComparisonResult) -> [Element] {
18000000x
894
        func leftMostSearch(lowerBound: Index, upperBound: Index) -> Index? {
17000000x
895
            var lowerBound = lowerBound
17000000x
896
            var upperBound = upperBound
7000000x
897
17000000x
898
            while lowerBound < upperBound {
10000000x
899
                let midIndex = (lowerBound &+ upperBound) / 2
17000000x
900
                if predicate(self[midIndex]) == .orderedAscending {
17000000x
901
                    lowerBound = midIndex &+ 1
1000000x
902
                } else {
1000000x
903
                    upperBound = midIndex
1000000x
904
                }
1x
905
            }
1x
906
            if predicate(self[lowerBound]) == .orderedSame {
!
907
                return lowerBound
1000000x
908
            } else {
1000000x
909
                return nil
1000000x
910
            }
1000000x
911
        }
1000000x
912
18000000x
913
        func rightMostSearch(lowerBound: Index, upperBound: Index) -> Index? {
17000000x
914
            var lowerBound = lowerBound
17000000x
915
            var upperBound = upperBound
12000000x
916
17000000x
917
            while lowerBound < upperBound {
5000000x
918
                let midIndex = (lowerBound &+ upperBound &+ 1) / 2
17000000x
919
                if predicate(self[midIndex]) == .orderedDescending {
17000000x
920
                    upperBound = midIndex &- 1
1000000x
921
                } else {
1000000x
922
                    lowerBound = midIndex
1000000x
923
                }
!
924
            }
!
925
            if predicate(self[lowerBound]) == .orderedSame {
!
926
                return lowerBound
1000000x
927
            } else {
1000000x
928
                return nil
1000000x
929
            }
2x
930
        }
1000000x
931
        guard !isEmpty,
1000000x
932
              let lowerBound = leftMostSearch(lowerBound: startIndex, upperBound: endIndex - 1),
1000000x
933
              let upperBound = rightMostSearch(lowerBound: startIndex, upperBound: endIndex - 1) else {
1000000x
934
            return []
935
        }
936
937
        return Array(self[lowerBound...upperBound])
938
    }
939
940
}