Slather logo

Coverage for "CollectionViewChatLayout.swift" : 0.00%

(0 of 754 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 visibleBounds = visibleBounds
!
240
        let layoutAttributes = controller.layoutAttributesForElements(in: visibleBounds.inset(by: insets),
!
241
                                                                      state: state,
!
242
                                                                      ignoreCache: true)
!
243
            .sorted(by: { $0.frame.maxY < $1.frame.maxY })
!
244
!
245
        switch edge {
!
246
        case .top:
!
247
            guard let firstVisibleItemAttributes = layoutAttributes.first(where: { $0.frame.minY >= visibleBounds.higherPoint.y }) else {
!
248
                return nil
!
249
            }
!
250
            let visibleBoundsTopOffset = firstVisibleItemAttributes.frame.minY - visibleBounds.higherPoint.y - settings.additionalInsets.top
!
251
            return ChatLayoutPositionSnapshot(indexPath: firstVisibleItemAttributes.indexPath, kind: firstVisibleItemAttributes.kind, edge: .top, offset: visibleBoundsTopOffset)
!
252
        case .bottom:
!
253
            guard let lastVisibleItemAttributes = layoutAttributes.last(where: { $0.frame.minY <= visibleBounds.lowerPoint.y }) else {
!
254
                return nil
!
255
            }
!
256
            let visibleBoundsBottomOffset = visibleBounds.lowerPoint.y - lastVisibleItemAttributes.frame.maxY - settings.additionalInsets.bottom
!
257
            return ChatLayoutPositionSnapshot(indexPath: lastVisibleItemAttributes.indexPath, kind: lastVisibleItemAttributes.kind, edge: .bottom, offset: visibleBoundsBottomOffset)
!
258
        }
!
259
    }
!
260
261
    /// Invalidates layout of the `UICollectionView` and trying to keep the offset of the item provided in `ChatLayoutPositionSnapshot`
262
    /// - Parameter snapshot: `ChatLayoutPositionSnapshot`
263
    public func restoreContentOffset(with snapshot: ChatLayoutPositionSnapshot) {
!
264
        guard let collectionView = collectionView else {
!
265
            return
!
266
        }
!
267
        collectionView.setNeedsLayout()
!
268
        collectionView.layoutIfNeeded()
!
269
        currentPositionSnapshot = snapshot
!
270
        let context = ChatLayoutInvalidationContext()
!
271
        context.invalidateLayoutMetrics = false
!
272
        invalidateLayout(with: context)
!
273
        collectionView.setNeedsLayout()
!
274
        collectionView.layoutIfNeeded()
!
275
        currentPositionSnapshot = nil
!
276
    }
!
277
278
    // MARK: Providing Layout Attributes
279
280
    /// Tells the layout object to update the current layout.
281
    public override func prepare() {
!
282
        super.prepare()
!
283
!
284
        guard let collectionView = collectionView,
!
285
              !prepareActions.isEmpty else {
!
286
            return
!
287
        }
!
288
!
289
        #if DEBUG
!
290
        if collectionView.isPrefetchingEnabled {
!
291
            preconditionFailure("UICollectionView with prefetching enabled is not supported due to https://openradar.appspot.com/40926834 bug.")
!
292
        }
!
293
        #endif
!
294
!
295
        if prepareActions.contains(.switchStates) {
!
296
            controller.commitUpdates()
!
297
            state = .beforeUpdate
!
298
            resetAttributesForPendingAnimations()
!
299
            resetInvalidatedAttributes()
!
300
        }
!
301
!
302
        if prepareActions.contains(.recreateSectionModels) {
!
303
            var sections: ContiguousArray<SectionModel<CollectionViewChatLayout>> = []
!
304
            for sectionIndex in 0..<collectionView.numberOfSections {
!
305
                // Header
!
306
                let header: ItemModel?
!
307
                if delegate?.shouldPresentHeader(self, at: sectionIndex) == true {
!
308
                    let headerPath = IndexPath(item: 0, section: sectionIndex)
!
309
                    header = ItemModel(with: configuration(for: .header, at: headerPath))
!
310
                } else {
!
311
                    header = nil
!
312
                }
!
313
!
314
                // Items
!
315
                var items: ContiguousArray<ItemModel> = []
!
316
                for itemIndex in 0..<collectionView.numberOfItems(inSection: sectionIndex) {
!
317
                    let itemPath = IndexPath(item: itemIndex, section: sectionIndex)
!
318
                    items.append(ItemModel(with: configuration(for: .cell, at: itemPath)))
!
319
                }
!
320
!
321
                // Footer
!
322
                let footer: ItemModel?
!
323
                if delegate?.shouldPresentFooter(self, at: sectionIndex) == true {
!
324
                    let footerPath = IndexPath(item: 0, section: sectionIndex)
!
325
                    footer = ItemModel(with: configuration(for: .footer, at: footerPath))
!
326
                } else {
!
327
                    footer = nil
!
328
                }
!
329
                var section = SectionModel(header: header, footer: footer, items: items, collectionLayout: self)
!
330
                section.assembleLayout()
!
331
                sections.append(section)
!
332
            }
!
333
            controller.set(sections, at: .beforeUpdate)
!
334
        }
!
335
!
336
        if prepareActions.contains(.updateLayoutMetrics),
!
337
           !prepareActions.contains(.recreateSectionModels) {
!
338
            var sections: ContiguousArray<SectionModel> = controller.layout(at: state).sections
!
339
            sections.withUnsafeMutableBufferPointer { directlyMutableSections in
!
340
                for sectionIndex in 0..<directlyMutableSections.count {
!
341
                    var section = directlyMutableSections[sectionIndex]
!
342
!
343
                    // Header
!
344
                    if var header = section.header {
!
345
                        header.resetSize()
!
346
                        section.set(header: header)
!
347
                    }
!
348
!
349
                    // Items
!
350
                    var items: ContiguousArray<ItemModel> = section.items
!
351
                    items.withUnsafeMutableBufferPointer { directlyMutableItems in
!
352
                        DispatchQueue.concurrentPerform(iterations: directlyMutableItems.count, execute: { rowIndex in
!
353
                            directlyMutableItems[rowIndex].resetSize()
!
354
                        })
!
355
                    }
!
356
                    section.set(items: items)
!
357
!
358
                    // Footer
!
359
                    if var footer = section.footer {
!
360
                        footer.resetSize()
!
361
                        section.set(footer: footer)
!
362
                    }
!
363
!
364
                    section.assembleLayout()
!
365
                    directlyMutableSections[sectionIndex] = section
!
366
                }
!
367
            }
!
368
            controller.set(sections, at: state)
!
369
        }
!
370
!
371
        if prepareActions.contains(.cachePreviousContentInsets) {
!
372
            cachedCollectionViewInset = adjustedContentInset
!
373
        }
!
374
!
375
        if prepareActions.contains(.cachePreviousWidth) {
!
376
            cachedCollectionViewSize = collectionView.bounds.size
!
377
        }
!
378
!
379
        prepareActions = []
!
380
    }
!
381
382
    /// Retrieves the layout attributes for all of the cells and views in the specified rectangle.
383
    public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
!
384
        // This early return prevents an issue that causes overlapping / misplaced elements after an
!
385
        // off-screen batch update occurs. The root cause of this issue is that `UICollectionView`
!
386
        // expects `layoutAttributesForElementsInRect:` to return post-batch-update layout attributes
!
387
        // immediately after an update is sent to the collection view via the insert/delete/reload/move
!
388
        // functions. Unfortunately, this is impossible - when batch updates occur, `invalidateLayout:`
!
389
        // is invoked immediately with a context that has `invalidateDataSourceCounts` set to `true`.
!
390
        // At this time, `CollectionViewChatLayout` has no way of knowing the details of this data source count
!
391
        // change (where the insert/delete/move took place). `CollectionViewChatLayout` only gets this additional
!
392
        // information once `prepareForCollectionViewUpdates:` is invoked. At that time, we're able to
!
393
        // update our layout's source of truth, the `StateController`, which allows us to resolve the
!
394
        // post-batch-update layout and return post-batch-update layout attributes from this function.
!
395
        // Between the time that `invalidateLayout:` is invoked with `invalidateDataSourceCounts` set to
!
396
        // `true`, and when `prepareForCollectionViewUpdates:` is invoked with details of the updates,
!
397
        // `layoutAttributesForElementsInRect:` is invoked with the expectation that we already have a
!
398
        // fully resolved layout. If we return incorrect layout attributes at that time, then we'll have
!
399
        // overlapping elements / visual defects. To prevent this, we can return `nil` in this
!
400
        // situation, which works around the bug.
!
401
        // `UICollectionViewCompositionalLayout`, in classic UIKit fashion, avoids this bug / feature by
!
402
        // implementing the private function
!
403
        // `_prepareForCollectionViewUpdates:withDataSourceTranslator:`, which provides the layout with
!
404
        // details about the updates to the collection view before `layoutAttributesForElementsInRect:`
!
405
        // is invoked, enabling them to resolve their layout in time.
!
406
        guard !dontReturnAttributes else {
!
407
            return nil
!
408
        }
!
409
!
410
        let visibleAttributes = controller.layoutAttributesForElements(in: rect, state: state)
!
411
        return visibleAttributes
!
412
    }
!
413
414
    /// Retrieves layout information for an item at the specified index path with a corresponding cell.
415
    public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
416
        guard !dontReturnAttributes else {
!
417
            return nil
!
418
        }
!
419
        let attributes = controller.itemAttributes(for: indexPath.itemPath, kind: .cell, at: state)
!
420
!
421
        return attributes
!
422
    }
!
423
424
    /// Retrieves the layout attributes for the specified supplementary view.
425
    public override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
426
        guard !dontReturnAttributes else {
!
427
            return nil
!
428
        }
!
429
!
430
        let kind = ItemKind(elementKind)
!
431
        let attributes = controller.itemAttributes(for: indexPath.itemPath, kind: kind, at: state)
!
432
!
433
        return attributes
!
434
    }
!
435
436
    // MARK: Coordinating Animated Changes
437
438
    /// Prepares the layout object for animated changes to the view’s bounds or the insertion or deletion of items.
439
    public override func prepare(forAnimatedBoundsChange oldBounds: CGRect) {
!
440
        controller.isAnimatedBoundsChange = true
!
441
        controller.process(changeItems: [])
!
442
        state = .afterUpdate
!
443
        prepareActions.remove(.switchStates)
!
444
        guard let collectionView = collectionView,
!
445
              oldBounds.width != collectionView.bounds.width,
!
446
              keepContentOffsetAtBottomOnBatchUpdates,
!
447
              controller.isLayoutBiggerThanVisibleBounds(at: state) else {
!
448
            return
!
449
        }
!
450
        let newBounds = collectionView.bounds
!
451
        let heightDifference = oldBounds.height - newBounds.height
!
452
        controller.proposedCompensatingOffset += heightDifference + (oldBounds.origin.y - newBounds.origin.y)
!
453
    }
!
454
455
    /// Cleans up after any animated changes to the view’s bounds or after the insertion or deletion of items.
456
    public override func finalizeAnimatedBoundsChange() {
!
457
        if controller.isAnimatedBoundsChange {
!
458
            state = .beforeUpdate
!
459
            resetInvalidatedAttributes()
!
460
            resetAttributesForPendingAnimations()
!
461
            controller.commitUpdates()
!
462
            controller.isAnimatedBoundsChange = false
!
463
            controller.proposedCompensatingOffset = 0
!
464
            controller.batchUpdateCompensatingOffset = 0
!
465
        }
!
466
    }
!
467
468
    // MARK: Context Invalidation
469
470
    /// Asks the layout object if changes to a self-sizing cell require a layout update.
471
    public override func shouldInvalidateLayout(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> Bool {
!
472
        let preferredAttributesItemPath = preferredAttributes.indexPath.itemPath
!
473
        guard let preferredMessageAttributes = preferredAttributes as? ChatLayoutAttributes,
!
474
              let item = controller.item(for: preferredAttributesItemPath, kind: preferredMessageAttributes.kind, at: state) else {
!
475
            return true
!
476
        }
!
477
!
478
        let shouldInvalidateLayout = item.calculatedSize == nil || item.alignment != preferredMessageAttributes.alignment
!
479
!
480
        return shouldInvalidateLayout
!
481
    }
!
482
483
    /// Retrieves a context object that identifies the portions of the layout that should change in response to dynamic cell changes.
484
    public override func invalidationContext(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext {
!
485
        guard let preferredMessageAttributes = preferredAttributes as? ChatLayoutAttributes else {
!
486
            return super.invalidationContext(forPreferredLayoutAttributes: preferredAttributes, withOriginalAttributes: originalAttributes)
!
487
        }
!
488
!
489
        let preferredAttributesItemPath = preferredMessageAttributes.indexPath.itemPath
!
490
!
491
        if state == .afterUpdate {
!
492
            invalidatedAttributes[preferredMessageAttributes.kind]?.insert(preferredAttributesItemPath)
!
493
        }
!
494
!
495
        let layoutAttributesForPendingAnimation = attributesForPendingAnimations[preferredMessageAttributes.kind]?[preferredAttributesItemPath]
!
496
!
497
        let newItemSize = itemSize(with: preferredMessageAttributes)
!
498
        let newItemAlignment: ChatItemAlignment
!
499
        if controller.reloadedIndexes.contains(preferredMessageAttributes.indexPath) {
!
500
            newItemAlignment = alignment(for: preferredMessageAttributes.kind, at: preferredMessageAttributes.indexPath)
!
501
        } else {
!
502
            newItemAlignment = preferredMessageAttributes.alignment
!
503
        }
!
504
        controller.update(preferredSize: newItemSize,
!
505
                          alignment: newItemAlignment,
!
506
                          for: preferredAttributesItemPath,
!
507
                          kind: preferredMessageAttributes.kind,
!
508
                          at: state)
!
509
!
510
        let context = super.invalidationContext(forPreferredLayoutAttributes: preferredMessageAttributes, withOriginalAttributes: originalAttributes) as! ChatLayoutInvalidationContext
!
511
!
512
        let heightDifference = newItemSize.height - originalAttributes.size.height
!
513
        let isAboveBottomEdge = originalAttributes.frame.minY.rounded() <= visibleBounds.maxY.rounded()
!
514
!
515
        if heightDifference != 0,
!
516
           (keepContentOffsetAtBottomOnBatchUpdates && controller.contentHeight(at: state).rounded() + heightDifference > visibleBounds.height.rounded()) || isUserInitiatedScrolling,
!
517
           isAboveBottomEdge {
!
518
            context.contentOffsetAdjustment.y += heightDifference
!
519
            invalidationActions.formUnion([.shouldInvalidateOnBoundsChange])
!
520
        }
!
521
!
522
        if let attributes = controller.itemAttributes(for: preferredAttributesItemPath, kind: preferredMessageAttributes.kind, at: state)?.typedCopy() {
!
523
            layoutAttributesForPendingAnimation?.frame = attributes.frame
!
524
            if state == .afterUpdate {
!
525
                controller.totalProposedCompensatingOffset += heightDifference
!
526
                controller.offsetByTotalCompensation(attributes: layoutAttributesForPendingAnimation, for: state, backward: true)
!
527
                if controller.insertedIndexes.contains(preferredMessageAttributes.indexPath) ||
!
528
                    controller.insertedSectionsIndexes.contains(preferredMessageAttributes.indexPath.section) {
!
529
                    layoutAttributesForPendingAnimation.map { attributes in
!
530
                        guard let delegate = delegate else {
!
531
                            attributes.alpha = 0
!
532
                            return
!
533
                        }
!
534
                        delegate.initialLayoutAttributesForInsertedItem(self, of: .cell, at: attributes.indexPath, modifying: attributes, on: .invalidation)
!
535
                    }
!
536
                }
!
537
            }
!
538
        } else {
!
539
            layoutAttributesForPendingAnimation?.frame.size = newItemSize
!
540
        }
!
541
!
542
        if #available(iOS 13.0, *) {
!
543
            switch preferredMessageAttributes.kind {
!
544
            case .cell:
!
545
                context.invalidateItems(at: [preferredMessageAttributes.indexPath])
!
546
            case .header, .footer:
!
547
                context.invalidateSupplementaryElements(ofKind: preferredMessageAttributes.kind.supplementaryElementStringType, at: [preferredMessageAttributes.indexPath])
!
548
            }
!
549
        }
!
550
!
551
        context.invalidateLayoutMetrics = false
!
552
!
553
        return context
!
554
    }
!
555
556
    /// Asks the layout object if the new bounds require a layout update.
557
    public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
!
558
        let shouldInvalidateLayout = cachedCollectionViewSize != .some(newBounds.size) ||
!
559
            cachedCollectionViewInset != .some(adjustedContentInset) ||
!
560
            invalidationActions.contains(.shouldInvalidateOnBoundsChange)
!
561
!
562
        invalidationActions.remove(.shouldInvalidateOnBoundsChange)
!
563
        return shouldInvalidateLayout
!
564
    }
!
565
566
    /// Retrieves a context object that defines the portions of the layout that should change when a bounds change occurs.
567
    public override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
!
568
        let invalidationContext = super.invalidationContext(forBoundsChange: newBounds) as! ChatLayoutInvalidationContext
!
569
        invalidationContext.invalidateLayoutMetrics = false
!
570
        return invalidationContext
!
571
    }
!
572
573
    /// Invalidates the current layout using the information in the provided context object.
574
    public override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) {
!
575
        guard let collectionView = collectionView else {
!
576
            super.invalidateLayout(with: context)
!
577
            return
!
578
        }
!
579
!
580
        guard let context = context as? ChatLayoutInvalidationContext else {
!
581
            assertionFailure("`context` must be an instance of `ChatLayoutInvalidationContext`.")
!
582
            return
!
583
        }
!
584
!
585
        controller.resetCachedAttributes()
!
586
!
587
        dontReturnAttributes = context.invalidateDataSourceCounts && !context.invalidateEverything
!
588
!
589
        if context.invalidateEverything {
!
590
            prepareActions.formUnion([.recreateSectionModels])
!
591
        }
!
592
!
593
        // Checking `cachedCollectionViewWidth != collectionView.bounds.size.width` is necessary
!
594
        // because the collection view's width can change without a `contentSizeAdjustment` occurring.
!
595
        if context.contentSizeAdjustment.width != 0 || cachedCollectionViewSize != collectionView.bounds.size {
!
596
            prepareActions.formUnion([.cachePreviousWidth])
!
597
        }
!
598
!
599
        if cachedCollectionViewInset != adjustedContentInset {
!
600
            prepareActions.formUnion([.cachePreviousContentInsets])
!
601
        }
!
602
!
603
        if context.invalidateLayoutMetrics, !context.invalidateDataSourceCounts {
!
604
            prepareActions.formUnion([.updateLayoutMetrics])
!
605
        }
!
606
!
607
        if let currentPositionSnapshot = currentPositionSnapshot {
!
608
            let contentHeight = controller.contentHeight(at: state)
!
609
            if let frame = controller.itemFrame(for: currentPositionSnapshot.indexPath.itemPath, kind: currentPositionSnapshot.kind, at: state, isFinal: true),
!
610
               contentHeight != 0,
!
611
               contentHeight > visibleBounds.size.height {
!
612
                switch currentPositionSnapshot.edge {
!
613
                case .top:
!
614
                    let desiredOffset = frame.minY - currentPositionSnapshot.offset - collectionView.adjustedContentInset.top - settings.additionalInsets.top
!
615
                    context.contentOffsetAdjustment.y = desiredOffset - collectionView.contentOffset.y
!
616
                case .bottom:
!
617
                    let maxAllowed = max(-collectionView.adjustedContentInset.top, contentHeight - collectionView.frame.height + collectionView.adjustedContentInset.bottom)
!
618
                    let desiredOffset = max(min(maxAllowed, frame.maxY + currentPositionSnapshot.offset - collectionView.bounds.height + collectionView.adjustedContentInset.bottom + settings.additionalInsets.bottom), -collectionView.adjustedContentInset.top)
!
619
                    context.contentOffsetAdjustment.y = desiredOffset - collectionView.contentOffset.y
!
620
                }
!
621
            }
!
622
        }
!
623
        super.invalidateLayout(with: context)
!
624
    }
!
625
626
    /// Invalidates the current layout and triggers a layout update.
627
    public override func invalidateLayout() {
!
628
        super.invalidateLayout()
!
629
    }
!
630
631
    /// Retrieves the content offset to use after an animated layout update or change.
632
    public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
!
633
        if controller.proposedCompensatingOffset != 0,
!
634
           let collectionView = collectionView {
!
635
            let minPossibleContentOffset = -collectionView.adjustedContentInset.top
!
636
            let newProposedContentOffset = CGPoint(x: proposedContentOffset.x, y: max(minPossibleContentOffset, min(proposedContentOffset.y + controller.proposedCompensatingOffset, maxPossibleContentOffset.y)))
!
637
            invalidationActions.formUnion([.shouldInvalidateOnBoundsChange])
!
638
            if needsIOS15_1IssueFix {
!
639
                controller.proposedCompensatingOffset = 0
!
640
                collectionView.contentOffset = newProposedContentOffset
!
641
                return newProposedContentOffset
!
642
            } else {
!
643
                controller.proposedCompensatingOffset = 0
!
644
                return newProposedContentOffset
!
645
            }
!
646
        }
!
647
        return super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
!
648
    }
!
649
650
    // MARK: Responding to Collection View Updates
651
652
    /// Notifies the layout object that the contents of the collection view are about to change.
653
    public override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
!
654
        let changeItems = updateItems.compactMap { ChangeItem(with: $0) }
!
655
        controller.process(changeItems: changeItems)
!
656
        state = .afterUpdate
!
657
        dontReturnAttributes = false
!
658
        super.prepare(forCollectionViewUpdates: updateItems)
!
659
    }
!
660
661
    /// Performs any additional animations or clean up needed during a collection view update.
662
    public override func finalizeCollectionViewUpdates() {
!
663
        controller.proposedCompensatingOffset = 0
!
664
!
665
        if keepContentOffsetAtBottomOnBatchUpdates,
!
666
           controller.isLayoutBiggerThanVisibleBounds(at: state),
!
667
           controller.batchUpdateCompensatingOffset != 0,
!
668
           let collectionView = collectionView {
!
669
            let compensatingOffset: CGFloat
!
670
            if controller.contentSize(for: .beforeUpdate).height > visibleBounds.size.height {
!
671
                compensatingOffset = controller.batchUpdateCompensatingOffset
!
672
            } else {
!
673
                compensatingOffset = maxPossibleContentOffset.y - collectionView.contentOffset.y
!
674
            }
!
675
            controller.batchUpdateCompensatingOffset = 0
!
676
            let context = ChatLayoutInvalidationContext()
!
677
            context.contentOffsetAdjustment.y = compensatingOffset
!
678
            invalidateLayout(with: context)
!
679
        } else {
!
680
            controller.batchUpdateCompensatingOffset = 0
!
681
            let context = ChatLayoutInvalidationContext()
!
682
            invalidateLayout(with: context)
!
683
        }
!
684
!
685
        prepareActions.formUnion(.switchStates)
!
686
!
687
        super.finalizeCollectionViewUpdates()
!
688
    }
!
689
690
    // MARK: - Cell Appearance Animation
691
692
    /// Retrieves the starting layout information for an item being inserted into the collection view.
693
    public override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
694
        var attributes: ChatLayoutAttributes?
!
695
!
696
        let itemPath = itemIndexPath.itemPath
!
697
        if state == .afterUpdate {
!
698
            if controller.insertedIndexes.contains(itemIndexPath) || controller.insertedSectionsIndexes.contains(itemPath.section) {
!
699
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .afterUpdate)?.typedCopy()
!
700
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: true)
!
701
                attributes.map { attributes in
!
702
                    guard let delegate = delegate else {
!
703
                        attributes.alpha = 0
!
704
                        return
!
705
                    }
!
706
                    delegate.initialLayoutAttributesForInsertedItem(self, of: .cell, at: itemIndexPath, modifying: attributes, on: .initial)
!
707
                }
!
708
                attributesForPendingAnimations[.cell]?[itemPath] = attributes
!
709
            } else if let itemIdentifier = controller.itemIdentifier(for: itemPath, kind: .cell, at: .afterUpdate),
!
710
                      let initialIndexPath = controller.itemPath(by: itemIdentifier, kind: .cell, at: .beforeUpdate) {
!
711
                attributes = controller.itemAttributes(for: initialIndexPath, kind: .cell, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forCellWith: itemIndexPath)
!
712
                attributes?.indexPath = itemIndexPath
!
713
                if #unavailable(iOS 13.0) {
!
714
                    if controller.reloadedIndexes.contains(itemIndexPath) || controller.reloadedSectionsIndexes.contains(itemPath.section) {
!
715
                        // It is needed to position the new cell in the middle of the old cell on ios 12
!
716
                        attributesForPendingAnimations[.cell]?[itemPath] = attributes
!
717
                    }
!
718
                }
!
719
            } else {
!
720
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
721
            }
!
722
        } else {
!
723
            attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
724
        }
!
725
!
726
        return attributes
!
727
    }
!
728
729
    /// Retrieves the final layout information for an item that is about to be removed from the collection view.
730
    public override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
731
        var attributes: ChatLayoutAttributes?
!
732
!
733
        let itemPath = itemIndexPath.itemPath
!
734
        if state == .afterUpdate {
!
735
            if controller.deletedIndexes.contains(itemIndexPath) || controller.deletedSectionsIndexes.contains(itemPath.section) {
!
736
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forCellWith: itemIndexPath)
!
737
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: false)
!
738
                if keepContentOffsetAtBottomOnBatchUpdates,
!
739
                   controller.isLayoutBiggerThanVisibleBounds(at: state),
!
740
                   let attributes = attributes {
!
741
                    attributes.frame = attributes.frame.offsetBy(dx: 0, dy: attributes.frame.height * 0.2)
!
742
                }
!
743
                attributes.map { attributes in
!
744
                    guard let delegate = delegate else {
!
745
                        attributes.alpha = 0
!
746
                        return
!
747
                    }
!
748
                    delegate.finalLayoutAttributesForDeletedItem(self, of: .cell, at: itemIndexPath, modifying: attributes)
!
749
                }
!
750
            } else if let itemIdentifier = controller.itemIdentifier(for: itemPath, kind: .cell, at: .beforeUpdate),
!
751
                      let finalIndexPath = controller.itemPath(by: itemIdentifier, kind: .cell, at: .afterUpdate) {
!
752
                if controller.movedIndexes.contains(itemIndexPath) || controller.movedSectionsIndexes.contains(itemPath.section) ||
!
753
                    controller.reloadedIndexes.contains(itemIndexPath) || controller.reloadedSectionsIndexes.contains(itemPath.section) {
!
754
                    attributes = controller.itemAttributes(for: finalIndexPath, kind: .cell, at: .afterUpdate)?.typedCopy()
!
755
                } else {
!
756
                    attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)?.typedCopy()
!
757
                }
!
758
                if invalidatedAttributes[.cell]?.contains(itemPath) ?? false {
!
759
                    attributes = nil
!
760
                }
!
761
!
762
                attributes?.indexPath = itemIndexPath
!
763
                attributesForPendingAnimations[.cell]?[itemPath] = attributes
!
764
                if controller.reloadedIndexes.contains(itemIndexPath) || controller.reloadedSectionsIndexes.contains(itemPath.section) {
!
765
                    attributes?.alpha = 0
!
766
                    attributes?.transform = CGAffineTransform(scaleX: 0, y: 0)
!
767
                }
!
768
            } else {
!
769
                attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
770
            }
!
771
        } else {
!
772
            attributes = controller.itemAttributes(for: itemPath, kind: .cell, at: .beforeUpdate)
!
773
        }
!
774
!
775
        return attributes
!
776
    }
!
777
778
    // MARK: - Supplementary View Appearance Animation
779
780
    /// Retrieves the starting layout information for a supplementary view being inserted into the collection view.
781
    public override func initialLayoutAttributesForAppearingSupplementaryElement(ofKind elementKind: String, at elementIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
782
        var attributes: ChatLayoutAttributes?
!
783
!
784
        let kind = ItemKind(elementKind)
!
785
        let elementPath = elementIndexPath.itemPath
!
786
        if state == .afterUpdate {
!
787
            if controller.insertedSectionsIndexes.contains(elementPath.section) {
!
788
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .afterUpdate)?.typedCopy()
!
789
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: true)
!
790
                attributes.map { attributes in
!
791
                    guard let delegate = delegate else {
!
792
                        attributes.alpha = 0
!
793
                        return
!
794
                    }
!
795
                    delegate.initialLayoutAttributesForInsertedItem(self, of: kind, at: elementIndexPath, modifying: attributes, on: .initial)
!
796
                }
!
797
                attributesForPendingAnimations[kind]?[elementPath] = attributes
!
798
            } else if let itemIdentifier = controller.itemIdentifier(for: elementPath, kind: kind, at: .afterUpdate),
!
799
                      let initialIndexPath = controller.itemPath(by: itemIdentifier, kind: kind, at: .beforeUpdate) {
!
800
                attributes = controller.itemAttributes(for: initialIndexPath, kind: kind, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: elementIndexPath)
!
801
                attributes?.indexPath = elementIndexPath
!
802
!
803
                if #unavailable(iOS 13.0) {
!
804
                    if controller.reloadedSectionsIndexes.contains(elementPath.section) {
!
805
                        // It is needed to position the new cell in the middle of the old cell on ios 12
!
806
                        attributesForPendingAnimations[kind]?[elementPath] = attributes
!
807
                    }
!
808
                }
!
809
            } else {
!
810
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
811
            }
!
812
        } else {
!
813
            attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
814
        }
!
815
!
816
        return attributes
!
817
    }
!
818
819
    /// Retrieves the final layout information for a supplementary view that is about to be removed from the collection view.
820
    public override func finalLayoutAttributesForDisappearingSupplementaryElement(ofKind elementKind: String, at elementIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
!
821
        var attributes: ChatLayoutAttributes?
!
822
!
823
        let kind = ItemKind(elementKind)
!
824
        let elementPath = elementIndexPath.itemPath
!
825
        if state == .afterUpdate {
!
826
            if controller.deletedSectionsIndexes.contains(elementPath.section) {
!
827
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)?.typedCopy() ?? ChatLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: elementIndexPath)
!
828
                controller.offsetByTotalCompensation(attributes: attributes, for: state, backward: false)
!
829
                if keepContentOffsetAtBottomOnBatchUpdates,
!
830
                   controller.isLayoutBiggerThanVisibleBounds(at: state),
!
831
                   let attributes = attributes {
!
832
                    attributes.frame = attributes.frame.offsetBy(dx: 0, dy: attributes.frame.height * 0.2)
!
833
                }
!
834
                attributes.map { attributes in
!
835
                    guard let delegate = delegate else {
!
836
                        attributes.alpha = 0
!
837
                        return
!
838
                    }
!
839
                    delegate.finalLayoutAttributesForDeletedItem(self, of: .cell, at: elementIndexPath, modifying: attributes)
!
840
                }
!
841
            } else if let itemIdentifier = controller.itemIdentifier(for: elementPath, kind: kind, at: .beforeUpdate),
!
842
                      let finalIndexPath = controller.itemPath(by: itemIdentifier, kind: kind, at: .afterUpdate) {
!
843
                if controller.movedSectionsIndexes.contains(elementPath.section) || controller.reloadedSectionsIndexes.contains(elementPath.section) {
!
844
                    attributes = controller.itemAttributes(for: finalIndexPath, kind: kind, at: .afterUpdate)?.typedCopy()
!
845
                } else {
!
846
                    attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)?.typedCopy()
!
847
                }
!
848
                if invalidatedAttributes[kind]?.contains(elementPath) ?? false {
!
849
                    attributes = nil
!
850
                }
!
851
!
852
                attributes?.indexPath = elementIndexPath
!
853
                attributesForPendingAnimations[kind]?[elementPath] = attributes
!
854
                if controller.reloadedSectionsIndexes.contains(elementPath.section) {
!
855
                    attributes?.alpha = 0
!
856
                    attributes?.transform = CGAffineTransform(scaleX: 0, y: 0)
!
857
                }
!
858
            } else {
!
859
                attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
860
            }
!
861
        } else {
!
862
            attributes = controller.itemAttributes(for: elementPath, kind: kind, at: .beforeUpdate)
!
863
        }
!
864
        return attributes
!
865
    }
!
866
867
}
868
869
extension CollectionViewChatLayout {
870
871
    func configuration(for element: ItemKind, at indexPath: IndexPath) -> ItemModel.Configuration {
!
872
        let itemSize = estimatedSize(for: element, at: indexPath)
!
873
        return ItemModel.Configuration(alignment: alignment(for: element, at: indexPath), preferredSize: itemSize.estimated, calculatedSize: itemSize.exact)
!
874
    }
!
875
876
    private func estimatedSize(for element: ItemKind, at indexPath: IndexPath) -> (estimated: CGSize, exact: CGSize?) {
!
877
        guard let delegate = delegate else {
!
878
            return (estimated: estimatedItemSize, exact: nil)
!
879
        }
!
880
!
881
        let itemSize = delegate.sizeForItem(self, of: element, at: indexPath)
!
882
!
883
        switch itemSize {
!
884
        case .auto:
!
885
            return (estimated: estimatedItemSize, exact: nil)
!
886
        case let .estimated(size):
!
887
            return (estimated: size, exact: nil)
!
888
        case let .exact(size):
!
889
            return (estimated: size, exact: size)
!
890
        }
!
891
    }
!
892
893
    private func itemSize(with preferredAttributes: ChatLayoutAttributes) -> CGSize {
!
894
        let itemSize: CGSize
!
895
        if let delegate = delegate,
!
896
           case let .exact(size) = delegate.sizeForItem(self, of: preferredAttributes.kind, at: preferredAttributes.indexPath) {
!
897
            itemSize = size
!
898
        } else {
!
899
            itemSize = preferredAttributes.size
!
900
        }
!
901
        return itemSize
!
902
    }
!
903
904
    private func alignment(for element: ItemKind, at indexPath: IndexPath) -> ChatItemAlignment {
!
905
        guard let delegate = delegate else {
!
906
            return .fullWidth
!
907
        }
!
908
        return delegate.alignmentForItem(self, of: element, at: indexPath)
!
909
    }
!
910
911
    private var estimatedItemSize: CGSize {
!
912
        guard let estimatedItemSize = settings.estimatedItemSize else {
!
913
            guard collectionView != nil else {
!
914
                return .zero
!
915
            }
!
916
            return CGSize(width: layoutFrame.width, height: 40)
!
917
        }
!
918
!
919
        return estimatedItemSize
!
920
    }
!
921
922
    private func resetAttributesForPendingAnimations() {
!
923
        ItemKind.allCases.forEach {
!
924
            attributesForPendingAnimations[$0] = [:]
!
925
        }
!
926
    }
!
927
928
    private func resetInvalidatedAttributes() {
!
929
        ItemKind.allCases.forEach {
!
930
            invalidatedAttributes[$0] = []
!
931
        }
!
932
    }
!
933
934
}
935
936
extension CollectionViewChatLayout: ChatLayoutRepresentation {
937
938
    func numberOfItems(in section: Int) -> Int {
!
939
        guard let collectionView = collectionView else {
!
940
            return .zero
!
941
        }
!
942
        return collectionView.numberOfItems(inSection: section)
!
943
    }
!
944
945
    func shouldPresentHeader(at sectionIndex: Int) -> Bool {
!
946
        delegate?.shouldPresentHeader(self, at: sectionIndex) ?? false
!
947
    }
!
948
949
    func shouldPresentFooter(at sectionIndex: Int) -> Bool {
!
950
        delegate?.shouldPresentFooter(self, at: sectionIndex) ?? false
!
951
    }
!
952
953
}
954
955
extension CollectionViewChatLayout {
956
957
    private var maxPossibleContentOffset: CGPoint {
!
958
        guard let collectionView = collectionView else {
!
959
            return .zero
!
960
        }
!
961
        let maxContentOffset = max(0 - collectionView.adjustedContentInset.top, controller.contentHeight(at: state) - collectionView.frame.height + collectionView.adjustedContentInset.bottom)
!
962
        return CGPoint(x: 0, y: maxContentOffset)
!
963
    }
!
964
965
    private var isUserInitiatedScrolling: Bool {
!
966
        guard let collectionView = collectionView else {
!
967
            return false
!
968
        }
!
969
        return collectionView.isDragging || collectionView.isDecelerating
!
970
    }
!
971
972
}