Slather logo

Coverage for "ChatLayout.swift" : 0.00%

(0 of 765 relevant lines covered)

ChatLayout/Classes/Core/ChatLayout.swift

1
//
2
// ChatLayout
3
// ChatLayout.swift
4
// https://github.com/ekazaev/ChatLayout
5
//
6
// Created by Eugene Kazaev in 2020-2022.
7
// Distributed under the MIT license.
8
//
9
10
import Foundation
11
import UIKit
12
13
/// A collection view layout that can display items in a grid similar to `UITableView` but aligning them
14
/// to the leading or trailing edge of the `UICollectionView`. Helps to maintain chat like behavior by keeping
15
/// content offset from the bottom constant. Can deal with autosizing cells and supplementary views.
16
/// ### Custom Properties:
17
/// `ChatLayout.delegate`
18
///
19
/// `ChatLayout.settings`
20
///
21
/// `ChatLayout.keepContentOffsetAtBottomOnBatchUpdates`
22
///
23
/// `ChatLayout.visibleBounds`
24
///
25
/// `ChatLayout.layoutFrame`
26
///
27
/// ### Custom Methods:
28
/// `ChatLayout.getContentOffsetSnapshot(...)`
29
///
30
/// `ChatLayout.restoreContentOffset(...)`
31
public final class ChatLayout: UICollectionViewLayout {
32
33
    // MARK: Custom Properties
34
35
    /// `ChatLayout` delegate.
36
    public weak var delegate: ChatLayoutDelegate?
37
38
    /// Additional settings for `ChatLayout`.
39
    public var settings = ChatLayoutSettings() {
!
40
        didSet {
!
41
            guard collectionView != nil else {
!
42
                return
!
43
            }
!
44
            invalidateLayout()
!
45
        }
!
46
    }
47
48
    /// Default `UIScrollView` behaviour is to keep content offset constant from the top edge. If this flag is set to `true`
49
    /// `ChatLayout` should try to compensate batch update changes to keep the current content at the bottom of the visible
50
    /// part of `UICollectionView`.
51
    ///
52
    /// **NB:**
53
    /// Keep in mind that if during the batch content inset changes also (e.g. keyboard frame changes), `ChatLayout` will usually get that information after
54
    /// the animation starts and wont be able to compensate that change too. It should be done manually.
55
    public var keepContentOffsetAtBottomOnBatchUpdates: Bool = false
56
57
    /// Represent the currently visible rectangle.
58
    public var visibleBounds: CGRect {
!
59
        guard let collectionView = collectionView else {
!
60
            return .zero
!
61
        }
!
62
        return CGRect(x: adjustedContentInset.left,
!
63
                      y: collectionView.contentOffset.y + adjustedContentInset.top,
!
64
                      width: collectionView.bounds.width - adjustedContentInset.left - adjustedContentInset.right,
!
65
                      height: collectionView.bounds.height - adjustedContentInset.top - adjustedContentInset.bottom)
!
66
    }
!
67
68
    /// Represent the rectangle where all the items are aligned.
69
    public var layoutFrame: CGRect {
!
70
        guard let collectionView = collectionView else {
!
71
            return .zero
!
72
        }
!
73
        let additionalInsets = settings.additionalInsets
!
74
        return CGRect(x: adjustedContentInset.left + additionalInsets.left,
!
75
                      y: adjustedContentInset.top + additionalInsets.top,
!
76
                      width: collectionView.bounds.width - additionalInsets.left - additionalInsets.right - adjustedContentInset.left - adjustedContentInset.right,
!
77
                      height: controller.contentHeight(at: state) - additionalInsets.top - additionalInsets.bottom - adjustedContentInset.top - adjustedContentInset.bottom)
!
78
    }
!
79
80
    // MARK: Inherited Properties
81
82
    /// The direction of the language you used when designing `ChatLayout` layout.
83
    public override var developmentLayoutDirection: UIUserInterfaceLayoutDirection {
!
84
        return .leftToRight
!
85
    }
!
86
87
    /// A Boolean value that indicates whether the horizontal coordinate system is automatically flipped at appropriate times.
88
    public override var flipsHorizontallyInOppositeLayoutDirection: Bool {
!
89
        return _flipsHorizontallyInOppositeLayoutDirection
!
90
    }
!
91
92
    /// Custom layoutAttributesClass is `ChatLayoutAttributes`.
93
    public override class var layoutAttributesClass: AnyClass {
!
94
        return ChatLayoutAttributes.self
!
95
    }
!
96
97
    /// Custom invalidationContextClass is `ChatLayoutInvalidationContext`.
98
    public override class var invalidationContextClass: AnyClass {
!
99
        return ChatLayoutInvalidationContext.self
!
100
    }
!
101
102
    /// The width and height of the collection view’s contents.
103
    public override var collectionViewContentSize: CGSize {
!
104
        let contentSize: CGSize
!
105
        if state == .beforeUpdate {
!
106
            contentSize = controller.contentSize(for: .beforeUpdate)
!
107
        } else {
!
108
            var size = controller.contentSize(for: .beforeUpdate)
!
109
            size.height += controller.totalProposedCompensatingOffset
!
110
            contentSize = size
!
111
        }
!
112
        return contentSize
!
113
    }
!
114
115
    /// There is an issue in IOS 15.1 that proposed content offset is being ignored by the UICollectionView when user is scrolling.
116
    /// This flag enables a hack to compensate this offset later. You can disable it if necessary.
117
    /// Bug reported: https://feedbackassistant.apple.com/feedback/9727104
118
    ///
119
    /// PS: This issue was fixed in 15.2
120
    public var enableIOS15_1Fix: Bool = true
121
122
    // MARK: Internal Properties
!
123
!
124
    var adjustedContentInset: UIEdgeInsets {
!
125
        guard let collectionView = collectionView else {
!
126
            return .zero
!
127
        }
!
128
        return collectionView.adjustedContentInset
129
    }
!
130
!
131
    var viewSize: CGSize {
!
132
        guard let collectionView = collectionView else {
!
133
            return .zero
!
134
        }
!
135
        return collectionView.frame.size
136
    }
137
138
    // MARK: Private Properties
139
140
    private struct PrepareActions: OptionSet {
141
142
        let rawValue: UInt
143
144
        static let recreateSectionModels = PrepareActions(rawValue: 1 << 0)
145
        static let updateLayoutMetrics = PrepareActions(rawValue: 1 << 1)
146
        static let cachePreviousWidth = PrepareActions(rawValue: 1 << 2)
147
        static let cachePreviousContentInsets = PrepareActions(rawValue: 1 << 3)
148
        static let switchStates = PrepareActions(rawValue: 1 << 4)
149
150
    }
151
152
    private struct InvalidationActions: OptionSet {
153
154
        let rawValue: UInt
155
156
        static let shouldInvalidateOnBoundsChange = InvalidationActions(rawValue: 1 << 0)
157
158
    }
159
160
    private lazy var controller = StateController(layoutRepresentation: self)
!
161
162
    private var state: ModelState = .beforeUpdate
!
163
164
    private var prepareActions: PrepareActions = []
!
165
166
    private var invalidationActions: InvalidationActions = []
167
168
    private var cachedCollectionViewSize: CGSize?
169
170
    private var cachedCollectionViewInset: UIEdgeInsets?
171
172
    // These properties are used to keep the layout attributes copies used for insert/delete
173
    // animations up-to-date as items are self-sized. If we don't keep these copies up-to-date, then
!
174
    // animations will start from the estimated height.
175
    private var attributesForPendingAnimations = [ItemKind: [ItemPath: ChatLayoutAttributes]]()
!
176
177
    private var invalidatedAttributes = [ItemKind: Set<ItemPath>]()
178
179
    private var dontReturnAttributes: Bool = true
180
181
    private var currentPositionSnapshot: ChatLayoutPositionSnapshot?
182
183
    private let _flipsHorizontallyInOppositeLayoutDirection: Bool
184
185
    // MARK: IOS 15.1 fix flags
!
186
!
187
    private var needsIOS15_1IssueFix: Bool {
!
188
        return enableIOS15_1Fix && isIOS15_1orHigher && !isIOS15_2orHigher && isUserInitiatedScrolling && !controller.isAnimatedBoundsChange
189
    }
190
191
    // MARK: Constructors
192
193
    /// Default constructor.
194
    /// - Parameters:
195
    ///   - flipsHorizontallyInOppositeLayoutDirection: Indicates whether the horizontal coordinate
196
    ///     system is automatically flipped at appropriate times. In practice, this is used to support
!
197
    ///     right-to-left layout.
!
198
    public init(flipsHorizontallyInOppositeLayoutDirection: Bool = true) {
!
199
        self._flipsHorizontallyInOppositeLayoutDirection = flipsHorizontallyInOppositeLayoutDirection
!
200
        super.init()
!
201
        resetAttributesForPendingAnimations()
!
202
        resetInvalidatedAttributes()
203
    }
204
!
205
    /// Returns an object initialized from data in a given unarchiver.
!
206
    public required init?(coder aDecoder: NSCoder) {
!
207
        self._flipsHorizontallyInOppositeLayoutDirection = true
!
208
        super.init(coder: aDecoder)
!
209
        resetAttributesForPendingAnimations()
!
210
        resetInvalidatedAttributes()
211
    }
212
213
    // MARK: Custom Methods
214
215
    /// Get current offset of the item closest to the provided edge.
216
    /// - Parameter edge: The edge of the `UICollectionView`
!
217
    /// - Returns: `ChatLayoutPositionSnapshot`
!
218
    public func getContentOffsetSnapshot(from edge: ChatLayoutPositionSnapshot.Edge) -> ChatLayoutPositionSnapshot? {
!
219
        guard let collectionView = collectionView else {
!
220
            return nil
!
221
        }
!
222
        let insets = UIEdgeInsets(top: -collectionView.frame.height,
!
223
                                  left: 0,
!
224
                                  bottom: -collectionView.frame.height,
!
225
                                  right: 0)
!
226
        let layoutAttributes = controller.layoutAttributesForElements(in: visibleBounds.inset(by: insets),
!
227
                                                                      state: state,
!
228
                                                                      ignoreCache: true)
!
229
            .sorted(by: { $0.frame.maxY < $1.frame.maxY })
!
230
!
231
        switch edge {
!
232
        case .top:
!
233
            guard let firstVisibleItemAttributes = layoutAttributes.first(where: { $0.frame.minY >= visibleBounds.higherPoint.y }) else {
!
234
                return nil
!
235
            }
!
236
            let visibleBoundsTopOffset = firstVisibleItemAttributes.frame.minY - visibleBounds.higherPoint.y - settings.additionalInsets.top
!
237
            return ChatLayoutPositionSnapshot(indexPath: firstVisibleItemAttributes.indexPath, kind: firstVisibleItemAttributes.kind, edge: .top, offset: visibleBoundsTopOffset)
!
238
        case .bottom:
!
239
            guard let lastVisibleItemAttributes = layoutAttributes.last(where: { $0.frame.minY <= visibleBounds.lowerPoint.y }) else {
!
240
                return nil
!
241
            }
!
242
            let visibleBoundsBottomOffset = visibleBounds.lowerPoint.y - lastVisibleItemAttributes.frame.maxY - settings.additionalInsets.bottom
!
243
            return ChatLayoutPositionSnapshot(indexPath: lastVisibleItemAttributes.indexPath, kind: lastVisibleItemAttributes.kind, edge: .bottom, offset: visibleBoundsBottomOffset)
!
244
        }
245
    }
246
247
    /// Invalidates layout of the `UICollectionView` and trying to keep the offset of the item provided in `ChatLayoutPositionSnapshot`
!
248
    /// - Parameter snapshot: `ChatLayoutPositionSnapshot`
!
249
    public func restoreContentOffset(with snapshot: ChatLayoutPositionSnapshot) {
!
250
        guard let collectionView = collectionView else {
!
251
            return
!
252
        }
!
253
        collectionView.setNeedsLayout()
!
254
        collectionView.layoutIfNeeded()
!
255
        currentPositionSnapshot = snapshot
!
256
        let context = ChatLayoutInvalidationContext()
!
257
        context.invalidateLayoutMetrics = false
!
258
        invalidateLayout(with: context)
!
259
        collectionView.setNeedsLayout()
!
260
        collectionView.layoutIfNeeded()
!
261
        currentPositionSnapshot = nil
262
    }
263
264
    // MARK: Providing Layout Attributes
265
!
266
    /// Tells the layout object to update the current layout.
!
267
    public override func prepare() {
!
268
        super.prepare()
!
269
!
270
        guard let collectionView = collectionView,
!
271
              !prepareActions.isEmpty else {
!
272
            return
!
273
        }
!
274
!
275
        if collectionView.isPrefetchingEnabled {
!
276
            preconditionFailure("UICollectionView with prefetching enabled is not supported due to https://openradar.appspot.com/40926834 bug.")
!
277
        }
!
278
!
279
        if prepareActions.contains(.switchStates) {
!
280
            controller.commitUpdates()
!
281
            state = .beforeUpdate
!
282
            resetAttributesForPendingAnimations()
!
283
            resetInvalidatedAttributes()
!
284
        }
!
285
!
286
        if prepareActions.contains(.recreateSectionModels) {
!
287
            var sections: [SectionModel] = []
!
288
            for sectionIndex in 0..<collectionView.numberOfSections {
!
289
                // Header
!
290
                let header: ItemModel?
!
291
                if delegate?.shouldPresentHeader(self, at: sectionIndex) == true {
!
292
                    let headerPath = ItemPath(item: 0, section: sectionIndex)
!
293
                    header = ItemModel(with: configuration(for: .header, at: headerPath))
!
294
                } else {
!
295
                    header = nil
!
296
                }
!
297
!
298
                // Items
!
299
                var items: [ItemModel] = []
!
300
                for itemIndex in 0..<collectionView.numberOfItems(inSection: sectionIndex) {
!
301
                    let itemPath = ItemPath(item: itemIndex, section: sectionIndex)
!
302
                    items.append(ItemModel(with: configuration(for: .cell, at: itemPath)))
!
303
                }
!
304
!
305
                // Footer
!
306
                let footer: ItemModel?
!
307
                if delegate?.shouldPresentFooter(self, at: sectionIndex) == true {
!
308
                    let footerPath = ItemPath(item: 0, section: sectionIndex)
!
309
                    footer = ItemModel(with: configuration(for: .footer, at: footerPath))
!
310
                } else {
!
311
                    footer = nil
!
312
                }
!
313
                var section = SectionModel(header: header, footer: footer, items: items, collectionLayout: self)
!
314
                section.assembleLayout()
!
315
                sections.append(section)
!
316
            }
!
317
            controller.set(sections, at: .beforeUpdate)
!
318
        }
!
319
!
320
        if prepareActions.contains(.updateLayoutMetrics),
!
321
           !prepareActions.contains(.recreateSectionModels) {
!
322
!
323
            var sections: [SectionModel] = []
!
324
            sections.reserveCapacity(controller.numberOfSections(at: state))
!
325
            for sectionIndex in 0..<controller.numberOfSections(at: state) {
!
326
                var section = controller.section(at: sectionIndex, at: state)
!
327
!
328
                // Header
!
329
                if delegate?.shouldPresentHeader(self, at: sectionIndex) == true {
!
330
                    var header = section.header
!
331
                    header?.resetSize()
!
332
                    section.set(header: header)
!
333
                } else {
!
334
                    section.set(header: nil)
!
335
                }
!
336
!
337
                // Items
!
338
                var items: [ItemModel] = []
!
339
                items.reserveCapacity(section.items.count)
!
340
                for rowIndex in 0..<section.items.count {
!
341
                    var item = section.items[rowIndex]
!
342
                    item.resetSize()
!
343
                    items.append(item)
!
344
                }
!
345
                section.set(items: items)
!
346
!
347
                // Footer
!
348
                if delegate?.shouldPresentFooter(self, at: sectionIndex) == true {
!
349
                    var footer = section.footer
!
350
                    footer?.resetSize()
!
351
                    section.set(footer: footer)
!
352
                } else {
!
353
                    section.set(footer: nil)
!
354
                }
!
355
!
356
                section.assembleLayout()
!
357
                sections.append(section)
!
358
            }
!
359
            controller.set(sections, at: state)
!
360
        }
!
361
!
362
        if prepareActions.contains(.cachePreviousContentInsets) {
!
363
            cachedCollectionViewInset = adjustedContentInset
!
364
        }
!
365
!
366
        if prepareActions.contains(.cachePreviousWidth) {
!
367
            cachedCollectionViewSize = collectionView.bounds.size
!
368
        }
!
369
!
370
        prepareActions = []
371
    }
372
!
373
    /// Retrieves the layout attributes for all of the cells and views in the specified rectangle.
!
374
    public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
!
375
        // This early return prevents an issue that causes overlapping / misplaced elements after an
!
376
        // off-screen batch update occurs. The root cause of this issue is that `UICollectionView`
!
377
        // expects `layoutAttributesForElementsInRect:` to return post-batch-update layout attributes
!
378
        // immediately after an update is sent to the collection view via the insert/delete/reload/move
!
379
        // functions. Unfortunately, this is impossible - when batch updates occur, `invalidateLayout:`
!
380
        // is invoked immediately with a context that has `invalidateDataSourceCounts` set to `true`.
!
381
        // At this time, `ChatLayout` has no way of knowing the details of this data source count
!
382
        // change (where the insert/delete/move took place). `ChatLayout` only gets this additional
!
383
        // information once `prepareForCollectionViewUpdates:` is invoked. At that time, we're able to
!
384
        // update our layout's source of truth, the `StateController`, which allows us to resolve the
!
385
        // post-batch-update layout and return post-batch-update layout attributes from this function.
!
386
        // Between the time that `invalidateLayout:` is invoked with `invalidateDataSourceCounts` set to
!
387
        // `true`, and when `prepareForCollectionViewUpdates:` is invoked with details of the updates,
!
388
        // `layoutAttributesForElementsInRect:` is invoked with the expectation that we already have a
!
389
        // fully resolved layout. If we return incorrect layout attributes at that time, then we'll have
!
390
        // overlapping elements / visual defects. To prevent this, we can return `nil` in this
!
391
        // situation, which works around the bug.
!
392
        // `UICollectionViewCompositionalLayout`, in classic UIKit fashion, avoids this bug / feature by
!
393
        // implementing the private function
!
394
        // `_prepareForCollectionViewUpdates:withDataSourceTranslator:`, which provides the layout with
!
395
        // details about the updates to the collection view before `layoutAttributesForElementsInRect:`
!
396
        // is invoked, enabling them to resolve their layout in time.
!
397
        guard !dontReturnAttributes else {
!
398
            return nil
!
399
        }
!
400
!
401
        let visibleAttributes = controller.layoutAttributesForElements(in: rect, state: state)
!
402
        return visibleAttributes
403
    }
404
!
405
    /// Retrieves layout information for an item at the specified index path with a corresponding cell.
!
406
    public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
407
        guard !dontReturnAttributes else {
!
408
            return nil
!
409
        }
!
410
        let attributes = controller.itemAttributes(for: indexPath.itemPath, kind: .cell, at: state)
!
411
!
412
        return attributes
413
    }
414
!
415
    /// Retrieves the layout attributes for the specified supplementary view.
!
416
    public override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
417
        guard !dontReturnAttributes else {
!
418
            return nil
!
419
        }
!
420
!
421
        let kind = ItemKind(elementKind)
!
422
        let attributes = controller.itemAttributes(for: indexPath.itemPath, kind: kind, at: state)
!
423
!
424
        return attributes
425
    }
426
427
    // MARK: Coordinating Animated Changes
428
!
429
    /// Prepares the layout object for animated changes to the view’s bounds or the insertion or deletion of items.
!
430
    public override func prepare(forAnimatedBoundsChange oldBounds: CGRect) {
!
431
        controller.isAnimatedBoundsChange = true
!
432
        controller.process(changeItems: [])
!
433
        state = .afterUpdate
!
434
        prepareActions.remove(.switchStates)
!
435
        guard let collectionView = collectionView,
!
436
              oldBounds.width != collectionView.bounds.width,
!
437
              keepContentOffsetAtBottomOnBatchUpdates,
!
438
              controller.isLayoutBiggerThanVisibleBounds(at: state) else {
!
439
            return
!
440
        }
!
441
        let newBounds = collectionView.bounds
!
442
        let heightDifference = oldBounds.height - newBounds.height
!
443
        controller.proposedCompensatingOffset += heightDifference + (oldBounds.origin.y - newBounds.origin.y)
444
    }
445
!
446
    /// Cleans up after any animated changes to the view’s bounds or after the insertion or deletion of items.
!
447
    public override func finalizeAnimatedBoundsChange() {
!
448
        if controller.isAnimatedBoundsChange {
!
449
            controller.isAnimatedBoundsChange = false
!
450
            controller.proposedCompensatingOffset = 0
!
451
            controller.batchUpdateCompensatingOffset = 0
!
452
            controller.commitUpdates()
!
453
            state = .beforeUpdate
!
454
            resetAttributesForPendingAnimations()
!
455
            resetInvalidatedAttributes()
!
456
        }
457
    }
458
459
    // MARK: Context Invalidation
460
!
461
    /// Asks the layout object if changes to a self-sizing cell require a layout update.
!
462
    public override func shouldInvalidateLayout(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> Bool {
!
463
        let preferredAttributesItemPath = preferredAttributes.indexPath.itemPath
!
464
        guard let preferredMessageAttributes = preferredAttributes as? ChatLayoutAttributes,
!
465
              let item = controller.item(for: preferredAttributesItemPath, kind: preferredMessageAttributes.kind, at: state) else {
!
466
            return true
!
467
        }
!
468
!
469
        let shouldInvalidateLayout = item.calculatedSize == nil || item.alignment != preferredMessageAttributes.alignment
!
470
!
471
        return shouldInvalidateLayout
472
    }
473
!
474
    /// Retrieves a context object that identifies the portions of the layout that should change in response to dynamic cell changes.
!
475
    public override func invalidationContext(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext {
!
476
        guard let preferredMessageAttributes = preferredAttributes as? ChatLayoutAttributes else {
!
477
            return super.invalidationContext(forPreferredLayoutAttributes: preferredAttributes, withOriginalAttributes: originalAttributes)
!
478
        }
!
479
!
480
        let preferredAttributesItemPath = preferredMessageAttributes.indexPath.itemPath
!
481
!
482
        if state == .afterUpdate {
!
483
            invalidatedAttributes[preferredMessageAttributes.kind]?.insert(preferredAttributesItemPath)
!
484
        }
!
485
!
486
        let layoutAttributesForPendingAnimation = attributesForPendingAnimations[preferredMessageAttributes.kind]?[preferredAttributesItemPath]
!
487
!
488
        let newItemSize = itemSize(with: preferredMessageAttributes)
!
489
!
490
        controller.update(preferredSize: newItemSize,
!
491
                          alignment: preferredMessageAttributes.alignment,
!
492
                          for: preferredAttributesItemPath,
!
493
                          kind: preferredMessageAttributes.kind,
!
494
                          at: state)
!
495
!
496
        let context = super.invalidationContext(forPreferredLayoutAttributes: preferredMessageAttributes, withOriginalAttributes: originalAttributes) as! ChatLayoutInvalidationContext
!
497
!
498
        let heightDifference = newItemSize.height - originalAttributes.size.height
!
499
        let isAboveBottomEdge = originalAttributes.frame.minY.rounded() <= visibleBounds.maxY.rounded()
!
500
!
501
        if heightDifference != 0,
!
502
           (keepContentOffsetAtBottomOnBatchUpdates && controller.contentHeight(at: state).rounded() + heightDifference > visibleBounds.height.rounded()) || isUserInitiatedScrolling,
!
503
           isAboveBottomEdge {
!
504
            context.contentOffsetAdjustment.y += heightDifference
!
505
            invalidationActions.formUnion([.shouldInvalidateOnBoundsChange])
!
506
        }
!
507
!
508
        if let attributes = controller.itemAttributes(for: preferredAttributesItemPath, kind: preferredMessageAttributes.kind, at: state)?.typedCopy() {
!
509
            controller.totalProposedCompensatingOffset += heightDifference
!
510
            layoutAttributesForPendingAnimation?.frame = attributes.frame
!
511
            if keepContentOffsetAtBottomOnBatchUpdates {
!
512
                controller.offsetByTotalCompensation(attributes: layoutAttributesForPendingAnimation, for: state, backward: true)
!
513
            }
!
514
            if state == .afterUpdate,
!
515
               controller.insertedIndexes.contains(preferredMessageAttributes.indexPath) ||
!
516
               controller.insertedSectionsIndexes.contains(preferredMessageAttributes.indexPath.section) {
!
517
                layoutAttributesForPendingAnimation.map { attributes in
!
518
                    guard let delegate = delegate else {
!
519
                        attributes.alpha = 0
!
520
                        return
!
521
                    }
!
522
                    delegate.initialLayoutAttributesForInsertedItem(self, of: .cell, at: attributes.indexPath, modifying: attributes, on: .invalidation)
!
523
                }
!
524
            }
!
525
        } else {
!
526
            layoutAttributesForPendingAnimation?.frame.size = newItemSize
!
527
        }
!
528
!
529
        if isIOS13orHigher {
!
530
            switch preferredMessageAttributes.kind {
!
531
            case .cell:
!
532
                context.invalidateItems(at: [preferredMessageAttributes.indexPath])
!
533
            case .header, .footer:
!
534
                context.invalidateSupplementaryElements(ofKind: preferredMessageAttributes.kind.supplementaryElementStringType, at: [preferredMessageAttributes.indexPath])
!
535
            }
!
536
        }
!
537
!
538
        context.invalidateLayoutMetrics = false
!
539
!
540
        return context
!
541
    }
542
543
    /// Asks the layout object if the new bounds require a layout update.
!
544
    public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
!
545
        let shouldInvalidateLayout = cachedCollectionViewSize != .some(newBounds.size) ||
!
546
            cachedCollectionViewInset != .some(adjustedContentInset) ||
!
547
            invalidationActions.contains(.shouldInvalidateOnBoundsChange)
!
548
!
549
        invalidationActions.remove(.shouldInvalidateOnBoundsChange)
!
550
        return shouldInvalidateLayout
!
551
    }
552
553
    /// Retrieves a context object that defines the portions of the layout that should change when a bounds change occurs.
!
554
    public override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
!
555
        let invalidationContext = super.invalidationContext(forBoundsChange: newBounds) as! ChatLayoutInvalidationContext
!
556
        invalidationContext.invalidateLayoutMetrics = false
!
557
        return invalidationContext
!
558
    }
559
560
    /// Invalidates the current layout using the information in the provided context object.
!
561
    public override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) {
!
562
        guard let collectionView = collectionView else {
!
563
            super.invalidateLayout(with: context)
!
564
            return
!
565
        }
!
566
!
567
        guard let context = context as? ChatLayoutInvalidationContext else {
!
568
            assertionFailure("`context` must be an instance of `ChatLayoutInvalidationContext`")
!
569
            return
!
570
        }
!
571
!
572
        controller.resetCachedAttributes()
!
573
!
574
        dontReturnAttributes = context.invalidateDataSourceCounts && !context.invalidateEverything
!
575
!
576
        if context.invalidateEverything {
!
577
            prepareActions.formUnion([.recreateSectionModels])
!
578
        }
!
579
!
580
        // Checking `cachedCollectionViewWidth != collectionView.bounds.size.width` is necessary
!
581
        // because the collection view's width can change without a `contentSizeAdjustment` occurring.
!
582
        if context.contentSizeAdjustment.width != 0 || cachedCollectionViewSize != collectionView.bounds.size {
!
583
            prepareActions.formUnion([.cachePreviousWidth])
!
584
        }
!
585
!
586
        if cachedCollectionViewInset != adjustedContentInset {
!
587
            prepareActions.formUnion([.cachePreviousContentInsets])
!
588
        }
!
589
!
590
        if context.invalidateLayoutMetrics, !context.invalidateDataSourceCounts {
!
591
            prepareActions.formUnion([.updateLayoutMetrics])
!
592
        }
!
593
!
594
        if let currentPositionSnapshot = currentPositionSnapshot {
!
595
            let contentHeight = controller.contentHeight(at: state)
!
596
            if let frame = controller.itemFrame(for: currentPositionSnapshot.indexPath.itemPath, kind: currentPositionSnapshot.kind, at: state, isFinal: true),
!
597
               contentHeight != 0,
!
598
               contentHeight > visibleBounds.size.height {
!
599
                switch currentPositionSnapshot.edge {
!
600
                case .top:
!
601
                    let desiredOffset = frame.minY - currentPositionSnapshot.offset - collectionView.adjustedContentInset.top - settings.additionalInsets.top
!
602
                    context.contentOffsetAdjustment.y = desiredOffset - collectionView.contentOffset.y
!
603
                case .bottom:
!
604
                    let maxAllowed = max(-collectionView.adjustedContentInset.top, contentHeight - collectionView.frame.height + collectionView.adjustedContentInset.bottom)
!
605
                    let desiredOffset = max(min(maxAllowed, frame.maxY + currentPositionSnapshot.offset - collectionView.bounds.height + collectionView.adjustedContentInset.bottom + settings.additionalInsets.bottom), -collectionView.adjustedContentInset.top)
!
606
                    context.contentOffsetAdjustment.y = desiredOffset - collectionView.contentOffset.y
!
607
                }
!
608
            }
!
609
        }
!
610
        super.invalidateLayout(with: context)
!
611
    }
612
613
    /// Invalidates the current layout and triggers a layout update.
!
614
    public override func invalidateLayout() {
!
615
        super.invalidateLayout()
!
616
    }
617
618
    /// Retrieves the content offset to use after an animated layout update or change.
!
619
    public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
!
620
        if controller.proposedCompensatingOffset != 0,
!
621
           let collectionView = collectionView {
!
622
            let minPossibleContentOffset = -collectionView.adjustedContentInset.top
!
623
            let newProposedContentOffset = CGPoint(x: proposedContentOffset.x, y: max(minPossibleContentOffset, min(proposedContentOffset.y + controller.proposedCompensatingOffset, maxPossibleContentOffset.y)))
!
624
            invalidationActions.formUnion([.shouldInvalidateOnBoundsChange])
!
625
            if needsIOS15_1IssueFix {
!
626
                controller.proposedCompensatingOffset = 0
!
627
                collectionView.contentOffset = newProposedContentOffset
!
628
                return newProposedContentOffset
!
629
            } else {
!
630
                controller.proposedCompensatingOffset = 0
!
631
                return newProposedContentOffset
!
632
            }
!
633
        }
!
634
        return super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
!
635
    }
636
637
    // MARK: Responding to Collection View Updates
638
639
    /// Notifies the layout object that the contents of the collection view are about to change.
!
640
    public override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
!
641
        let changeItems = updateItems.compactMap { ChangeItem(with: $0) }
!
642
        controller.process(changeItems: changeItems)
!
643
        state = .afterUpdate
!
644
        dontReturnAttributes = false
!
645
        super.prepare(forCollectionViewUpdates: updateItems)
!
646
    }
647
648
    /// Performs any additional animations or clean up needed during a collection view update.
!
649
    public override func finalizeCollectionViewUpdates() {
!
650
        controller.proposedCompensatingOffset = 0
!
651
!
652
        if keepContentOffsetAtBottomOnBatchUpdates,
!
653
           controller.isLayoutBiggerThanVisibleBounds(at: state),
!
654
           controller.batchUpdateCompensatingOffset != 0,
!
655
           let collectionView = collectionView {
!
656
            let compensatingOffset: CGFloat
!
657
            if controller.contentSize(for: .beforeUpdate).height > visibleBounds.size.height {
!
658
                compensatingOffset = controller.batchUpdateCompensatingOffset
!
659
            } else {
!
660
                compensatingOffset = maxPossibleContentOffset.y - collectionView.contentOffset.y
!
661
            }
!
662
            controller.batchUpdateCompensatingOffset = 0
!
663
            let context = ChatLayoutInvalidationContext()
!
664
            context.contentOffsetAdjustment.y = compensatingOffset
!
665
            invalidateLayout(with: context)
!
666
        } else {
!
667
            controller.batchUpdateCompensatingOffset = 0
!
668
            let context = ChatLayoutInvalidationContext()
!
669
            invalidateLayout(with: context)
!
670
        }
!
671
!
672
        prepareActions.formUnion(.switchStates)
!
673
!
674
        super.finalizeCollectionViewUpdates()
!
675
    }
676
677
    // MARK: - Cell Appearance Animation
678
679
    /// Retrieves the starting layout information for an item being inserted into the collection view.
!
680
    public override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
681
        var attributes: ChatLayoutAttributes?
!
682
!
683
        let itemPath = itemIndexPath.itemPath
!
684
        if state == .afterUpdate {
!
685
            if controller.insertedIndexes.contains(itemIndexPath) || controller.insertedSectionsIndexes.contains(itemPath.section) {
!
686
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .afterUpdate)?.typedCopy()
!
687
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: true)
!
688
                attributes.map { attributes in
!
689
                    guard let delegate = delegate else {
!
690
                        attributes.alpha = 0
!
691
                        return
!
692
                    }
!
693
                    delegate.initialLayoutAttributesForInsertedItem(self, of: .cell, at: itemIndexPath, modifying: attributes, on: .initial)
!
694
                }
!
695
                attributesForPendingAnimations[.cell]?[itemPath] = attributes
!
696
            } else if let itemIdentifier = controller.itemIdentifier(for: itemPath, kind: .cell, at: .afterUpdate),
!
697
                      let initialIndexPath = controller.itemPath(by: itemIdentifier, kind: .cell, at: .beforeUpdate) {
!
698
                attributes = controller.itemAttributes(for: initialIndexPath, kind: .cell, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forCellWith: itemIndexPath)
!
699
                attributes?.indexPath = itemIndexPath
!
700
                if !isIOS13orHigher {
!
701
                    if controller.reloadedIndexes.contains(itemIndexPath) || controller.reloadedSectionsIndexes.contains(itemPath.section) {
!
702
                        // It is needed to position the new cell in the middle of the old cell on ios 12
!
703
                        attributesForPendingAnimations[.cell]?[itemPath] = attributes
!
704
                    }
!
705
                }
!
706
            } else {
!
707
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
708
            }
!
709
        } else {
!
710
            attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
711
        }
!
712
!
713
        return attributes
!
714
    }
715
716
    /// Retrieves the final layout information for an item that is about to be removed from the collection view.
!
717
    public override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
718
        var attributes: ChatLayoutAttributes?
!
719
!
720
        let itemPath = itemIndexPath.itemPath
!
721
        if state == .afterUpdate {
!
722
            if controller.deletedIndexes.contains(itemIndexPath) || controller.deletedSectionsIndexes.contains(itemPath.section) {
!
723
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forCellWith: itemIndexPath)
!
724
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: false)
!
725
                if keepContentOffsetAtBottomOnBatchUpdates,
!
726
                   controller.isLayoutBiggerThanVisibleBounds(at: state),
!
727
                   let attributes = attributes {
!
728
                    attributes.frame = attributes.frame.offsetBy(dx: 0, dy: attributes.frame.height / 2)
!
729
                }
!
730
                attributes.map { attributes in
!
731
                    guard let delegate = delegate else {
!
732
                        attributes.alpha = 0
!
733
                        return
!
734
                    }
!
735
                    delegate.finalLayoutAttributesForDeletedItem(self, of: .cell, at: itemIndexPath, modifying: attributes)
!
736
                }
!
737
            } else if let itemIdentifier = controller.itemIdentifier(for: itemPath, kind: .cell, at: .beforeUpdate),
!
738
                      let finalIndexPath = controller.itemPath(by: itemIdentifier, kind: .cell, at: .afterUpdate) {
!
739
                if controller.movedIndexes.contains(itemIndexPath) || controller.movedSectionsIndexes.contains(itemPath.section) ||
!
740
                    controller.reloadedIndexes.contains(itemIndexPath) || controller.reloadedSectionsIndexes.contains(itemPath.section) {
!
741
                    attributes = controller.itemAttributes(for: finalIndexPath, kind: .cell, at: .afterUpdate)?.typedCopy()
!
742
                } else {
!
743
                    attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)?.typedCopy()
!
744
                }
!
745
                if invalidatedAttributes[.cell]?.contains(itemPath) ?? false {
!
746
                    attributes = nil
!
747
                }
!
748
!
749
                attributes?.indexPath = itemIndexPath
!
750
                attributesForPendingAnimations[.cell]?[itemPath] = attributes
!
751
                if controller.reloadedIndexes.contains(itemIndexPath) || controller.reloadedSectionsIndexes.contains(itemPath.section) {
!
752
                    attributes?.alpha = 0
!
753
                    attributes?.transform = CGAffineTransform(scaleX: 0, y: 0)
!
754
                }
!
755
            } else {
!
756
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
757
            }
!
758
        } else {
!
759
            attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
760
        }
!
761
!
762
        return attributes
!
763
    }
764
765
    // MARK: - Supplementary View Appearance Animation
766
767
    /// Retrieves the starting layout information for a supplementary view being inserted into the collection view.
!
768
    public override func initialLayoutAttributesForAppearingSupplementaryElement(ofKind elementKind: String, at elementIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
769
        var attributes: ChatLayoutAttributes?
!
770
!
771
        let kind = ItemKind(elementKind)
!
772
        let elementPath = elementIndexPath.itemPath
!
773
        if state == .afterUpdate {
!
774
            if controller.insertedSectionsIndexes.contains(elementPath.section) {
!
775
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .afterUpdate)?.typedCopy()
!
776
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: true)
!
777
                attributes.map { attributes in
!
778
                    guard let delegate = delegate else {
!
779
                        attributes.alpha = 0
!
780
                        return
!
781
                    }
!
782
                    delegate.initialLayoutAttributesForInsertedItem(self, of: kind, at: elementIndexPath, modifying: attributes, on: .initial)
!
783
                }
!
784
                attributesForPendingAnimations[kind]?[elementPath] = attributes
!
785
            } else if let itemIdentifier = controller.itemIdentifier(for: elementPath, kind: kind, at: .afterUpdate),
!
786
                      let initialIndexPath = controller.itemPath(by: itemIdentifier, kind: kind, at: .beforeUpdate) {
!
787
                attributes = controller.itemAttributes(for: initialIndexPath, kind: kind, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: elementIndexPath)
!
788
                attributes?.indexPath = elementIndexPath
!
789
!
790
                if !isIOS13orHigher {
!
791
                    if controller.reloadedSectionsIndexes.contains(elementPath.section) {
!
792
                        // It is needed to position the new cell in the middle of the old cell on ios 12
!
793
                        attributesForPendingAnimations[kind]?[elementPath] = attributes
!
794
                    }
!
795
                }
!
796
            } else {
!
797
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
798
            }
!
799
        } else {
!
800
            attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
801
        }
!
802
!
803
        return attributes
!
804
    }
805
806
    /// Retrieves the final layout information for a supplementary view that is about to be removed from the collection view.
!
807
    public override func finalLayoutAttributesForDisappearingSupplementaryElement(ofKind elementKind: String, at elementIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
808
        var attributes: ChatLayoutAttributes?
!
809
!
810
        let kind = ItemKind(elementKind)
!
811
        let elementPath = elementIndexPath.itemPath
!
812
        if state == .afterUpdate {
!
813
            if controller.deletedSectionsIndexes.contains(elementPath.section) {
!
814
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: elementIndexPath)
!
815
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: false)
!
816
                if keepContentOffsetAtBottomOnBatchUpdates,
!
817
                   controller.isLayoutBiggerThanVisibleBounds(at: state),
!
818
                   let attributes = attributes {
!
819
                    attributes.frame = attributes.frame.offsetBy(dx: 0, dy: attributes.frame.height / 2)
!
820
                }
!
821
                attributes.map { attributes in
!
822
                    guard let delegate = delegate else {
!
823
                        attributes.alpha = 0
!
824
                        return
!
825
                    }
!
826
                    delegate.finalLayoutAttributesForDeletedItem(self, of: .cell, at: elementIndexPath, modifying: attributes)
!
827
                }
!
828
            } else if let itemIdentifier = controller.itemIdentifier(for: elementPath, kind: kind, at: .beforeUpdate),
!
829
                      let finalIndexPath = controller.itemPath(by: itemIdentifier, kind: kind, at: .afterUpdate) {
!
830
                if controller.movedSectionsIndexes.contains(elementPath.section) || controller.reloadedSectionsIndexes.contains(elementPath.section) {
!
831
                    attributes = controller.itemAttributes(for: finalIndexPath, kind: kind, at: .afterUpdate)?.typedCopy()
!
832
                } else {
!
833
                    attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)?.typedCopy()
!
834
                }
!
835
                if invalidatedAttributes[kind]?.contains(elementPath) ?? false {
!
836
                    attributes = nil
!
837
                }
!
838
!
839
                attributes?.indexPath = elementIndexPath
!
840
                attributesForPendingAnimations[kind]?[elementPath] = attributes
!
841
                if controller.reloadedSectionsIndexes.contains(elementPath.section) {
!
842
                    attributes?.alpha = 0
!
843
                    attributes?.transform = CGAffineTransform(scaleX: 0, y: 0)
!
844
                }
!
845
            } else {
!
846
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
847
            }
!
848
        } else {
!
849
            attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
850
        }
!
851
        return attributes
!
852
    }
853
854
}
855
856
extension ChatLayout {
857
!
858
    func configuration(for element: ItemKind, at itemPath: ItemPath) -> ItemModel.Configuration {
!
859
        let indexPath = itemPath.indexPath
!
860
        let itemSize = estimatedSize(for: element, at: indexPath)
!
861
        return ItemModel.Configuration(alignment: alignment(for: element, at: indexPath), preferredSize: itemSize.estimated, calculatedSize: itemSize.exact)
!
862
    }
863
!
864
    private func estimatedSize(for element: ItemKind, at indexPath: IndexPath) -> (estimated: CGSize, exact: CGSize?) {
!
865
        guard let delegate = delegate else {
!
866
            return (estimated: estimatedItemSize, exact: nil)
!
867
        }
!
868
!
869
        let itemSize = delegate.sizeForItem(self, of: element, at: indexPath)
!
870
!
871
        switch itemSize {
!
872
        case .auto:
!
873
            return (estimated: estimatedItemSize, exact: nil)
!
874
        case let .estimated(size):
!
875
            return (estimated: size, exact: nil)
!
876
        case let .exact(size):
!
877
            return (estimated: size, exact: size)
!
878
        }
!
879
    }
880
!
881
    private func itemSize(with preferredAttributes: ChatLayoutAttributes) -> CGSize {
!
882
        let itemSize: CGSize
!
883
        if let delegate = delegate,
!
884
           case let .exact(size) = delegate.sizeForItem(self, of: preferredAttributes.kind, at: preferredAttributes.indexPath) {
!
885
            itemSize = size
!
886
        } else {
!
887
            itemSize = preferredAttributes.size
!
888
        }
!
889
        return itemSize
!
890
    }
891
!
892
    private func alignment(for element: ItemKind, at indexPath: IndexPath) -> ChatItemAlignment {
!
893
        guard let delegate = delegate else {
!
894
            return .fullWidth
!
895
        }
!
896
        return delegate.alignmentForItem(self, of: element, at: indexPath)
!
897
    }
898
!
899
    private var estimatedItemSize: CGSize {
!
900
        guard let estimatedItemSize = settings.estimatedItemSize else {
!
901
            guard collectionView != nil else {
!
902
                return .zero
!
903
            }
!
904
            return CGSize(width: layoutFrame.width, height: 40)
!
905
        }
!
906
!
907
        return estimatedItemSize
!
908
    }
909
!
910
    private func resetAttributesForPendingAnimations() {
!
911
        ItemKind.allCases.forEach {
!
912
            attributesForPendingAnimations[$0] = [:]
!
913
        }
!
914
    }
915
!
916
    private func resetInvalidatedAttributes() {
!
917
        ItemKind.allCases.forEach {
!
918
            invalidatedAttributes[$0] = []
!
919
        }
!
920
    }
921
922
}
923
924
extension ChatLayout: ChatLayoutRepresentation {
925
!
926
    func numberOfItems(in section: Int) -> Int {
!
927
        guard let collectionView = collectionView else {
!
928
            return .zero
!
929
        }
!
930
        return collectionView.numberOfItems(inSection: section)
!
931
    }
932
!
933
    func shouldPresentHeader(at sectionIndex: Int) -> Bool {
!
934
        return delegate?.shouldPresentHeader(self, at: sectionIndex) ?? false
!
935
    }
936
!
937
    func shouldPresentFooter(at sectionIndex: Int) -> Bool {
!
938
        return delegate?.shouldPresentFooter(self, at: sectionIndex) ?? false
!
939
    }
940
941
}
942
943
extension ChatLayout {
944
!
945
    private var maxPossibleContentOffset: CGPoint {
!
946
        guard let collectionView = collectionView else {
!
947
            return .zero
!
948
        }
!
949
        let maxContentOffset = max(0 - collectionView.adjustedContentInset.top, controller.contentHeight(at: state) - collectionView.frame.height + collectionView.adjustedContentInset.bottom)
!
950
        return CGPoint(x: 0, y: maxContentOffset)
!
951
    }
952
!
953
    private var isUserInitiatedScrolling: Bool {
!
954
        guard let collectionView = collectionView else {
!
955
            return false
!
956
        }
!
957
        return collectionView.isDragging || collectionView.isDecelerating
!
958
    }
959
960
}
961
962
var isIOS13orHigher: Bool = {
!
963
    if #available(iOS 13.0, *) {
!
964
        return true
!
965
    } else {
!
966
        return false
!
967
    }
!
968
}()
!
969
970
var isIOS15_1orHigher: Bool = {
971
    if #available(iOS 15.1, *) {
!
972
        return true
!
973
    } else {
!
974
        return false
!
975
    }
!
976
}()
!
977
!
978
var isIOS15_2orHigher: Bool = {
979
    if #available(iOS 15.2, *) {
980
        return true
!
981
    } else {
!
982
        return false
!
983
    }
!
984
}()
!