Why is it a Box/Card drawn over the boundaries of ...
# compose-desktop
d
Why is it a Box/Card drawn over the boundaries of "its" component is opaque whilst on its component, but transparent over neighbour components??
d
Fascinating. Code?
d
also copy/paste not working on the middle basic text field. and I wonder why cursor up down is not supported in TextFields??
i
but transparent over neighbour components??
It is because
TextField
draws after Box/Card:
Copy code
ADTextWithPopup(...)
TextField(...)
If you want popup always be over the other components, you need to draw it after them:
Copy code
private val popups = mutableSetOf<@Composable () -> Unit>()

fun main() = Window {
    Content()
    for (popup in list) {
        popup()
    }
}

@Composable
fun AppPopup(content: @Composable () -> Unit) {
    val globalPosition by remember { mutableStateOf(Offset.Zero) }
    Box(Modifier.onGloballyPositioned { globalPosition = it.positionInWindow() })
    DisposableEffect(content, globalPosition) {
        val popup = @Composable {
            Box(Modifier.offset { globalPosition.round() }, content = content)
        }
        popups.add(popup)
        onDispose {
            popups.remove(popup)
        }
    }
}
d
I don't get this to work with the computation of the local offset calculated by
textLayoutResult.currentCursorOffset()
above ... how would I achieve that?
i
I fixed the code. Now it works with the example above:
Copy code
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.unit.round

private val popups = mutableStateListOf<Popup>()

@Composable
fun AppPopups() = Box(Modifier.fillMaxSize()) {
    for (popup in popups) {
        popup.Root()
    }
}

@Composable
fun AppPopup(content: @Composable () -> Unit) {
    val popup = remember { Popup(content) }

    Box(Modifier.onGloballyPositioned { popup.position = it.positionInWindow() })

    DisposableEffect(popup) {
        popups.add(popup)
        onDispose {
            popups.remove(popup)
        }
    }
}

private class Popup(
    val content: @Composable () -> Unit
) {
    var position: Offset? by mutableStateOf(null)

    @Composable
    fun Root() {
        if (position != null) {
            Box(Modifier.offset { position!!.round() }) { content() }
        }
    }
}
Copy code
fun main() = Window {
    DesktopTheme {
        ...
        AppPopups()
    }
}

...
if (popupOffset.value != null && isPopupVisible.value) {
    AppPopup {
        Card...
    }
}
d
just for the books: here's my working version (for the time being):
Copy code
import androidx.compose.desktop.DesktopTheme
import androidx.compose.desktop.LocalAppWindow
import androidx.compose.desktop.Window
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.*
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.*
import kotlin.math.roundToInt

object PopupState {
    val isPopupVisible: MutableState<Boolean> = mutableStateOf(false)
}

private val popups = mutableStateListOf<Popup>()
private class Popup(val content: @Composable () -> Unit) {
    var position: Offset? by mutableStateOf(null)
    @Composable
    fun PopupRoot() {
        if (position != null) {
            Box(Modifier.offset { position!!.round() }) {
                content()
            }
        }
    }
}

@Composable
fun GlassPaneComponents() = Box(Modifier.fillMaxSize()) { // glass pane over the whole window
    for (popup in popups) {
        popup.PopupRoot()
    }
}

@Composable
fun AppPopup(content: @Composable () -> Unit) {
    val popup = remember { Popup(content) }
    Box(Modifier.onGloballyPositioned { popup.position = it.positionInWindow() })
    DisposableEffect(popup) {
        popups.add(popup)
        onDispose {
            popups.remove(popup)
        }
    }
}

//fun TextLayoutResult.currentCursorOffset(textFieldValue: TextFieldValue): IntOffset = getCursorRect(
//    textFieldValue.selection.end.coerceAtMost(layoutInput.text.length)
//).bottomLeft.round()
fun TextLayoutResult.currentCursorRect(textFieldValue: TextFieldValue): Rect = getCursorRect(
    textFieldValue.selection.end.coerceAtMost(layoutInput.text.length)
)



fun main() = Window(size = IntSize(800, 600)) {

    DesktopTheme {
        var topText by remember { mutableStateOf("TopText") }
        var leftText by remember { mutableStateOf("LeftText") }
        var rightText by remember { mutableStateOf("RightText") }
        var bottomText by remember { mutableStateOf("bottomText") }
        Column {
            TextField(value = topText, onValueChange = { topText = it }, Modifier.fillMaxWidth().height(50.dp), label = { Text(topText) })
            Row(Modifier.weight(1f)) {
                TextField(value = leftText, onValueChange = { leftText = it }, Modifier.fillMaxHeight().width(100.dp), label = { Text(leftText) })

                ADTextWithPopup(PopupState.isPopupVisible, Modifier.weight(1f))

                TextField(value = rightText, onValueChange = { rightText = it }, Modifier.fillMaxHeight().width(100.dp), label = { Text(rightText) })
            }
            TextField(value = bottomText, onValueChange = { bottomText = it }, Modifier.fillMaxWidth().height(50.dp), label = { Text(bottomText) })
        }
        GlassPaneComponents()
    }
}

@Composable
fun ADTextWithPopup(isPopupVisible: MutableState<Boolean>, modifier: Modifier = Modifier) {
    var floatingPopup: Boolean              by remember { mutableStateOf(true) } // true -> Popup floats with cursor movement, false -> Popup stays where it first appeared
    var textFieldValue: TextFieldValue      by remember { mutableStateOf(TextFieldValue("This is just repeated blind text.. PRESS CTRL+Space for popup below cursor!!! ".repeat(12))) }
    var textLayoutResult: TextLayoutResult? by remember { mutableStateOf(null) }
    var position: Offset?                   by remember { mutableStateOf(null) }
    val cursorRect: State<Rect?> = if (floatingPopup) {
        remember { derivedStateOf { if(isPopupVisible.value) { textLayoutResult?.currentCursorRect(textFieldValue) } else null } }
    } else {
        remember { mutableStateOf(textLayoutResult?.currentCursorRect(textFieldValue)) }
    }

    BoxWithConstraints(modifier.fillMaxSize()) { //BoxWithConstraints(modifier.weight(1f)) {
        val parentWidth = with(LocalDensity.current) { constraints.maxWidth.toDp() }
        val parentHeight = with(LocalDensity.current) { constraints.maxHeight.toDp() }

        SelectionContainer {
            BasicTextField(
                textFieldValue,
                onValueChange = { textFieldValue = it },
                modifier = Modifier.fillMaxSize()
                    .onGloballyPositioned { position = it.positionInWindow() }
                    .onPreviewKeyEvent {
                        if ((it.key == Key.Spacebar || it.utf16CodePoint == ' '.toInt()) && it.isCtrlPressed) {
                            if (it.type == KeyEventType.KeyDown) {
                                isPopupVisible.value = true
                                if (!floatingPopup) {
                                    (cursorRect as MutableState<Rect?>).value =  textLayoutResult?.currentCursorRect(textFieldValue)
                                }
                            }
                            true
                        } else {
                            if ((it.type != KeyEventType.KeyUp) && (it.nativeKeyEvent.keyCode != NativeKeyEvent.VK_CONTROL)) {
                                if (it.nativeKeyEvent.keyCode == NativeKeyEvent.VK_ESCAPE) {
                                    isPopupVisible.value = false
                                    true
                                } else if (isPopupVisible.value && (it.key == Key.Enter) || (it.key == Key.Tab)) {
                                    isPopupVisible.value = false
                                    true
                                } else {
                                    false
                                }
                            } else {
                                false
                            }
                        }
                    },
                onTextLayout = {
                    textLayoutResult = it
                }
            )
        }
        if (isPopupVisible.value && cursorRect.value != null) {
            AppPopup {
                val width = 250.dp
                val height = 140.dp

                val wWindow = LocalAppWindow.current.width
                val hWindow = LocalAppWindow.current.height
                val density = LocalDensity.current.density
                //Card(Modifier.offset { popupOffset.value ?: IntOffset.Zero }.requiredSize(width, height)) {
                Card(Modifier.offset {
                    // coerce x offset of popup so that popup always stays completely inside the LocalAppWindow
                    if ( (cursorRect.value?.bottomLeft?.round()?.y ?: 0) < (hWindow.times(density).roundToInt()) - (height.value.times(density).roundToInt()) - (position?.y?.roundToInt() ?: 0) - 48 ) {
                        // popup under cursor rect
                        IntOffset(
                            x = (cursorRect.value?.bottomLeft?.round()?.x?.coerceAtMost((wWindow.times(density).roundToInt()) - (width.value.times(density).roundToInt()) - (position?.x?.roundToInt() ?: 0)) ?: 0),
                            y = (cursorRect.value?.bottomLeft?.round()?.y?.coerceAtMost((hWindow.times(density).roundToInt()) - (height.value.times(density).roundToInt()) - (position?.y?.roundToInt() ?: 0) - 48) ?: 0)
                        )
                    } else {
                        // popup above cursor rect
                        IntOffset(
                            x = (cursorRect.value?.bottomLeft?.round()?.x?.coerceAtMost((wWindow.times(density).roundToInt()) - (width.value.times(density).roundToInt()) - (position?.x?.roundToInt() ?: 0)) ?: 0),
                            y = (cursorRect.value?.topLeft?.round()?.y?.minus(height.value.times(density).roundToInt()) ?: 0)
                        )
                    }}
                    .requiredSize(width, height)
                ) {
                    Column(Modifier.background(Color.Red).padding(2.dp)) {
                        Text("LocalDensity: ${LocalDensity.current.density}")
                        Text("window w x h: ${LocalAppWindow.current.width} x ${LocalAppWindow.current.height}")
                        Text("position x,y: ${position}")
                        Text("offset   x,y: ${cursorRect.value}")
                        Text("width   (dp): ${width.value} (${width.value * density})")
                        Spacer(Modifier.weight(1f))
                        Row(
                            Modifier.border(1.dp, Color.DarkGray).requiredHeight(25.dp)
                                .background(Color.LightGray), verticalAlignment = Alignment.CenterVertically
                        ) {
                            Spacer(Modifier.weight(1f))
                            Text("floatingWithCursor", Modifier.padding(2.dp), color = Color.DarkGray)
                            Checkbox(floatingPopup, onCheckedChange = { floatingPopup = !floatingPopup })
                        }
                    }
                }
            }
        }
    }
}
Popup can move/float with the cursor, or stays where it first appeared (on Ctrl-Space). Popup makes sure it stays inside the LocalAppWindow with its full width. If not enough space left below the cursor, Popup will be displayed above the cursor.