Skip to content

Commit

Permalink
Use ResizeObserver to react to size changes on JS DOM in `BoxWithCo…
Browse files Browse the repository at this point in the history
…nstraints`

See the added FIXME for the reason why it doesn't work
  • Loading branch information
ShreckYe committed Sep 11, 2024
1 parent 026d258 commit cc2209c
Showing 1 changed file with 38 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.huanshankeji.compose.foundation.ExperimentalFoundationApi
import com.huanshankeji.compose.foundation.layout.Box
import com.huanshankeji.compose.ui.Alignment
import com.huanshankeji.compose.ui.Modifier
import com.varabyte.kobweb.browser.dom.observers.ResizeObserver
import com.varabyte.kobweb.compose.foundation.layout.BoxScope
import com.varabyte.kobweb.compose.ui.attrsModifier

Expand All @@ -19,14 +20,45 @@ actual fun BoxWithConstraints(
) {
var clientSize by remember { mutableStateOf<ClientSize?>(null) }
Box(
Modifier.platformModify {
attrsModifier {
ref {
clientSize = ClientSize(it.clientWidth, it.clientHeight)
onDispose { clientSize = null }
Modifier.fillMaxSizeStretch()
.platformModify {
attrsModifier {
ref {
//clientSize = ClientSize(it.clientWidth, it.clientHeight) // Adding this doesn't make a difference to solve the issue below.
val resizeObserver = ResizeObserver { entries, _ ->
val element = entries.first().target

/*
console.log("width: ${element.clientWidth}, height: ${element.clientHeight}")
console.log(entries.first().contentBoxSize.first())
console.log(entries.first().borderBoxSize.first())
console.log(entries.first().devicePixelContentBoxSize.first())
*/

/* FIXME The height is sometimes 0 when resizing,
a non-zero size (as filtered through below) is not observed in time,
and sometimes a child element doesn't show,
until it's inspected with the Chrome Dev Tools.
I don't know whether this is a browser bug or a bug in our implementation.
Therefore, the 0 size changes are filtered out.
Uncomment the commented `console.log` debug code above to debug this further. */
with(element) {
if (clientWidth != 0 && clientHeight != 0) {
//console.log("width: ${element.clientWidth}, height: ${element.clientHeight}")
clientSize = ClientSize(clientWidth, clientHeight)
}
}
}
resizeObserver.observe(it)

onDispose {
//resizeObserver.unobserve(it)
resizeObserver.disconnect()
clientSize = null
}
}
}
}
}.fillMaxSizeStretch()
.then(modifier),
contentAlignment
) {
Expand Down

0 comments on commit cc2209c

Please sign in to comment.