Slather logo

Coverage for "ChatLayout.swift" : 0.00%

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