Slather logo

Coverage for "CollectionViewChatLayout.swift" : 0.00%

(0 of 763 relevant lines covered)

ChatLayout/Classes/Core/CollectionViewChatLayout.swift

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