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