Can I use optional parameter in path in Jetpack Compose Navigaiton? - kotlin

I have this navigation graph
fun NavGraphBuilder.manageAvailabilityGraph() {
composable(
"availability/{id}",
arguments = listOf(
navArgument("id") {
type = NavType.StringType
nullable = true
},
),
) {
ManageAvailabilityScreen()
}
}
I thought I can use it for both
navHostController.navigate("availability")
navHostController.navigate("availability/123")
But first one does not work, I get
java.lang.IllegalArgumentException: Navigation destination that matches request NavDeepLinkRequest{ uri=android-app://androidx.navigation/availability } cannot be found in the navigation graph NavGraph(0x0) startDestination={Destination(0xcfbbf7da) route=home}
I fixed it by providing two different routes.
fun NavGraphBuilder.manageAvailabilityGraph() {
composable(
"availability",
) {
ManageAvailabilityScreen()
}
composable(
"availability/{id}",
arguments = listOf(
navArgument("id") {
type = NavType.StringType
nullable = true
},
),
) {
ManageAvailabilityScreen()
}
}
However, I want to know is if it is possible to combine both and just have one route with name "availability", so I don't need to repeat "availability"? And eseentially, both use the same screen.
I tried something like this but does not work.
fun NavGraphBuilder.manageAvailabilityGraph() {
composable(
"availability",
) {
ManageAvailabilityScreen()
navigation(startDestination = "{id}", "{id}") {
composable(
"{id}",
arguments = listOf(
navArgument("id") {
type = NavType.StringType
},
),
) {
ManageAvailabilityScreen()
}
}
}
}

You can mark id as the optional parameter in the route. Refer Documentation
fun NavGraphBuilder.manageAvailabilityGraph() {
composable(
"availability?id={id}",
arguments = listOf(
navArgument("id") {
type = NavType.StringType
nullable = true
},
),
) {
ManageAvailabilityScreen()
}
}
While navigating you can use,
navHostController.navigate("availability")
navHostController.navigate("availability?id=123")

Related

Problem with custom dialog show in jetpack compose. Not correct background

I'm created custom dialog from common class in ini
init {
activity.setContent {
CustomDialog(viewModel)
}
}
#Composable
fun CustomDialog(viewModel: ViewModel){
Dialog(
onDismissRequest = { },
properties = DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true)
) {
}
}
But under dialog background is an empty activity, but must be a preference activity.
Not correct composable:
correct dialog via XML:
I tried, but didn't help
Surface(modifier = Modifier.background(Color.Transparent)) {
CustomDialog(viewModel)
}
```
Exampe:
Dialog(onDismissRequest = { onDismissRequest() }, properties = DialogProperties()) {
Column(
modifier = Modifier
.wrapContentSize()
.background(
color = MaterialTheme.colors.surface,
shape = RoundedCornerShape(size = 16.dp)
).clip(shape = RoundedCornerShape(size = 16.dp))
) {
//.....
}
}
Found solution:
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog?.window?.setDimAmount(0.0f)

Adding dynamic maps in DynamoDB with Kotlin

I'm using Spring Boot, Kotlin and CrudRepository to add items to my Dynamo Table.
The map I'm trying to add is dynamic, and can change attributes every single time.
I add the date of the object (delta) and save it, but I am having several errors:
When I save:
#DynamoDBTable(tableName = "delta_computers_inventory")
class DeltaComputersInventory(
#DynamoDBHashKey
#DynamoDBAttribute(attributeName = "delta_computers_inventory_id")
var id: String = UUID.randomUUID().toString(),
#DynamoDBTyped(DynamoDBMapperFieldModel.DynamoDBAttributeType.M)
#DynamoDBAttribute(attributeName = "delta")
var delta: Map<String, Any?> = mapOf(),
) {
#DynamoDBAttribute(attributeName = "date")
var date: String = OffsetDateTime.now(ZoneOffset.UTC).format(
DateTimeFormatter.ISO_DATE_TIME
)
}
and I do:
.doOnSuccess { listOfDocuments ->
deltaComputersRepository.saveAll(
listOfDocuments.map {
DeltaComputersInventory(
delta = it,
)
}
)
}
I get:
reactor.core.Exceptions$ErrorCallbackNotImplemented: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: not supported; requires #DynamoDBTyped or #DynamoDBTypeConverted
instead, if I do it through an Item (Item.fromMap(it))
#DynamoDBTable(tableName = "delta_computers_inventory")
class DeltaComputersInventory(
#DynamoDBHashKey
#DynamoDBAttribute(attributeName = "delta_computers_inventory_id")
var id: String = UUID.randomUUID().toString(),
#DynamoDBTyped(DynamoDBMapperFieldModel.DynamoDBAttributeType.M)
#DynamoDBAttribute(attributeName = "delta")
var delta: Item = Item(),
) {
#DynamoDBAttribute(attributeName = "date")
var date: String = OffsetDateTime.now(ZoneOffset.UTC).format(
DateTimeFormatter.ISO_DATE_TIME
)
}
I get no error, but my item in my DynamoDB shows empty:
{
"delta_computers_inventory_id": {
"S": "d389d63e-8e93-4b08-b576-e37fae9a4d58"
},
"date": {
"S": "2023-01-24T12:00:33.620015Z"
},
"delta": {
"M": {}
},
}
What am I doing wrong?

How to refresh UI in Kotlin with Compose desktop when runBlocking?

I'm learning Kotlin and Compose Desktop and I'm trying refresh the UI before fetch data from an API.
But the request is running inside a runBlocking, thus the UI freezes until request is completed.
This is my code, everything works.
val client = HttpClient(CIO)
#OptIn(ExperimentalComposeUiApi::class)
#Composable
#Preview
fun App() {
var text by remember { mutableStateOf("Test button") }
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
modifier = Modifier.padding(50.dp)
) {
Button(
onClick = {
text = "Wait..."//How to refresh UI to display this text?
runBlocking {
delay(5000)//blocking test
val response: HttpResponse = client.request("https://myapi.com/") {
// Configure request parameters exposed by HttpRequestBuilder
}
if (response.status == HttpStatusCode.OK) {
val body = response.body<String>()
println(body)
} else {
println("Error has occurred")
}
}
text = "Test button"
},
modifier = Modifier.fillMaxWidth()
) {
Text(text)
}
OutlinedTextField(
value = "",
singleLine = true,
onValueChange = { text = it }
)
}
}
}
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
state = WindowState(size = DpSize(350.dp, 500.dp)),
title = "Compose test"
) {
App()
}
}
How to achieve that?
The problem here is that you are using runBlocking at all.
The most straightforward solution for your case would be to replace your runBlocking {} with a coroutine scope. At the top of your App() function, create your scope: val scope = rememberCoroutineScope(), then instead of runBlocking you can say scope.launch {}.
New code would be:
#OptIn(ExperimentalComposeUiApi::class)
#Composable
#Preview
fun App() {
var text by remember { mutableStateOf("Test button") }
val scope = rememberCoroutineScope()
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
modifier = Modifier.padding(50.dp)
) {
Button(
onClick = {
text = "Wait..."//How to refresh UI to display this text?
scope.launch {
delay(5000)//blocking test
val response: HttpResponse = client.request("https://myapi.com/") {
// Configure request parameters exposed by HttpRequestBuilder
}
if (response.status == HttpStatusCode.OK) {
val body = response.body<String>()
println(body)
} else {
println("Error has occurred")
}
}
text = "Test button"
},
modifier = Modifier.fillMaxWidth()
) {
Text(text)
}
OutlinedTextField(
value = "",
singleLine = true,
onValueChange = { text = it }
)
}
}
}
I saw one comment say to use LaunchedEffect() but this won't work in your case since you can't use that in an onClick since it's not a Composable.

Multiple different pointerInput

I'm currently trying to implement the option of switching between a composable being either zoomable, pannable (dragging the surface) or neither of those. What works so far is toggling the respective buttons, with the expected result. What does not work is toggling one button from the other - this gives the unexpected result of keeping the functionality of the first button.
For example, let's say zoom is active. When I then press the pan button, the background highlighting changes accordingly, all test-logs show the expected state - but the surface is still zoomable, NOT draggable. I first have to manually disable zoom. Any ideas as to why this might happen?
Modifier.run {
if (zoomEnabled) {
this.pointerInput(Unit) {
detectTransformGestures { _, _, zoom, _ ->
passScale(zoom)
}
}
} else if (panEnabled) {
this.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consumeAllChanges()
passOffsetX(dragAmount.x / 3)
passOffsetY(dragAmount.y / 3)
}
}
} else
this
}
Buttons:
#Composable
fun TopBarAction(
zoomEnabled: Boolean,
passZoomEnabled: (Boolean) -> Unit,
panEnabled: Boolean,
passPanEnabled: (Boolean) -> Unit
) {
IconToggleButton(
checked = zoomEnabled,
onCheckedChange = {
passPanEnabled(false)
passZoomEnabled(it)
},
modifier = Modifier
.background(
if (zoomEnabled) Color.LightGray else Color.Transparent,
shape = CircleShape
),
enabled = true
) {
Icon(...)
}
IconToggleButton(
checked = panEnabled,
onCheckedChange = {
passZoomEnabled(false)
passPanEnabled(it)
},
modifier = Modifier
.background(
if (panEnabled) Color.LightGray else Color.Transparent,
shape = CircleShape
),
enabled = true
) {
Icon(...)
}
}
Using the normal .pointerInput modifier with the condition inside instead of run does not recognize any input at all and detectTransformGesture's pan did not behave the way I need it to (though this is probably what I will use if all else fails)
First issue is PointerInput creates a closure with key or keys and uses old values unless the keys you set change.
You need to set keys accordingly.
Second issue is even if you set keys, detectDragGestures or detectTransformGestures will consume events so PointerInputChange above won't get it if first one has already consumed event.
What consume() or consumeAllChanges() does is it prevents pointerInput above it or on parent to receive events by returning PointeInputChange.positionChange() Offset.Zero, PointerInputChange.isConsumed true. Since drag, scroll or transform gestures check if PointeInputChange.isConsumed is true they will never get any event if you consume them in previous pointerInput.
Drag source code for instance
suspend fun PointerInputScope.detectDragGestures(
onDragStart: (Offset) -> Unit = { },
onDragEnd: () -> Unit = { },
onDragCancel: () -> Unit = { },
onDrag: (change: PointerInputChange, dragAmount: Offset) -> Unit
) {
forEachGesture {
awaitPointerEventScope {
val down = awaitFirstDown(requireUnconsumed = false)
var drag: PointerInputChange?
var overSlop = Offset.Zero
do {
drag = awaitPointerSlopOrCancellation(
down.id,
down.type
) { change, over ->
change.consume()
overSlop = over
}
// ! EVERY Default GESTURE HAS THIS CHECK
} while (drag != null && !drag.isConsumed)
if (drag != null) {
onDragStart.invoke(drag.position)
onDrag(drag, overSlop)
if (
!drag(drag.id) {
onDrag(it, it.positionChange())
it.consume()
}
) {
onDragCancel()
} else {
onDragEnd()
}
}
}
}
}
Instead of using Modifier.run you can chain Modifier.pointerInput()
Modifier
.pointerInput(keys){
// Gesture scope1
if(zoomEnabled){...}
}
.pointerInput(keys){
// Gesture scope2
if(panEnabled){
....
}
}
Events first go to gesture scope 2 then gesture scope 1
Created a small sample that you can observer how gestures change and propagate and how they reset with keys
#Composable
private fun MyComposable() {
var zoomEnabled by remember { mutableStateOf(false) }
var dragEnabled by remember { mutableStateOf(false) }
var text by remember { mutableStateOf("") }
Column() {
val modifier = Modifier
.size(400.dp)
.background(Color.Red)
.pointerInput(zoomEnabled) {
if (zoomEnabled) {
detectTransformGestures { centroid, pan, zoom, rotation ->
println("ZOOOMING")
text = "ZOOMING centroid: $centroid"
}
}
}
.pointerInput(key1 = dragEnabled, key2= zoomEnabled) {
if (dragEnabled && !zoomEnabled) {
detectDragGestures { change, dragAmount ->
println("DRAGGING")
text = "DRAGGING $dragAmount"
}
}
}
Box(modifier = modifier)
Text(text = text)
OutlinedButton(onClick = { zoomEnabled = !zoomEnabled }) {
Text("zoomEnabled: $zoomEnabled")
}
OutlinedButton(onClick = { dragEnabled = !dragEnabled }) {
Text("dragEnabled: $dragEnabled")
}
}
}
You can create your own behavior using the answer and snippet above.

How to test onDismissRequest attribute of AlertDialog?

In its simplest form I have this dialog:
#Composable
fun MyDialog(
showDialogState: MutableState<Boolean>
) {
if (showDialogState.value) {
AlertDialog(onDismissRequest = { showDialogState.value = false },
// Other irrelevant attributes have been omitted
)
}
}
How can I trigger "onDismissRequest" on this composable in Robolectric?
This is usually how I build my composable tests by the way:
#Config(sdk = [Build.VERSION_CODES.O_MR1])
#RunWith(AndroidJUnit4::class)
#LooperMode(LooperMode.Mode.PAUSED)
class MyDialogTest {
#get:Rule
val composeTestRule = createComposeRule()
#Test
fun `MyDialog - when showing state and dismissed - changes showing state`() {
val state = mutableStateOf(true)
composeTestRule.setContent {
MyDialog(
showDialogState = state
)
}
// TODO: How do I trigger dismiss!?
assertFalse(state.value)
}
}
Compose version: 1.1.0-rc01
Android Gradle Plugin version: 7.0.4
Robolectric version: 4.7.3
I don't think this is possible at the moment. I have written this test to confirm:
val onButtonPressed = mock<() -> Unit>()
composeTestRule.setContent {
Scaffold(topBar = {
TopAppBar {
Text(text = "This test does not work")
}
}) {
AlertDialog(
onDismissRequest = {},
properties = DialogProperties(
dismissOnBackPress = true,
dismissOnClickOutside = true
),
title = { Text(text = "This is a dialog")},
confirmButton = { Button(onClick = {}) {
Text(text = "Confirm")
}}
)
Column(modifier = Modifier.fillMaxSize()) {
Spacer(modifier = Modifier.weight(1f))
Button(onClick = onButtonPressed) {
Text(text = "test")
}
}
}
}
composeTestRule.onNode(isDialog()).assertExists()
composeTestRule.onNodeWithText("test", ignoreCase = true).performClick()
verify(onButtonPressed).invoke()
composeTestRule.onNode(isDialog()).assertDoesNotExist()
Even though the button is "behind" the dialog, it receives click events without dismissing the dialog.
Manual testing has confirmed that the implementation works, so perhaps a UIAutomator test could automate this, but that seems like an overly complicated way of solving this issue.
I quote the official documentation:
Dismiss the dialog when the user clicks outside the dialog or on the
back button. If you want to disable that functionality, simply use an
empty onCloseRequest.
https://foso.github.io/Jetpack-Compose-Playground/material/alertdialog/