Home telegram - listViewItemNode
Post
Cancel

telegram - listViewItemNode

ListViewItemNode

enum ListViewItemNodeVisibility

1
2
case none
case visible(CGFloat)

class ListViewItemNode:ASDisplayNode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
let rotated: Bool

// index
final var index: Int?

public var isHighlightedInOverlay: Bool = false

// accessoryItemNode
public private(set) var accessoryItemNode: ListViewAccessoryItemNode?

// set accessoryItemNode
func setAccessoryItemNode(_ accessoryItemNode: ListViewAccessoryItemNode?, leftInset: CGFloat, rightInset: CGFloat) {
    self.accessoryItemNode = accessoryItemNode
    if let accessoryItemNode = accessoryItemNode {
        self.layoutAccessoryItemNode(accessoryItemNode, leftInset: leftInset, rightInset: rightInset)
    }
}

// add accessoryItemNode to hierarchy
open func addAccessoryItemNode(_ accessoryItemNode: ListViewAccessoryItemNode) {
    self.addSubnode(accessoryItemNode)
}

// for subclasses to override
open func layoutAccessoryItemNode(_ accessoryItemNode: ListViewAccessoryItemNode, leftInset: CGFloat, rightInset: CGFloat) {
}

// header accessoryItemNode
final var headerAccessoryItemNode: ListViewAccessoryItemNode? {
    didSet {
        if let headerAccessoryItemNode = self.headerAccessoryItemNode {
            self.layoutHeaderAccessoryItemNode(headerAccessoryItemNode)
        }
    }
}

private final var spring: ListViewItemSpring?
private final var animations: [(String, ListViewAnimation)] = []

// wants scroll dynamics
final let wantsScrollDynamics: Bool

// wants trailing item space updates
public final var wantsTrailingItemSpaceUpdates: Bool = false

// scroll position insets
public final var scrollPositioningInsets: UIEdgeInsets = UIEdgeInsets()

// can be used as scroll to item anchor
public final var canBeUsedAsScrollToItemAnchor: Bool = true

// can be selected
open var canBeSelected: Bool {
    return true
}

// can be long tapped
open var canBeLongTapped: Bool {
    return false
}

// prevents touches to other items
open var preventsTouchesToOtherItems: Bool {
    return false
}

// touches to other items prevented
open func touchesToOtherItemsPrevented() {
    
}

// tapped
open func tapped() {
}

// long tapped
open func longTapped() {
}

// set insets
public final var insets: UIEdgeInsets = UIEdgeInsets() {
    didSet {
        let effectiveInsets = self.insets
      // update frame.height
        self.frame = CGRect(origin: self.frame.origin, size: CGSize(width: self.contentSize.width, height: self.contentSize.height + effectiveInsets.top + effectiveInsets.bottom))
        let bounds = self.bounds
      // insets does not affect [bound.origin.x, bound.size]
      // instead affects [bounds.origin.y]
      // update bounds.origin.y
      // -effectiveInsets.top + self.contentOffset + self.transitionOffset
        self.bounds = CGRect(origin: CGPoint(x: bounds.origin.x, y: -effectiveInsets.top + self.contentOffset + self.transitionOffset), size: bounds.size)
    }
}

// contentsize
private final var _contentSize: CGSize = CGSize()
public final var contentSize: CGSize {
    get {
        return self._contentSize
    } set(value) {
        let effectiveInsets = self.insets
      // contentsize affects the frame.size.height, frame.size.width
        self.frame = CGRect(origin: self.frame.origin, size: CGSize(width: value.width, height: value.height + effectiveInsets.top + effectiveInsets.bottom))
    }
}


// contentoffset
private var contentOffset: CGFloat = 0.0 {
    didSet {
        let effectiveInsets = self.insets
        let bounds = self.bounds
      // update bound.origin.y
      // -effectiveInsets.top + self.contentOffset + self.transitionOffset
        self.bounds = CGRect(origin: CGPoint(x: bounds.origin.x, y: -effectiveInsets.top + self.contentOffset + self.transitionOffset), size: bounds.size)
    }
}

// transition offset
public var transitionOffset: CGFloat = 0.0 {
    didSet {
        let effectiveInsets = self.insets
        let bounds = self.bounds
      // update bound.origin.y
      // -effectiveInsets.top + self.contentOffset + self.transitionOffset
        self.bounds = CGRect(origin: CGPoint(x: bounds.origin.x, y: -effectiveInsets.top + self.contentOffset + self.transitionOffset), size: bounds.size)
    }
}

// real time layout (considering animation)
public var layout: ListViewItemNodeLayout {
    var insets = self.insets
    var contentSize = self.contentSize
    
  // insets animation
  // insets = animation.to as! UIEdgeInsets
    if let animation = self.animationForKey("insets") {
        insets = animation.to as! UIEdgeInsets
    }
    
  // apparentHeight animation
  // contentSize.height = (animation.to as! CGFloat) - insets.top - insets.bottom
  // the apparentHeight act as self.frame.height
    if let animation = self.animationForKey("apparentHeight") {
        contentSize.height = (animation.to as! CGFloat) - insets.top - insets.bottom
    }
    
    return ListViewItemNodeLayout(contentSize: contentSize, insets: insets)
}

// displayResourcesReady
public var displayResourcesReady: Signal<Void, NoError> {
    return .complete()
}

// apparentHeight
var apparentHeight: CGFloat = 0.0
private var _bounds: CGRect = CGRect()
private var _position: CGPoint = CGPoint()

// frame getter & setter
open override var frame: CGRect {
    get {
        return CGRect(origin: CGPoint(x: self._position.x - self._bounds.width / 2.0, y: self._position.y - self._bounds.height / 2.0), size: self._bounds.size)
    } set(value) {
        let previousSize = self._bounds.size

        super.frame = value
      // recording _bounds, _position, _contentsize
        self._bounds.size = value.size
        self._position = CGPoint(x: value.midX, y: value.midY)
        let effectiveInsets = self.insets
        self._contentSize = CGSize(width: value.size.width, height: value.size.height - effectiveInsets.top - effectiveInsets.bottom)

        if previousSize != value.size {
            if let headerAccessoryItemNode = self.headerAccessoryItemNode {
              // layout header accessoryItemNode if size changed
                self.layoutHeaderAccessoryItemNode(headerAccessoryItemNode)
            }
        }
    }
}

// bounds getter & setter
open override var bounds: CGRect {
    get {
        return self._bounds
    } set(value) {
        let previousSize = self._bounds.size
        
            // recording _bounds, _contentsize
        super.bounds = value
        self._bounds = value
        let effectiveInsets = self.insets
        self._contentSize = CGSize(width: value.size.width, height: value.size.height - effectiveInsets.top - effectiveInsets.bottom)
        
        if previousSize != value.size {
          // layout header accessoryItemNode if size changed
            if let headerAccessoryItemNode = self.headerAccessoryItemNode {
                self.layoutHeaderAccessoryItemNode(headerAccessoryItemNode)
            }
        }
    }
}

// content bounds
// has a insets diff in vertical direction as self.bounds
public var contentBounds: CGRect {
    let bounds = self.bounds
    let effectiveInsets = self.insets
    return CGRect(origin: CGPoint(x: 0.0, y: bounds.origin.y + effectiveInsets.top), size: CGSize(width: bounds.size.width, height: bounds.size.height - effectiveInsets.top - effectiveInsets.bottom))
}

// position getter & setter
open override var position: CGPoint {
    get {
        return self._position
    } set(value) {
      // recording _position
        super.position = value
        self._position = value
    }
}

// apparent frame
// the real time frame
public final var apparentFrame: CGRect {
    var frame = self.frame
    frame.size.height = self.apparentHeight
    return frame
}

// apparent content frame
// the real time content frame
public final var apparentContentFrame: CGRect {
    var frame = self.frame
    let insets = self.insets
    frame.origin.y += insets.top
    frame.size.height = self.apparentHeight - insets.top - insets.bottom
    return frame
}

// apparent bounds
// bound with apparent height
public final var apparentBounds: CGRect {
    var bounds = self.bounds
    bounds.size.height = self.apparentHeight
    return bounds
}

// reuse 
// for subclasses to override
open func reuse() {
}

// add scrolling offset
// set contentoffset
final func addScrollingOffset(_ scrollingOffset: CGFloat) {
    if self.spring != nil {
        self.contentOffset += scrollingOffset
    }
}

// initialize dynamics from sibling
 func initializeDynamicsFromSibling(_ itemView: ListViewItemNode, additionalOffset: CGFloat) {
     if let itemViewSpring = itemView.spring {
         self.contentOffset = itemView.contentOffset + additionalOffset
         self.spring?.velocity = itemViewSpring.velocity
     }
 }

// animate
public func animate(_ timestamp: Double) -> Bool {
    var continueAnimations = false

    if let _ = self.spring {
        var offset = self.contentOffset

        let frictionConstant: CGFloat = testSpringFriction
        let springConstant: CGFloat = testSpringConstant
        let time: CGFloat = 1.0 / 60.0

        // friction force = velocity * friction constant
        let frictionForce = self.spring!.velocity * frictionConstant
        // spring force = (target point - current position) * spring constant
        let springForce = -self.contentOffset * springConstant
        // force = spring force - friction force
        let force = springForce - frictionForce

        // velocity = current velocity + force * time / mass
        self.spring!.velocity = self.spring!.velocity + force * time
        // position = current position + velocity * time
        offset = self.contentOffset + self.spring!.velocity * time

        offset = offset.isNaN ? 0.0 : offset

        let epsilon: CGFloat = 0.1
        if abs(offset) < epsilon && abs(self.spring!.velocity) < epsilon {
            offset = 0.0
            self.spring!.velocity = 0.0
        } else {
            continueAnimations = true
        }

        if abs(offset) > 250.0 {
            offset = offset < 0.0 ? -250.0 : 250.0
        }
        self.contentOffset = offset
    }

    var i = 0
    var animationCount = self.animations.count
    while i < animationCount {
        let (_, animation) = self.animations[i]
        animation.applyAt(timestamp)

        if animation.completeAt(timestamp) {
            animations.remove(at: i)
            animationCount -= 1
            i -= 1
        } else {
            continueAnimations = true
        }

        i += 1
    }

    if let accessoryItemNode = self.accessoryItemNode {
        if (accessoryItemNode.animate(timestamp)) {
            continueAnimations = true
        }
    }

    return continueAnimations
}

// layout
// for subclasses to override
open func layoutForParams(_ params: ListViewItemLayoutParams, item: ListViewItem, previousItem: ListViewItem?, nextItem: ListViewItem?) {
}

// query animation with key
public func animationForKey(_ key: String) -> ListViewAnimation? {
    for (animationKey, animation) in self.animations {
        if animationKey == key {
            return animation
        }
    }
    return nil
}

// set animation with key
public final func setAnimationForKey(_ key: String, animation: ListViewAnimation?) {
    for i in 0 ..< self.animations.count {
        let (currentKey, currentAnimation) = self.animations[i]
        if currentKey == key {
            self.animations.remove(at: i)
            currentAnimation.cancel()
            break
        }
    }
    if let animation = animation {
        self.animations.append((key, animation))
    }
}

// cancell and remove all animations
public final func removeAllAnimations() {
    let previousAnimations = self.animations
    self.animations.removeAll()
    
    for (_, animation) in previousAnimations {
        animation.cancel()
    }
    
    self.accessoryItemNode?.removeAllAnimations()
}

// add insets animation
public func addInsetsAnimationToValue(_ value: UIEdgeInsets, duration: Double, beginAt: Double) {
    let animation = ListViewAnimation(from: self.insets, to: value, duration: duration, curve: listViewAnimationCurveSystem, beginAt: beginAt, update: { [weak self] _, currentValue in
        if let strongSelf = self {
            strongSelf.insets = currentValue
        }
    })
    self.setAnimationForKey("insets", animation: animation)
}

// add height animation
public func addHeightAnimation(_ value: CGFloat, duration: Double, beginAt: Double, update: ((CGFloat, CGFloat) -> Void)? = nil) {
    let animation = ListViewAnimation(from: self.bounds.height, to: value, duration: duration, curve: listViewAnimationCurveSystem, beginAt: beginAt, update: { [weak self] progress, currentValue in
        if let strongSelf = self {
            let frame = strongSelf.frame
            strongSelf.frame = CGRect(origin: frame.origin, size: CGSize(width: frame.width, height: currentValue))
            if let update = update {
                update(progress, currentValue)
            }
        }
    })
    self.setAnimationForKey("height", animation: animation)
}

// copy height and apparentheight animations
func copyHeightAndApparentHeightAnimations(to otherNode: ListViewItemNode) {
    if let animation = self.animationForKey("apparentHeight") {
        let updatedAnimation = ListViewAnimation(copying: animation, update: { [weak otherNode] (progress: CGFloat, currentValue: CGFloat) -> Void in
            if let strongSelf = otherNode {
                let frame = strongSelf.frame
                strongSelf.frame = CGRect(origin: frame.origin, size: CGSize(width: frame.width, height: currentValue))
            }
        })
        otherNode.setAnimationForKey("height", animation: updatedAnimation)
    }
    
    if let animation = self.animationForKey("apparentHeight") {
        let updatedAnimation = ListViewAnimation(copying: animation, update: { [weak otherNode] (progress: CGFloat, currentValue: CGFloat) -> Void in
            if let strongSelf = otherNode {
                strongSelf.apparentHeight = currentValue
            }
        })
        otherNode.setAnimationForKey("apparentHeight", animation: updatedAnimation)
    }
}

// and apparentheight animation
public func addApparentHeightAnimation(_ value: CGFloat, duration: Double, beginAt: Double, update: ((CGFloat, CGFloat) -> Void)? = nil) {
    let animation = ListViewAnimation(from: self.apparentHeight, to: value, duration: duration, curve: listViewAnimationCurveSystem, beginAt: beginAt, update: { [weak self] progress, currentValue in
        if let strongSelf = self {
            strongSelf.apparentHeight = currentValue
            if let update = update {
                update(progress, currentValue)
            }
        }
    })
    self.setAnimationForKey("apparentHeight", animation: animation)
}

// modify apparentheight animation
public func modifyApparentHeightAnimation(_ value: CGFloat, beginAt: Double) {
    if let previousAnimation = self.animationForKey("apparentHeight") {
        var duration = previousAnimation.startTime + previousAnimation.duration - beginAt
        if abs(self.apparentHeight - value) < CGFloat.ulpOfOne {
            duration = 0.0
        }
        
        let animation = ListViewAnimation(from: self.apparentHeight, to: value, duration: duration, curve: listViewAnimationCurveSystem, beginAt: beginAt, update: { [weak self] _, currentValue in
            if let strongSelf = self {
                strongSelf.apparentHeight = currentValue
            }
        })
        
        self.setAnimationForKey("apparentHeight", animation: animation)
    }
}

// remove apparentheight animation
public func removeApparentHeightAnimation() {
    self.setAnimationForKey("apparentHeight", animation: nil)
}

// add transitionoffset animation
public func addTransitionOffsetAnimation(_ value: CGFloat, duration: Double, beginAt: Double) {
    let animation = ListViewAnimation(from: self.transitionOffset, to: value, duration: duration, curve: listViewAnimationCurveSystem, beginAt: beginAt, update: { [weak self] _, currentValue in
        if let strongSelf = self {
            strongSelf.transitionOffset = currentValue
        }
    })
    self.setAnimationForKey("transitionOffset", animation: animation)
}

// animate insertion
open func animateInsertion(_ currentTimestamp: Double, duration: Double, short: Bool) {
}

// animate added
open func animateAdded(_ currentTimestamp: Double, duration: Double) {
}

// animate removed
open func animateRemoved(_ currentTimestamp: Double, duration: Double) {
}

// set highlighted at point
open func setHighlighted(_ highlighted: Bool, at point: CGPoint, animated: Bool) {
}

// selected
open func selected() {
}

// is reorderable
open func isReorderable(at point: CGPoint) -> Bool {
    return false
}

// animate frame transition
open func animateFrameTransition(_ progress: CGFloat, _ currentValue: CGFloat) {
    
}

// should animate horizontal frame transition
open func shouldAnimateHorizontalFrameTransition() -> Bool {
    return false
}

// query header
open func header() -> ListViewItemHeader? {
    return nil
}

// update trailing item space
open func updateTrailingItemSpace(_ height: CGFloat, transition: ContainedViewLayoutTransition) {
}

// accessibility elements became focused
override open func accessibilityElementDidBecomeFocused() {
    (self.supernode as? ListView)?.ensureItemNodeVisible(self, animated: false, overflow: 22.0)
}

// update frame
public func updateFrame(_ frame: CGRect, within containerSize: CGSize) {
    self.frame = frame
    self.updateAbsoluteRect(frame, within: containerSize)
}

// update absolute rect
// for subclasses to override
open func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) {
}

// apply absolute offset
// for subclassses to override
open func applyAbsoluteOffset(value: CGFloat, animationCurve: ContainedViewLayoutTransitionCurve, duration: Double) {
}
This post is licensed under CC BY 4.0 by the author.