|
| 1 | +package expo.modules.blueskyswissarmy.visibilityview |
| 2 | + |
| 3 | +import android.graphics.Rect |
| 4 | + |
| 5 | +class VisibilityViewManager { |
| 6 | + companion object { |
| 7 | + private val views = HashMap<Int, VisibilityView>() |
| 8 | + private var currentlyActiveView: VisibilityView? = null |
| 9 | + private var prevCount = 0 |
| 10 | + |
| 11 | + fun addView(view: VisibilityView) { |
| 12 | + this.views[view.id] = view |
| 13 | + |
| 14 | + if (this.prevCount == 0) { |
| 15 | + this.updateActiveView() |
| 16 | + } |
| 17 | + this.prevCount = this.views.count() |
| 18 | + } |
| 19 | + |
| 20 | + fun removeView(view: VisibilityView) { |
| 21 | + this.views.remove(view.id) |
| 22 | + this.prevCount = this.views.count() |
| 23 | + } |
| 24 | + |
| 25 | + fun updateActiveView() { |
| 26 | + var activeView: VisibilityView? = null |
| 27 | + val count = this.views.count() |
| 28 | + |
| 29 | + if (count == 1) { |
| 30 | + val view = this.views.values.first() |
| 31 | + if (view.isViewableEnough()) { |
| 32 | + activeView = view |
| 33 | + } |
| 34 | + } else if (count > 1) { |
| 35 | + val views = this.views.values |
| 36 | + var mostVisibleView: VisibilityView? = null |
| 37 | + var mostVisiblePosition: Rect? = null |
| 38 | + |
| 39 | + views.forEach { view -> |
| 40 | + if (!view.isViewableEnough()) { |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + val position = view.getPositionOnScreen() ?: return@forEach |
| 45 | + val topY = position.centerY() - (position.height() / 2) |
| 46 | + |
| 47 | + if (topY >= 150) { |
| 48 | + if (mostVisiblePosition == null) { |
| 49 | + mostVisiblePosition = position |
| 50 | + } |
| 51 | + |
| 52 | + if (position.centerY() <= mostVisiblePosition!!.centerY()) { |
| 53 | + mostVisibleView = view |
| 54 | + mostVisiblePosition = position |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + activeView = mostVisibleView |
| 60 | + } |
| 61 | + |
| 62 | + if (activeView == this.currentlyActiveView) { |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + this.clearActiveView() |
| 67 | + if (activeView != null) { |
| 68 | + this.setActiveView(activeView) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private fun clearActiveView() { |
| 73 | + this.currentlyActiveView?.setIsCurrentlyActive(false) |
| 74 | + this.currentlyActiveView = null |
| 75 | + } |
| 76 | + |
| 77 | + private fun setActiveView(view: VisibilityView) { |
| 78 | + view.setIsCurrentlyActive(true) |
| 79 | + this.currentlyActiveView = view |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments