Slather logo

Coverage for "ChatLayout.swift" : 0.00%

(0 of 760 relevant lines covered)

ChatLayout/Classes/Core/ChatLayout.swift

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