Slather logo

Coverage for "ChatLayout.swift" : 0.00%

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