Slather logo

Coverage for "ChatLayout.swift" : 0.00%

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