|
| 1 | +package org.openinsectid.app.ui.components |
| 2 | + |
| 3 | +import androidx.compose.foundation.layout.Box |
| 4 | +import androidx.compose.foundation.layout.fillMaxWidth |
| 5 | +import androidx.compose.foundation.layout.height |
| 6 | +import androidx.compose.material3.CircularProgressIndicator |
| 7 | +import androidx.compose.material3.MaterialTheme |
| 8 | +import androidx.compose.material3.Text |
| 9 | +import androidx.compose.runtime.Composable |
| 10 | +import androidx.compose.runtime.LaunchedEffect |
| 11 | +import androidx.compose.runtime.getValue |
| 12 | +import androidx.compose.runtime.mutableStateOf |
| 13 | +import androidx.compose.runtime.remember |
| 14 | +import androidx.compose.runtime.rememberCoroutineScope |
| 15 | +import androidx.compose.runtime.setValue |
| 16 | +import androidx.compose.ui.Alignment |
| 17 | +import androidx.compose.ui.Modifier |
| 18 | +import androidx.compose.ui.unit.dp |
| 19 | +import kotlinx.coroutines.Dispatchers |
| 20 | +import kotlinx.coroutines.withContext |
| 21 | +import org.openinsectid.app.data.DdgImage |
| 22 | +import org.openinsectid.app.data.ImageSearchState |
| 23 | +import org.openinsectid.app.data.searchDuckDuckGoImages |
| 24 | + |
| 25 | +@Composable |
| 26 | +fun DuckDuckGoImageSearch( |
| 27 | + query: String, |
| 28 | + onImageSelected: (DdgImage) -> Unit |
| 29 | +) { |
| 30 | + var state by remember { mutableStateOf<ImageSearchState>(ImageSearchState.Idle) } |
| 31 | + val scope = rememberCoroutineScope() |
| 32 | + |
| 33 | + LaunchedEffect(query) { |
| 34 | + if (query.isBlank()) return@LaunchedEffect |
| 35 | + |
| 36 | + state = ImageSearchState.Loading |
| 37 | + |
| 38 | + try { |
| 39 | + val images = withContext(Dispatchers.IO) { |
| 40 | + searchDuckDuckGoImages(query) |
| 41 | + } |
| 42 | + state = ImageSearchState.Success(images) |
| 43 | + } catch (e: Exception) { |
| 44 | + state = ImageSearchState.Error("No internet connection") |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + when (state) { |
| 49 | + ImageSearchState.Idle -> Unit |
| 50 | + |
| 51 | + ImageSearchState.Loading -> { |
| 52 | + Box( |
| 53 | + modifier = Modifier |
| 54 | + .fillMaxWidth() |
| 55 | + .height(200.dp), |
| 56 | + contentAlignment = Alignment.Center |
| 57 | + ) { |
| 58 | + CircularProgressIndicator() |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + is ImageSearchState.Error -> { |
| 63 | + Text( |
| 64 | + text = (state as ImageSearchState.Error).message, |
| 65 | + color = MaterialTheme.colorScheme.error |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + is ImageSearchState.Success -> { |
| 70 | + val images = (state as ImageSearchState.Success).images |
| 71 | + if (images.isEmpty()) { |
| 72 | + Text("No images found") |
| 73 | + } else { |
| 74 | + ImageResultsGrid(images, onImageSelected) |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments