Skip to content

Commit cc2209c

Browse files
committed
Use ResizeObserver to react to size changes on JS DOM in BoxWithConstraints
See the added FIXME for the reason why it doesn't work
1 parent 026d258 commit cc2209c

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

compose-multiplatform-common/src/jsMain/kotlin/com/huanshankeji/compose/foundation/layout/ext/BoxWithConstraints.js.kt

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import com.huanshankeji.compose.foundation.ExperimentalFoundationApi
77
import com.huanshankeji.compose.foundation.layout.Box
88
import com.huanshankeji.compose.ui.Alignment
99
import com.huanshankeji.compose.ui.Modifier
10+
import com.varabyte.kobweb.browser.dom.observers.ResizeObserver
1011
import com.varabyte.kobweb.compose.foundation.layout.BoxScope
1112
import com.varabyte.kobweb.compose.ui.attrsModifier
1213

@@ -19,14 +20,45 @@ actual fun BoxWithConstraints(
1920
) {
2021
var clientSize by remember { mutableStateOf<ClientSize?>(null) }
2122
Box(
22-
Modifier.platformModify {
23-
attrsModifier {
24-
ref {
25-
clientSize = ClientSize(it.clientWidth, it.clientHeight)
26-
onDispose { clientSize = null }
23+
Modifier.fillMaxSizeStretch()
24+
.platformModify {
25+
attrsModifier {
26+
ref {
27+
//clientSize = ClientSize(it.clientWidth, it.clientHeight) // Adding this doesn't make a difference to solve the issue below.
28+
val resizeObserver = ResizeObserver { entries, _ ->
29+
val element = entries.first().target
30+
31+
/*
32+
console.log("width: ${element.clientWidth}, height: ${element.clientHeight}")
33+
console.log(entries.first().contentBoxSize.first())
34+
console.log(entries.first().borderBoxSize.first())
35+
console.log(entries.first().devicePixelContentBoxSize.first())
36+
*/
37+
38+
/* FIXME The height is sometimes 0 when resizing,
39+
a non-zero size (as filtered through below) is not observed in time,
40+
and sometimes a child element doesn't show,
41+
until it's inspected with the Chrome Dev Tools.
42+
I don't know whether this is a browser bug or a bug in our implementation.
43+
Therefore, the 0 size changes are filtered out.
44+
Uncomment the commented `console.log` debug code above to debug this further. */
45+
with(element) {
46+
if (clientWidth != 0 && clientHeight != 0) {
47+
//console.log("width: ${element.clientWidth}, height: ${element.clientHeight}")
48+
clientSize = ClientSize(clientWidth, clientHeight)
49+
}
50+
}
51+
}
52+
resizeObserver.observe(it)
53+
54+
onDispose {
55+
//resizeObserver.unobserve(it)
56+
resizeObserver.disconnect()
57+
clientSize = null
58+
}
59+
}
2760
}
2861
}
29-
}.fillMaxSizeStretch()
3062
.then(modifier),
3163
contentAlignment
3264
) {

0 commit comments

Comments
 (0)