https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hiring-french
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
d

Dirk Hoffmann

03/14/2021, 12:01 PM
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

Dominaezzz

03/14/2021, 12:49 PM
Fascinating. Code?
d

Dirk Hoffmann

03/14/2021, 12:57 PM
also copy/paste not working on the middle basic text field. and I wonder why cursor up down is not supported in TextFields??
i

Igor Demin

03/14/2021, 2:35 PM
but transparent over neighbour components??
It is because
TextField
draws after Box/Card:
ADTextWithPopup(...)
TextField(...)
If you want popup always be over the other components, you need to draw it after them:
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

Dirk Hoffmann

03/15/2021, 12:15 PM
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

Igor Demin

03/15/2021, 12:41 PM
I fixed the code. Now it works with the example above:
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() }
        }
    }
}
fun main() = Window {
    DesktopTheme {
        ...
        AppPopups()
    }
}

...
if (popupOffset.value != null && isPopupVisible.value) {
    AppPopup {
        Card...
    }
}
d

Dirk Hoffmann

03/15/2021, 10:41 PM
just for the books: here's my working version (for the time being):
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.