package com.pixelized.desktop.lwa.utils.extention

import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned


/**
 * is an extension function for Modifier.
 * It allows you to attach visibility detection logic to any composable element
 */
fun Modifier.isElementVisible(onVisibilityChanged: (Boolean) -> Unit): Modifier {
    var isVisible = false
    return this.onGloballyPositioned { layoutCoordinates ->
        val localIsVisible = layoutCoordinates.parentLayoutCoordinates?.let {
            val parentBounds = it.boundsInWindow()
            val childBounds = layoutCoordinates.boundsInWindow()
            parentBounds.overlaps(childBounds)
        } ?: false
        if (isVisible != localIsVisible) {
            isVisible = localIsVisible
            onVisibilityChanged(localIsVisible)
        }
    }
}