path
stringlengths
4
242
contentHash
stringlengths
1
10
content
stringlengths
0
3.9M
AndroidSonarCloudIntegration/app/src/main/java/com/example/myapplication/ui/gallery/GalleryViewModel.kt
459445287
package com.example.myapplication.ui.gallery import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class GalleryViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is gallery Fragment" } val text: LiveData<String> = _text }
AndroidSonarCloudIntegration/app/src/main/java/com/example/myapplication/ui/gallery/GalleryFragment.kt
39613274
package com.example.myapplication.ui.gallery import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.myapplication.databinding.FragmentGalleryBinding class GalleryFragment : Fragment() { private var _binding: FragmentGalleryBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val galleryViewModel = ViewModelProvider(this).get(GalleryViewModel::class.java) _binding = FragmentGalleryBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textGallery galleryViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
AndroidSonarCloudIntegration/app/src/main/java/com/example/myapplication/ui/slideshow/SlideshowViewModel.kt
1159846286
package com.example.myapplication.ui.slideshow import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SlideshowViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is slideshow Fragment" } val text: LiveData<String> = _text }
AndroidSonarCloudIntegration/app/src/main/java/com/example/myapplication/ui/slideshow/SlideshowFragment.kt
1988086251
package com.example.myapplication.ui.slideshow import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.myapplication.databinding.FragmentSlideshowBinding class SlideshowFragment : Fragment() { private var _binding: FragmentSlideshowBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val slideshowViewModel = ViewModelProvider(this).get(SlideshowViewModel::class.java) _binding = FragmentSlideshowBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textSlideshow slideshowViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
AndroidSonarCloudIntegration/app/src/main/java/com/example/myapplication/MainActivity.kt
3516094249
package com.example.myapplication import android.os.Bundle import android.view.Menu import com.google.android.material.snackbar.Snackbar import com.google.android.material.navigation.NavigationView import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.AppCompatActivity import com.example.myapplication.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.appBarMain.toolbar) binding.appBarMain.fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = binding.drawerLayout val navView: NavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_content_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow ), drawerLayout ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
kotinassessment/src/test/kotlin/NumberConversionTest.kt
1261146230
import junit.framework.Assert.assertEquals import org.junit.Test class NumberConversionTest { @Test fun convertNumberToRomainInvaldConversion() { val converter = IntegerToRoman() val testCases = mapOf( 100 to "C", 50 to "X", ) for ((input, expected) in testCases) { val actual = converter.intToRomanNumber(input) assertEquals("Conversion for input: $input", expected, actual) } } @Test fun convertNumberToRomainTest2ValidConversion() { val converter = IntegerToRoman() val testCases = mapOf( 100 to "C", 50 to "L", ) for ((input, expected) in testCases) { val actual = converter.intToRomanNumber(input) assertEquals("Conversion for input: $input", expected, actual) } } @Test fun convertNumberToRomain3000Fail() { val converter = IntegerToRoman() val testCases = mapOf( 3000 to "M" ) for ((input, expected) in testCases) { val actual = converter.intToRomanNumber(input) assertEquals("Conversion for input: $input", expected, actual) } } @Test fun convertNumberToRomain3000Pass() { val converter = IntegerToRoman() val testCases = mapOf( 3000 to "MMM" ) for ((input, expected) in testCases) { val actual = converter.intToRomanNumber(input) assertEquals("Conversion for input: $input", expected, actual) } } @Test fun convertRomainToNumber() { val converter = IntegerToRoman() val inputs = arrayOf("III", "IV", "IX", "LVII", "MMM") val expectedOutputs = intArrayOf(3, 4, 9, 58, 3000) for (i in inputs.indices) { val result = converter.romanToInt(inputs[i]) println("Input: ${inputs[i]}, Expected: ${expectedOutputs[i]}, Result: $result") if (result == expectedOutputs[i]) { println("Test case ${i + 1} PASSED") } else { println("Test case ${i + 1} FAILED") } println("--------------------------------------") } } }
kotinassessment/src/main/kotlin/numberconversation.kt
1221487524
class IntegerToRoman { fun main() { println(" intToRomanNumber ${intToRomanNumber(99)}") } fun intToRomanNumber(num: Int): String { var result: String = ""; // values in map to be given in descending order ( else it will return result from the lower roman literal) val intToRomanMap = listOf( 1000 to "M",900 to "CM" ,500 to "D", 400 to "CD", 100 to "C", 90 to "XC", 50 to "L", 40 to "XL", 10 to "X", 9 to "IX", 5 to "V", 4 to "IV", 1 to "I" ) var numTemp = num for ((value, romannumber) in intToRomanMap) { while (numTemp >= value) { result += romannumber numTemp -= value; } } return result; } fun romanToInt(s: String): Int { var ans = 0 var num = 0 for (i in s.length - 1 downTo 0) { when (s[i]) { 'I' -> num = 1 'V' -> num = 5 'X' -> num = 10 'L' -> num = 50 'C' -> num = 100 'D' -> num = 500 'M' -> num = 1000 } if (4 * num < ans) ans -= num else ans += num } return ans } }
RecipeAppUsingRestAPI/app/src/androidTest/java/com/example/recipeappusingapi/ExampleInstrumentedTest.kt
954752144
package com.example.recipeappusingapi import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.recipeappusingapi", appContext.packageName) } }
RecipeAppUsingRestAPI/app/src/test/java/com/example/recipeappusingapi/ExampleUnitTest.kt
3081470304
package com.example.recipeappusingapi import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/ui/theme/Color.kt
2774586898
package com.example.recipeappusingapi.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/ui/theme/Theme.kt
926297235
package com.example.recipeappusingapi.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun RecipeAppUsingAPITheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/ui/theme/Type.kt
1138670924
package com.example.recipeappusingapi.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/viewModels/MainViewModel.kt
2727399524
package com.example.recipeappusingapi.viewModels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.recipeappusingapi.models.RecipeList import com.example.recipeappusingapi.repository.RecipeRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MainViewModel(private val repository: RecipeRepository) : ViewModel() { private val _recipes = MutableLiveData<RecipeList>() val recipes: LiveData<RecipeList> get() = _recipes init { loadRecipes() } private fun loadRecipes() { viewModelScope.launch(Dispatchers.IO) { val result = repository.getRecipe() _recipes.postValue(result) } } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/viewModels/MainViewModelFactory.kt
2263915081
package com.example.recipeappusingapi.viewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.recipeappusingapi.repository.RecipeRepository class MainViewModelFactory(private val repository: RecipeRepository): ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return MainViewModel(repository) as T } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/repository/RecipeRepository.kt
3424221278
package com.example.recipeappusingapi.repository import com.example.recipeappusingapi.api.RecipeService import com.example.recipeappusingapi.models.RecipeList class RecipeRepository(private val recipeService: RecipeService) { suspend fun getRecipe(): RecipeList { val result = recipeService.getRecipes() return result.body()!! } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/MainActivity.kt
2133219465
package com.example.recipeappusingapi import HomeScreen import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavController import com.example.recipeappusingapi.api.RecipeService import com.example.recipeappusingapi.api.RetrofitHelper import com.example.recipeappusingapi.repository.RecipeRepository import com.example.recipeappusingapi.ui.theme.RecipeAppUsingAPITheme import com.example.recipeappusingapi.utils.AppNavigation import com.example.recipeappusingapi.viewModels.MainViewModel import com.example.recipeappusingapi.viewModels.MainViewModelFactory class MainActivity : ComponentActivity() { private lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val recipeService = RetrofitHelper.getInstance().create(RecipeService::class.java) val repository = RecipeRepository(recipeService) mainViewModel = ViewModelProvider(this, MainViewModelFactory(repository))[MainViewModel::class.java] setContent { RecipeAppUsingAPITheme { AppNavigation(mainViewModel = mainViewModel) // HorizontalPagerExample() } } } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/utils/AppNavigation.kt
2046176386
package com.example.recipeappusingapi.utils import HomeScreen import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.recipeappusingapi.viewModels.MainViewModel @Composable fun AppNavigation(mainViewModel: MainViewModel) { val navController = rememberNavController() NavHost(navController, startDestination = "homeScreen"){ composable("homeScreen"){ HomeScreen(mainViewModel, navController) } composable("detailScreen/{recipeId}"){backStackEntry-> val recipeId = backStackEntry.arguments?.getString("recipeId") val singleRecipe = mainViewModel.recipes.value?.recipes?.find { it.id.toString() == recipeId } singleRecipe?.let { DetailScreen(navController, singleRecipe, mainViewModel) } } } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/utils/HomeScreen.kt
3006576513
import android.content.ContentValues.TAG import android.graphics.fonts.FontStyle import android.service.autofill.OnClickAction import android.util.Log import android.view.View.OnClickListener import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight.Companion.Bold import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import coil.compose.AsyncImage import coil.compose.AsyncImagePainter import coil.compose.rememberAsyncImagePainter import coil.compose.rememberImagePainter import com.example.recipeappusingapi.models.Recipe import com.example.recipeappusingapi.models.SingleRecipe import com.example.recipeappusingapi.viewModels.MainViewModel @Composable fun HomeScreen( viewModel: MainViewModel, navController: NavController ) { val recipesState by viewModel.recipes.observeAsState() Box(modifier = Modifier .padding(15.dp) .fillMaxSize()) { LazyColumn { items(recipesState?.recipes.orEmpty()) { recipe -> Card( modifier = Modifier .padding(top = 18.dp) .padding(horizontal = 8.dp), colors = CardDefaults.cardColors( containerColor = Color(0xFFFF004A) ), shape = RoundedCornerShape(8.dp) ) { val imageModel = recipe.image Box(modifier = Modifier.fillMaxSize()) { AsyncImage( model = imageModel, alpha = 0.95f, contentDescription = null, modifier = Modifier .fillMaxSize() .clickable { val singleRecipe = SingleRecipe( id = recipe.id, image = recipe.image, instructions = recipe.instructions, ingredients = recipe.ingredients, name = recipe.name ) navController.navigate("detailScreen/${singleRecipe.id}") { launchSingleTop = true } } ) Box( modifier = Modifier .fillMaxSize() .align(Alignment.BottomStart) .background( brush = Brush.verticalGradient( colors = listOf(Color.Transparent, Color.Black), startY = 200f, endY = 1200f // Adjust as needed for the gradient length ) ) ) Text( text = recipe.name, color = Color.White, modifier = Modifier .align(Alignment.BottomStart) .padding(start = 16.dp, bottom = 8.dp), // Adjust as needed for the text position fontSize = 25.sp, fontWeight = Bold ) } } } } } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/utils/detailScreen.kt
2337859696
package com.example.recipeappusingapi.utils import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight.Companion.Bold import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import coil.compose.AsyncImage import com.example.recipeappusingapi.models.Recipe import com.example.recipeappusingapi.viewModels.MainViewModel @Composable fun DetailScreen( navController: NavHostController, singleRecipe: Recipe?, viewModel: MainViewModel ) { val recipeState by viewModel.recipes.observeAsState() var colorState by remember { mutableStateOf(false) } val recipeList by remember { mutableStateOf(recipeState?.recipes ?: emptyList()) } Box(modifier = Modifier.fillMaxSize()) { Column { // Image with gradient overlay Box( modifier = Modifier .fillMaxWidth() .weight(3f), contentAlignment = Alignment.TopCenter ) { AsyncImage( model = singleRecipe!!.image, // Assuming there's a field for image URL in your Recipe model contentDescription = "image detail", modifier = Modifier .fillMaxSize(), contentScale = ContentScale.Crop // Adjust content scale as needed ) Box( modifier = Modifier .fillMaxSize() .background( brush = Brush.verticalGradient( colors = listOf(Color.Transparent, Color.White), startY = 200f, endY = 1200f // Adjust as needed for the gradient length ) ) ) Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxSize() .padding(top = 16.dp) .padding(horizontal = 6.dp) ) { Box( modifier = Modifier .padding(5.dp) .size(40.dp) .background(Color(0xFFFA1457), shape = CircleShape) .clickable { navController.navigate("homeScreen") } ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "back move", modifier = Modifier.align(Alignment.Center), tint = Color.White ) } Box( modifier = Modifier .size(50.dp) .padding(5.dp) .background(color = if (colorState) Color(0xFFFA1457) else Color.Black, shape = CircleShape) .clickable { colorState = !colorState } ) { Icon( imageVector = Icons.Default.FavoriteBorder, contentDescription = "favorite", modifier = Modifier.align(Alignment.Center).background(if (colorState) Color(0xFFFA1457) else Color.Transparent), tint = Color.White ) } } } // Text content Box( modifier = Modifier .verticalScroll(rememberScrollState()) .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 16.dp) .padding(bottom = 30.dp) .weight(3f) .background(Color.White, shape = RoundedCornerShape(16.dp)), contentAlignment = Alignment.TopCenter ) { Column { Text( text = singleRecipe!!.name, fontWeight = Bold, fontSize = 25.sp, modifier = Modifier.padding(bottom = 8.dp) ) Text( text = "Instructions", fontSize = 25.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 8.dp) ) Text( text = singleRecipe.instructions.joinToString("\n"), modifier = Modifier.padding(top = 8.dp), color = Color.Gray ) Text( text = "Ingredients", fontSize = 25.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 8.dp) ) Text( text = singleRecipe.ingredients.joinToString("\n"), modifier = Modifier.padding(top = 8.dp), color = Color.Gray ) } } } } } // paging concept oin /* @OptIn(ExperimentalFoundationApi::class) @Composable fun HorizontalPagerExample() { val items = (1..10).toList() // Example list of items HorizontalPager( state = rememberPagerState { items.size }, modifier = Modifier.fillMaxSize() ) { page -> Box( modifier = Modifier .fillMaxSize() .padding(16.dp) .background(color = if (page % 2 == 0) Color.Green else Color.Blue), contentAlignment = Alignment.Center ) { Text(text = "Page $page", fontSize = 24.sp, color = Color.White) } } }*/
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/models/SingleRecipe.kt
335799218
package com.example.recipeappusingapi.models data class SingleRecipe( val id: Int, val image: String, val instructions: List<String>, val ingredients: List<String>, val name: String )
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/models/Recipe.kt
357864144
package com.example.recipeappusingapi.models data class Recipe( val caloriesPerServing: Int, val cookTimeMinutes: Int, val cuisine: String, val difficulty: String, val id: Int, val image: String, val ingredients: List<String>, val instructions: List<String>, val mealType: List<String>, val name: String, val prepTimeMinutes: Int, val rating: Double, val reviewCount: Int, val servings: Int, val tags: List<String>, val userId: Int )
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/models/RecipeList.kt
3921555863
package com.example.recipeappusingapi.models data class RecipeList( val limit: Int, val recipes: List<Recipe>, val skip: Int, val total: Int )
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/api/RetrofitHelper.kt
3858014253
package com.example.recipeappusingapi.api import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitHelper { private const val BASE_URL = "https://dummyjson.com/" fun getInstance(): Retrofit{ return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } }
RecipeAppUsingRestAPI/app/src/main/java/com/example/recipeappusingapi/api/RecipeService.kt
842393423
package com.example.recipeappusingapi.api import com.example.recipeappusingapi.models.RecipeList import retrofit2.Response import retrofit2.http.GET interface RecipeService { @GET("recipes") suspend fun getRecipes(): Response<RecipeList> }
Compostory/compostory-compiler/src/commonMain/kotlin/io/github/anbuiii/compostory/compiler/BuilderProcessor.kt
1722567284
package io.github.anbuiii.compostory.compiler import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.KSAnnotated import io.github.anbuiii.compostory.compiler.utils.writeText /** * Builder for Local Navigator * * Remove */ class BuilderProcessor( private val codeGenerator: CodeGenerator, ) : SymbolProcessor { private var invoked = false override fun process(resolver: Resolver): List<KSAnnotated> { if (!invoked) { val mainScreenKt = codeGenerator.createNewFile(Dependencies(true), "", "AppNavigator", "kt") val text = """ import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.staticCompositionLocalOf import cafe.adriel.voyager.navigator.Navigator val LocalAppNavigator: ProvidableCompositionLocal<Navigator?> = staticCompositionLocalOf { null } @Composable fun ProvideAppNavigator(navigator: Navigator, content: @Composable () -> Unit) { CompositionLocalProvider(LocalAppNavigator provides navigator) { content() } } """.trimIndent() invoked = true mainScreenKt.writeText(text) } return emptyList() } } class BuilderProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { return BuilderProcessor(environment.codeGenerator) } }
Compostory/compostory-compiler/src/commonMain/kotlin/io/github/anbuiii/compostory/compiler/repostory/CompostoryRepository.kt
3298873885
package io.github.anbuiii.compostory.compiler.repostory internal class CompostoryRepository { internal val screens = hashMapOf<String, () -> Unit>() fun addScreen(name: String, callback: () -> Unit) { screens[name] = callback } companion object { val instance: CompostoryRepository by lazy { CompostoryRepository() } } }
Compostory/compostory-compiler/src/commonMain/kotlin/io/github/anbuiii/compostory/compiler/CompostoryProcessor.kt
2778286042
package io.github.anbuiii.compostory.compiler import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSVisitorVoid import com.google.devtools.ksp.validate import io.github.anbuiii.compostory.annotation.Compostory import io.github.anbuiii.compostory.compiler.repostory.CompostoryRepository import io.github.anbuiii.compostory.compiler.utils.writeText internal class CompostoryProcessor( val codeGenerator: CodeGenerator, ) : SymbolProcessor { val repository: CompostoryRepository = CompostoryRepository.instance private var invoked = false override fun process(resolver: Resolver): List<KSAnnotated> { val symbols = resolver.getSymbolsWithAnnotation(Compostory::class.qualifiedName!!) symbols.filter { it is KSFunctionDeclaration && it.validate() } .forEach { it.accept(CompostoryVisitor(), Unit) } if (!invoked) { val homeScreenKt = codeGenerator.createNewFile(Dependencies(true), "", "HomeScreenKt") val screenList = repository.screens.map { it.key }.joinToString { """ "$it" to ${it}Detail() """.trimIndent() } val homeScreenText = """ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import cafe.adriel.voyager.core.screen.Screen class HomeScreen() : Screen { private val screens = listOf( $screenList ) @Composable override fun Content() { val navigator = LocalNavigator.currentOrThrow LazyColumn() { items(screens) { Button( onClick = { navigator.push(it.second) } ) { Text(it.first) } } } } } """.trimIndent() homeScreenKt.writeText(homeScreenText) val compostoryAppKt = codeGenerator.createNewFile(Dependencies(true), "", "CompostoryApp") val compostoryAppText = """ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import cafe.adriel.voyager.navigator.Navigator import cafe.adriel.voyager.transitions.SlideTransition @Composable fun CompostoryApp() { Scaffold( modifier = Modifier.fillMaxSize(), ) { Navigator( screen = HomeScreen(), content = { navigator -> ProvideAppNavigator( navigator = navigator, content = { SlideTransition(navigator) } ) } ) } } """.trimIndent() invoked = true compostoryAppKt.writeText(compostoryAppText) } return emptyList() } inner class CompostoryVisitor : KSVisitorVoid() { override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) { val functionName = function.simpleName.asString() val packageName = function.containingFile?.packageName?.asString() ?: "" val file = codeGenerator.createNewFile(Dependencies.ALL_FILES, packageName, functionName) repository.addScreen(functionName, {}) val text = """ import androidx.compose.runtime.Composable import cafe.adriel.voyager.core.screen.Screen class ${functionName}Detail : Screen { @Composable override fun Content() { ${functionName}() } } """.trimIndent() file.writeText(text) } } } class CompostoryProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { return CompostoryProcessor(environment.codeGenerator) } }
Compostory/compostory-compiler/src/commonMain/kotlin/io/github/anbuiii/compostory/compiler/utils/FileExtension.kt
1330796802
/** * @author An Bui */ package io.github.anbuiii.compostory.compiler.utils import java.io.OutputStream /** * Shortcut for write text to file */ internal fun OutputStream.writeText(text: String) { this.write(text.toByteArray()) }
Compostory/compostory-compiler/src/commonTest/kotlin/JvmFibiTest.kt
3132069393
import kotlin.test.Test import kotlin.test.assertEquals class JvmFibiTest { @Test fun `test init`() { assertEquals(2, 1 + 1) } }
Compostory/compostory-annotations/src/commonMain/kotlin/io/github/anbuiii/compostory/annotation/Annotation.kt
1971449408
/** * @author An Bui */ package io.github.anbuiii.compostory.annotation /** * Compostory definition annotation * * Create a screen and entry point to that screen * * example: * * @Compostory * @Composable * fun SampleUI () { ... } * */ @Target(AnnotationTarget.FUNCTION) annotation class Compostory
spring-data-lab/src/main/kotlin/ua/kpi/its/lab/data/config/Config.kt
1286880414
package ua.kpi.its.lab.data.config import jakarta.persistence.EntityManagerFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType import org.springframework.orm.jpa.JpaTransactionManager import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter import org.springframework.transaction.PlatformTransactionManager import org.springframework.transaction.annotation.EnableTransactionManagement import java.util.* import javax.sql.DataSource @Configuration @ComponentScan(basePackages = ["ua.kpi.its.lab.data"]) @EnableJpaRepositories(basePackages = ["ua.kpi.its.lab.data.repo"]) @EnableTransactionManagement class Config { /** * Configures the data source for the embedded database. * * Uses Spring's [EmbeddedDatabaseBuilder] to configure an in-memory HSQL database. * * @return DataSource the configured data source for the application. */ @Bean fun dataSource(): DataSource = EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .build() /** * Configures the [EntityManagerFactory] bean used by JPA to manage entity persistence. * * Sets the data source and package to scan for JPA entities. Additionally, it configures * Hibernate as the JPA vendor adapter, specifying properties such as DDL auto-generation and SQL dialect. * * @param dataSource The DataSource bean configured for the application. * @return LocalContainerEntityManagerFactoryBean the EntityManagerFactory instance for managing JPA entities. */ @Bean fun entityManagerFactory(dataSource: DataSource) = LocalContainerEntityManagerFactoryBean().apply { setDataSource(dataSource) setPackagesToScan("ua.kpi.its.lab.data.entity") jpaVendorAdapter = HibernateJpaVendorAdapter() setJpaProperties(additionalProperties()) } /** * Configures the transaction manager to be used for managing transactions within the Spring application. * * Utilizes [JpaTransactionManager] for managing JPA transactions, linked with the configured [EntityManagerFactory]. * * @param entityManagerFactory The EntityManagerFactory bean for creating EntityManager instances. * @return PlatformTransactionManager the transaction manager for managing transactions. */ @Bean fun transactionManager(entityManagerFactory: EntityManagerFactory): PlatformTransactionManager = JpaTransactionManager(entityManagerFactory) /** * Configures a bean to automatically translate any persistence-related exceptions into Spring's DataAccessException hierarchy. * * This abstraction allows for consistent exception handling across different persistence technologies. * * @return PersistenceExceptionTranslationPostProcessor the exception translation post-processor. */ @Bean fun exceptionTranslation() = PersistenceExceptionTranslationPostProcessor() /** * Specifies additional properties for the JPA provider (Hibernate in this case). * * This includes properties such as the Hibernate dialect, DDL auto generation strategy, and whether to show SQL in logs. * * @return Properties the additional properties to set on the JPA provider. */ private fun additionalProperties(): Properties = Properties().apply { setProperty("hibernate.hbm2ddl.auto", "create") setProperty("hibernate.show_sql", "true") } @Bean fun calendar(): Calendar = GregorianCalendar() }
spring-data-lab/src/main/kotlin/ua/kpi/its/lab/data/entity/Entity.kt
1741571154
package ua.kpi.its.lab.data.entity import jakarta.persistence.* import java.util.* @Entity @Table(name = "satellites") class Satellite( @Column var name: String, @Column var country: String, @Column var launchDate: Date, @Column var purpose: String, @Column var weight: Double, @Column var height: Double, @Column var isGeostationary: Boolean, @OneToOne(cascade = [CascadeType.ALL]) @JoinColumn(name = "processor_id", referencedColumnName = "id") var processor: Processor ) : Comparable<Satellite> { @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long = -1 override fun compareTo(other: Satellite): Int { val equal = this.name == other.name && this.launchDate.time == other.launchDate.time return if (equal) 0 else 1 } override fun toString(): String { return "Satellite(name=$name, launchDate=$launchDate, processor=$processor)" } } @Entity @Table(name = "processors") class Processor( @Column var name: String, @Column var manufacturer: String, @Column var cores: Int, @Column var frequency: Double, @Column var socket: String, @Column var productionDate: Date, @Column var mmxSupport: Boolean, @OneToOne(mappedBy = "processor") var satellite: Satellite? = null ) : Comparable<Processor> { @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long = -1 override fun compareTo(other: Processor): Int { val equal = this.name == other.name && this.cores == other.cores return if (equal) 0 else 1 } override fun toString(): String { return "Processor(name=$name, cores=$cores)" } }
spring-data-lab/src/main/kotlin/ua/kpi/its/lab/data/Main.kt
2188028747
package ua.kpi.its.lab.data import org.springframework.context.annotation.AnnotationConfigApplicationContext import ua.kpi.its.lab.data.config.Config import ua.kpi.its.lab.data.entity.Satellite import ua.kpi.its.lab.data.entity.Processor import ua.kpi.its.lab.data.svc.SatelliteService import java.util.Calendar fun main() { val context = AnnotationConfigApplicationContext(Config::class.java) val satelliteService = context.getBean(SatelliteService::class.java) val calendar = context.getBean(Calendar::class.java) val processor1 = Processor( "processor_name_1", "processor_manufacturer_1", 4, 2.0, "socket_1", calendar.apply { set(2015, 0, 1, 0, 0, 0) }.time, true ) val processor2 = Processor( "processor_name_2", "processor_manufacturer_2", 8, 3.0, "socket_2", calendar.apply { set(2016, 0, 1, 0, 0, 0) }.time, false ) val satellite1 = Satellite( "satellite_name_1", "country_1", calendar.apply { set(2017, 0, 1, 0, 0, 0) }.time, "purpose_1", 1000.0, 500.0, true, processor1 ) val satellite2 = Satellite( "satellite_name_2", "country_2", calendar.apply { set(2018, 0, 1, 0, 0, 0) }.time, "purpose_2", 2000.0, 1000.0, false, processor2 ) val satellite3 = Satellite( "satellite_name_3", "country_1", calendar.apply { set(2019, 0, 1, 0, 0, 0) }.time, "purpose_2", 3000.0, 1500.0, true, processor1 ) val satellite4 = Satellite( "satellite_name_4", "country_2", calendar.apply { set(2020, 0, 1, 0, 0, 0) }.time, "purpose_3", 4000.0, 2000.0, false, processor2 ) val satellite5 = Satellite( "satellite_name_5", "country_1", calendar.apply { set(2021, 0, 1, 0, 0, 0) }.time, "purpose_3", 5000.0, 2500.0, true, processor1 ) val satellites = listOf(satellite1, satellite2, satellite3, satellite4, satellite5) satellites.forEach { satelliteService.create(it) } val satellite2Retrieved = satelliteService.readByIndex(3) println("Retrieved satellite: $satellite2Retrieved") val deletedSatellite = satelliteService.deleteByIndex(4) println("Removed satellite: $deletedSatellite") }
spring-data-lab/src/main/kotlin/ua/kpi/its/lab/data/svc/impl/EntityServiceImpl.kt
3024597030
package ua.kpi.its.lab.data.svc.impl import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import ua.kpi.its.lab.data.entity.Satellite import ua.kpi.its.lab.data.entity.Processor import ua.kpi.its.lab.data.repo.SatelliteRepository import ua.kpi.its.lab.data.repo.ProcessorRepository import ua.kpi.its.lab.data.svc.SatelliteService @Service class SatelliteServiceImpl @Autowired constructor( private val repository: SatelliteRepository ): SatelliteService { override fun create(satellite: Satellite): Satellite { if (satellite.id != -1L && repository.existsById(satellite.id)) { throw IllegalArgumentException("Satellite with ID = ${satellite.id} already exists") } return repository.save(satellite) } override fun read(): List<Satellite> { return repository.findAll() } override fun readByIndex(index: Int): Satellite { return this.read()[index] } override fun update(satellite: Satellite): Satellite { if (!repository.existsById(satellite.id)) { throw IllegalArgumentException("Satellite with ID = ${satellite.id} not found") } return repository.save(satellite) } override fun delete(satellite: Satellite) { if (!repository.existsById(satellite.id)) { throw IllegalArgumentException("Satellite with ID = ${satellite.id} not found") } repository.deleteById(satellite.id) } override fun deleteByIndex(index: Int): Satellite { val target = this.readByIndex(index) this.delete(target) return target } }
spring-data-lab/src/main/kotlin/ua/kpi/its/lab/data/svc/EntityService.kt
3650190077
package ua.kpi.its.lab.data.svc import ua.kpi.its.lab.data.entity.Satellite import ua.kpi.its.lab.data.entity.Processor interface SatelliteService { /** * Creates a new Satellite record. * * @param satellite: The Satellite instance to be inserted * @return: The recently created Satellite instance */ fun create(satellite: Satellite): Satellite /** * Reads all created Satellite records. * * @return: List of created Satellite records */ fun read(): List<Satellite> /** * Reads a Satellite record by its index. * The order is determined by the order of creation. * * @param index: The index of Satellite record * @return: The Satellite instance at index */ fun readByIndex(index: Int): Satellite /** * Updates a Satellite record data. * * @param satellite: The Satellite instance to be updated (valid id is required) * @return: The updated Satellite record */ fun update(satellite: Satellite): Satellite /** * Deletes a Satellite record data. * * @param satellite: The Satellite instance to be deleted (valid `id` is required) */ fun delete(satellite: Satellite) /** * Deletes a Satellite record by its index. * The order is determined by the order of creation. * * @param index: The index of Satellite record to delete * @return: The deleted Satellite instance at index */ fun deleteByIndex(index: Int): Satellite }
spring-data-lab/src/main/kotlin/ua/kpi/its/lab/data/repo/Repository.kt
2328813704
package ua.kpi.its.lab.data.repo import org.springframework.data.jpa.repository.JpaRepository import ua.kpi.its.lab.data.entity.Satellite import ua.kpi.its.lab.data.entity.Processor interface SatelliteRepository : JpaRepository<Satellite, Long> { } interface ProcessorRepository : JpaRepository<Processor, Long> { }
kmp-compose-gradle-skeleton/composeApp/src/iosMain/kotlin/MainViewController.kt
3500059733
import androidx.compose.ui.window.ComposeUIViewController fun MainViewController() = ComposeUIViewController { App() }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/App.kt
3655926072
import androidx.compose.runtime.Composable import coil3.ImageLoader import coil3.annotation.ExperimentalCoilApi import coil3.compose.setSingletonImageLoaderFactory import coil3.network.ktor.KtorNetworkFetcherFactory import com.santimattius.kmp.skeleton.MainApplication import com.santimattius.kmp.skeleton.core.ui.themes.AppTheme @OptIn(ExperimentalCoilApi::class) @Composable fun App() { setSingletonImageLoaderFactory { context -> ImageLoader.Builder(context) .components { add(KtorNetworkFetcherFactory()) } .build() } AppTheme { MainApplication() } }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/di/Dependencies.kt
3095231137
package com.santimattius.kmp.skeleton.di import com.santimattius.kmp.skeleton.core.data.PictureRepository import com.santimattius.kmp.skeleton.core.network.ktorHttpClient import com.santimattius.kmp.skeleton.features.home.HomeScreenModel import org.koin.core.qualifier.qualifier import org.koin.dsl.module val sharedModules = module { single(qualifier(AppQualifiers.BaseUrl)) { "https://api-picture.onrender.com" } single(qualifier(AppQualifiers.Client)) { ktorHttpClient( baseUrl = get( qualifier = qualifier( AppQualifiers.BaseUrl ) ) ) } single { PictureRepository(get(qualifier(AppQualifiers.Client))) } } val homeModule = module { factory { HomeScreenModel(repository = get()) } } fun applicationModules() = listOf(sharedModules, homeModule)
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/di/AppQualifiers.kt
3570439144
package com.santimattius.kmp.skeleton.di enum class AppQualifiers { Client, BaseUrl }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/ui/components/NetworkImage.kt
2724309957
package com.santimattius.kmp.skeleton.core.ui.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import coil3.compose.LocalPlatformContext import coil3.compose.SubcomposeAsyncImage import coil3.request.ImageRequest @Composable internal fun NetworkImage( imageUrl: String, modifier: Modifier = Modifier, contentScale: ContentScale, contentDescription: String? = null, ) { SubcomposeAsyncImage( model = ImageRequest.Builder(LocalPlatformContext.current) .data(imageUrl).build(), loading = { Box(contentAlignment = Alignment.Center) { CircularProgressIndicator( color = MaterialTheme.colorScheme.secondary, modifier = Modifier.size(32.dp) ) } }, contentDescription = contentDescription, contentScale = contentScale, modifier = modifier ) }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/ui/components/AppBar.kt
1618467653
package com.santimattius.kmp.skeleton.core.ui.components import androidx.compose.foundation.layout.RowScope import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color @OptIn(ExperimentalMaterial3Api::class) @Composable fun AppBar( title: String = "", navigationIcon: @Composable () -> Unit = { }, containerColor: Color = MaterialTheme.colorScheme.primary, titleContentColor: Color = MaterialTheme.colorScheme.onPrimary, actions: @Composable RowScope.() -> Unit = {}, ) { TopAppBar( title = { Text(text = title) }, navigationIcon = navigationIcon, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = containerColor, titleContentColor = titleContentColor, navigationIconContentColor = titleContentColor, actionIconContentColor = titleContentColor, ), actions = actions ) }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/ui/components/Center.kt
313219713
package com.santimattius.kmp.skeleton.core.ui.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable private fun Center(content: @Composable () -> Unit) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { content() } } @Composable fun LoadingIndicator() { Center { CircularProgressIndicator() } } @Composable fun ErrorView(message: String) { Center { Text(message) } }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/ui/themes/Color.kt
1953350628
package com.santimattius.kmp.entertainment.core.ui.themes import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/ui/themes/Theme.kt
1403563290
package com.santimattius.kmp.skeleton.core.ui.themes import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import com.santimattius.kmp.entertainment.core.ui.themes.Pink40 import com.santimattius.kmp.entertainment.core.ui.themes.Pink80 import com.santimattius.kmp.entertainment.core.ui.themes.Purple40 import com.santimattius.kmp.entertainment.core.ui.themes.Purple80 import com.santimattius.kmp.entertainment.core.ui.themes.PurpleGrey40 import com.santimattius.kmp.entertainment.core.ui.themes.PurpleGrey80 import com.santimattius.kmp.entertainment.core.ui.themes.Typography private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40, onPrimary = Color.White, background = Color.White ) @Composable fun AppTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit, ) { val colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/ui/themes/Type.kt
2818163262
package com.santimattius.kmp.entertainment.core.ui.themes import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) )
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/network/Client.kt
36583637
package com.santimattius.kmp.skeleton.core.network import io.ktor.client.HttpClient import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.defaultRequest import io.ktor.client.plugins.logging.DEFAULT import io.ktor.client.plugins.logging.LogLevel import io.ktor.client.plugins.logging.Logger import io.ktor.client.plugins.logging.Logging import io.ktor.http.ContentType import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json internal fun ktorHttpClient(baseUrl: String) = HttpClient { install(ContentNegotiation) { json(Json { prettyPrint = true isLenient = true ignoreUnknownKeys = true }) } install(Logging) { logger = Logger.DEFAULT level = LogLevel.ALL } defaultRequest { url(baseUrl) contentType(ContentType.Application.Json) } }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/data/PictureRepository.kt
1703210643
package com.santimattius.kmp.skeleton.core.data import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.get import com.santimattius.kmp.skeleton.core.domain.Picture as DomainPicture private fun Picture.asDomain(): DomainPicture { return DomainPicture(this.id, this.author, this.downloadURL) } class PictureRepository( private val client: HttpClient, ) { suspend fun random() = runCatching { val response = client.get("/random") response.body<Picture>().asDomain() } }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/data/Picture.kt
628589392
package com.santimattius.kmp.skeleton.core.data import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Picture( @SerialName("id") val id: String, @SerialName("author") val author: String, @SerialName("width") val width: Long, @SerialName("height") val height: Long, @SerialName("url") val url: String, @SerialName("download_url") val downloadURL: String, )
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/core/domain/Picture.kt
2367178700
package com.santimattius.kmp.skeleton.core.domain data class Picture( val id: String, val author: String, val url: String, )
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/features/home/HomeScreenModel.kt
1487017047
package com.santimattius.kmp.skeleton.features.home import cafe.adriel.voyager.core.model.StateScreenModel import cafe.adriel.voyager.core.model.screenModelScope import com.santimattius.kmp.skeleton.core.data.PictureRepository import com.santimattius.kmp.skeleton.core.domain.Picture import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch data class HomeUiState( val isLoading: Boolean = false, val hasError: Boolean = false, val data: Picture? = null, ) class HomeScreenModel( private val repository: PictureRepository, ) : StateScreenModel<HomeUiState>(HomeUiState()) { private val exceptionHandler = CoroutineExceptionHandler { _, _ -> mutableState.update { it.copy(isLoading = false, hasError = true) } } init { randomImage() } fun randomImage() { mutableState.update { it.copy(isLoading = true, hasError = false) } screenModelScope.launch(exceptionHandler) { repository.random().onSuccess { picture -> mutableState.update { it.copy(isLoading = false, data = picture) } }.onFailure { mutableState.update { it.copy(isLoading = false, hasError = true) } } } } }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/features/home/HomeScreen.kt
509669395
package com.santimattius.kmp.skeleton.features.home import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.Card import androidx.compose.material3.FabPosition import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.koin.getScreenModel import com.santimattius.kmp.skeleton.core.ui.components.AppBar import com.santimattius.kmp.skeleton.core.ui.components.ErrorView import com.santimattius.kmp.skeleton.core.ui.components.LoadingIndicator import com.santimattius.kmp.skeleton.core.ui.components.NetworkImage object HomeScreen : Screen { @Composable override fun Content() { val screenModel = getScreenModel<HomeScreenModel>() HomeScreenContent(screenModel) } } @Composable fun HomeScreenContent( screenModel: HomeScreenModel, ) { val state by screenModel.state.collectAsState() Scaffold( topBar = { AppBar(title = "Compose Skeleton") }, floatingActionButtonPosition = FabPosition.Center, floatingActionButton = { FloatingActionButton(onClick = { screenModel.randomImage() }) { Icon(Icons.Default.Refresh, contentDescription = null) } } ) { Box( modifier = Modifier.fillMaxSize().padding(it), contentAlignment = Alignment.Center ) { when { state.isLoading -> LoadingIndicator() state.data == null || state.hasError -> { ErrorView(message = "An error occurred while updating the image") } else -> { Card(modifier = Modifier.padding(start = 16.dp, end = 16.dp)) { NetworkImage( imageUrl = state.data!!.url, contentDescription = "Image", contentScale = ContentScale.Crop, modifier = Modifier .fillMaxWidth() .background(Color.LightGray) .aspectRatio(ratio = (16 / 8).toFloat()), ) } } } } } }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/features/splash/SplashScreen.kt
3347060201
package com.santimattius.kmp.skeleton.features.splash import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import com.santimattius.kmp.skeleton.features.home.HomeScreen import kmp_compose_gradle_skeleton.composeapp.generated.resources.Res import kmp_compose_gradle_skeleton.composeapp.generated.resources.compose_multiplatform import kotlinx.coroutines.delay import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource object SplashScreen : Screen { @Composable override fun Content() { val navigator = LocalNavigator.currentOrThrow SplashScreenContent { navigator.replace(HomeScreen) } } } @OptIn(ExperimentalResourceApi::class) @Composable fun SplashScreenContent(navigate: () -> Unit) { val scale = remember { Animatable(0f) } LaunchedEffect(key1 = true) { scale.animateTo( targetValue = 0.7f, animationSpec = spring( dampingRatio = Spring.DampingRatioHighBouncy, stiffness = 1000f ) ) delay(800L) navigate() } Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Image( painterResource(Res.drawable.compose_multiplatform), null ) } }
kmp-compose-gradle-skeleton/composeApp/src/commonMain/kotlin/com/santimattius/kmp/skeleton/MainApplication.kt
556936271
package com.santimattius.kmp.skeleton import androidx.compose.runtime.Composable import cafe.adriel.voyager.navigator.Navigator import com.santimattius.kmp.skeleton.di.applicationModules import com.santimattius.kmp.skeleton.features.splash.SplashScreen import org.koin.compose.KoinApplication @Composable fun MainApplication() { KoinApplication(application = { modules(applicationModules() ) }) { Navigator(SplashScreen) } }
kmp-compose-gradle-skeleton/composeApp/src/androidMain/kotlin/com/santimattius/kmp/skeleton/MainActivity.kt
4047078621
package com.santimattius.kmp.skeleton import App import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { App() } } } @Preview @Composable fun AppAndroidPreview() { App() }
luke/src/main/kotlin/Main.kt
3243588231
package com.gwen.luke //TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. fun main() { val name = "Kotlin" //TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text // to see how IntelliJ IDEA suggests fixing it. println("Hello, " + name + "!") for (i in 1..5) { //TIP Press <shortcut actionId="Debug"/> to start debugging your code. We have set one <icon src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint // for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>. println("i = $i") } }
Destinos/app/src/androidTest/java/com/example/destination/ExampleInstrumentedTest.kt
800297027
package com.example.destination import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.destination", appContext.packageName) } }
Destinos/app/src/test/java/com/example/destination/ExampleUnitTest.kt
4154695061
package com.example.destination import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Destinos/app/src/main/java/com/example/destination/ui/theme/Color.kt
2092121919
package com.example.destination.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Destinos/app/src/main/java/com/example/destination/ui/theme/Theme.kt
403752677
package com.example.destination.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun DestinationTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Destinos/app/src/main/java/com/example/destination/ui/theme/Type.kt
394752299
package com.example.destination.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Destinos/app/src/main/java/com/example/destination/DetailActivity.kt
3660960122
package com.example.destination import android.annotation.SuppressLint import android.content.res.ColorStateList import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import com.example.destination.model.Destination import com.example.destination.model.DestinationManager import com.example.destination.model.ApiInterface import com.example.destination.model.WeatherApp import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class DetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) val city = intent.getStringExtra("city") val cityField = findViewById<TextView>(R.id.city) val info = findViewById<TextView>(R.id.info) val favBtn = findViewById<Button>(R.id.favsBtn) val destination: Destination? = city?.let { DestinationManager.instance.getDestinationbyCity(it) } if (city != null) { getWeather(city) } initializeButtonStyle(destination, favBtn) initializeInfo(destination, cityField, info) favBtn.setOnClickListener { styleButton(favBtn) if(!DestinationManager.instance.isAddedToFav(destination)){ DestinationManager.instance.addFav(destination) Toast.makeText(this,"añadido a favoritos", Toast.LENGTH_SHORT).show() } } } fun styleButton(btn: Button){ btn.isEnabled = false btn.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(this, R.color.gray)) } fun initializeButtonStyle(destination:Destination?, btn:Button){ if(destination?.let { it1 -> DestinationManager.instance.isAddedToFav(it1) } == true){ styleButton(btn) } } fun initializeInfo(destination:Destination?, cityField:TextView, info:TextView){ if (destination != null) { cityField.text = destination.city info.text = destination.country + "\n" + destination.category + "\n" + destination.activity + "\n$" + destination.price } } fun getWeather(nombreQuery : String){ val txtViewCiudadC = findViewById<TextView>(R.id.infoWeather) val retrofit = Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()) .baseUrl("https://api.weatherapi.com/v1/").build().create(ApiInterface::class.java) val response = retrofit.getWeatherData(nombreQuery, "f5857345c87c41f486b01214242502") response.enqueue(object : Callback<WeatherApp> { @SuppressLint("SetTextI18n") override fun onResponse(call: Call<WeatherApp>, response: Response<WeatherApp>) { val responseBody = response.body() if(response.isSuccessful && responseBody != null){ txtViewCiudadC.text = """ Location: ${responseBody.location.name}, ${responseBody.location.region}, ${responseBody.location.country} Local Time: ${responseBody.location.localtime} Current Temperature: ${responseBody.current.temp_c}°C Feels Like: ${responseBody.current.feelslike_c}°C """.trimIndent() } } override fun onFailure(call: Call<WeatherApp>, t: Throwable) { Log.i("FAIL", "Ha fallado") Log.e("API_RESPONSE", "Error fetching weather data", t) } }) } }
Destinos/app/src/main/java/com/example/destination/MainActivity.kt
645962097
package com.example.destination import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.destination.ui.theme.DestinationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DestinationTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { DestinationTheme { Greeting("Android") } }
Destinos/app/src/main/java/com/example/destination/HomeActivity.kt
2908315655
package com.example.destination import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.Button import android.widget.Spinner import android.widget.Toast class HomeActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val btnExplore = findViewById<Button>(R.id.destinosBtn) val btnRecomend = findViewById<Button>(R.id.recomendBtn) val btnFavs = findViewById<Button>(R.id.favsBtn) val spinner = findViewById<Spinner>(R.id.spinner) spinner.onItemSelectedListener = this btnExplore.setOnClickListener { setExploreIntent(spinner) } btnFavs.setOnClickListener { val intent = Intent(this, FavsActivity::class.java) startActivity(intent) } btnRecomend.setOnClickListener { val intent = Intent(this, RecomendationActivity::class.java) startActivity(intent) } } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val filter = parent?.selectedItem Toast.makeText(baseContext, "Filter: "+ filter, Toast.LENGTH_LONG).show() } override fun onNothingSelected(parent: AdapterView<*>?) { } fun setExploreIntent(spinner:Spinner){ val intent = Intent(this, ExploreActivity::class.java) val bundle = Bundle() bundle.putString("filter", spinner.selectedItem.toString()) intent.putExtra("bundle", bundle) startActivity(intent) } }
Destinos/app/src/main/java/com/example/destination/FavsActivity.kt
137351259
package com.example.destination import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView import android.widget.TextView import com.example.destination.model.DestinationManager class FavsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_favs) val title = findViewById<TextView>(R.id.favsText) val favsList = findViewById<ListView>(R.id.favsDest) val destinationsList = findViewById<ListView>(R.id.favsDest) initializeList(title, favsList) destinationsList.setOnItemClickListener(object: AdapterView.OnItemClickListener { override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val intent = Intent(baseContext, DetailActivity::class.java) intent.putExtra("city", destinationsList.getItemAtPosition(position).toString()) startActivity(intent) } }) } fun initializeList(title:TextView, favsList:ListView){ if(DestinationManager.instance.favs.isEmpty()){ title.text = "Destinos favritos: NA" }else{ val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, DestinationManager.instance.buildFav()) favsList.adapter = adapter } } }
Destinos/app/src/main/java/com/example/destination/model/DestinationManager.kt
2108157771
package com.example.destination.model import android.app.Activity import org.json.JSONArray import org.json.JSONObject import java.io.IOException import java.nio.charset.StandardCharsets class DestinationManager private constructor() { lateinit var destinations: JSONArray var destinationsList: MutableList<Destination> = mutableListOf() var favs: MutableList<Destination> = mutableListOf() val jsonFile = "destinos.json" companion object{ val instance: DestinationManager by lazy { DestinationManager()} } fun loadJSONFromAsset(activity: Activity): String? { try { val assets = activity.assets val inputStream = assets.open(jsonFile) val buffer = ByteArray(inputStream.available()) inputStream.read(buffer) inputStream.close() return String(buffer, StandardCharsets.UTF_8) } catch (ex: IOException) { ex.printStackTrace() return null } } fun getDestinations(activity: Activity): JSONArray { val json = JSONObject(loadJSONFromAsset(activity)) return json.getJSONArray("destinos") } fun buildAdapter(categoryE: String?, activity: Activity): MutableList<String> { try { val jsonArray = getDestinations(activity) val countriesArr = mutableListOf<String>() for (i in 0 until jsonArray.length()) { val jsonObject = jsonArray.getJSONObject(i) val capital = jsonObject.getString("nombre") val category = jsonObject.getString("categoria") val country = jsonObject.getString("pais") val activity = jsonObject.getString("plan") val price = jsonObject.getString("precio") var destination = Destination(capital, country, category, activity, price) if(!isAdded(capital)){ destinationsList.add(destination) } if (categoryE.equals("Todos", ignoreCase = true) || category.equals(categoryE, ignoreCase = true)) { countriesArr.add(capital) } } return countriesArr } catch (ex: Exception) { ex.printStackTrace() return mutableListOf() } } fun getDestinationbyCity(city:String): Destination { lateinit var destination: Destination for(dest: Destination in destinationsList){ if(dest.city.equals(city)){ destination = dest } } return destination } fun isAddedToFav(destination: Destination?): Boolean{ if(destination != null){ for(dest: Destination in favs){ if(dest.city.equals(destination.city)){ return true } } } return false } fun isAdded(destination: String): Boolean{ for(dest: Destination in destinationsList){ if(dest.city.equals(destination)){ return true } } return false } fun addFav(destination: Destination?){ if(destination != null){ favs.add(destination) } } fun buildFav(): MutableList<String>{ val favsDestinations = mutableListOf<String>() for(dest: Destination in favs){ favsDestinations.add(dest.city) } return favsDestinations } fun buildRecomendations(): String { val recomendations: MutableList<String> = mutableListOf() val favsCategories = mutableMapOf<String, Int>() var maxFrequency = 0 for (dest: Destination in favs) { val category = dest.category favsCategories[category] = favsCategories.getOrDefault(category, 0) + 1 maxFrequency = maxOf(maxFrequency, favsCategories[category]!!) } for ((category, frequency) in favsCategories) { if (frequency == maxFrequency) { for (dest in favs) { if (dest.category == category) { recomendations.add(dest.city) } } } } if(recomendations.size == 0){ return "" } return recomendations.random() } }
Destinos/app/src/main/java/com/example/destination/model/ApiInterface.kt
2876904827
package com.example.destination.model import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface ApiInterface { @GET("current.json") fun getWeatherData( @Query("q") city: String, @Query("key") apiKey: String, @Query("aqi") aqi: String = "no" // Include additional query parameter ): Call<WeatherApp> }
Destinos/app/src/main/java/com/example/destination/model/Destination.kt
348013414
package com.example.destination.model class Destination { var city: String var country: String var category: String var activity: String var price: String constructor(city: String, country: String, category: String, activity: String, price: String) { this.city = city this.country = country this.category = category this.activity = activity this.price = price } }
Destinos/app/src/main/java/com/example/destination/model/WeatherApp.kt
1881277654
package com.example.destination.model data class WeatherApp( val location: Location, val current: Current ) data class Location( val name: String, val region: String, val country: String, val lat: Double, val lon: Double, val tz_id: String, val localtime_epoch: Long, val localtime: String ) data class Current( val last_updated_epoch: Long, val last_updated: String, val temp_c: Double, val temp_f: Double, val is_day: Int, val condition: Condition, val wind_mph: Double, val wind_kph: Double, val wind_degree: Int, val wind_dir: String, val pressure_mb: Double, val pressure_in: Double, val precip_mm: Double, val precip_in: Double, val humidity: Int, val cloud: Int, val feelslike_c: Double, val feelslike_f: Double, val vis_km: Double, val vis_miles: Double, val uv: Int, val gust_mph: Double, val gust_kph: Double ) data class Condition( val text: String, val icon: String, val code: Int )
Destinos/app/src/main/java/com/example/destination/RecomendationActivity.kt
443156334
package com.example.destination import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.ListView import android.widget.TextView import com.example.destination.model.ApiInterface import com.example.destination.model.Destination import com.example.destination.model.DestinationManager import com.example.destination.model.WeatherApp import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class RecomendationActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_recomendation) val title = findViewById<TextView>(R.id.title) val cityField = findViewById<TextView>(R.id.city) val info = findViewById<TextView>(R.id.info) val titleWeather = findViewById<TextView>(R.id.titleWeather) val infoWeather = findViewById<TextView>(R.id.infoWeather) if(DestinationManager.instance.favs.isEmpty()){ title.text = "Recomendaciones: NA" cityField.text = "" info.text = "" titleWeather.text = "" infoWeather.text = "" }else{ val city = DestinationManager.instance.buildRecomendations() val destination: Destination? = city?.let { DestinationManager.instance.getDestinationbyCity(it) } if (destination != null) { getWeather(city) cityField.text = destination.city info.text = destination.country + "\n" + destination.category + "\n" + destination.activity + "\n$" + destination.price } } } fun getWeather(nombreQuery : String){ val txtViewCiudadC = findViewById<TextView>(R.id.infoWeather) val retrofit = Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()) .baseUrl("https://api.weatherapi.com/v1/").build().create(ApiInterface::class.java) val response = retrofit.getWeatherData(nombreQuery, "f5857345c87c41f486b01214242502") response.enqueue(object : Callback<WeatherApp> { @SuppressLint("SetTextI18n") override fun onResponse(call: Call<WeatherApp>, response: Response<WeatherApp>) { val responseBody = response.body() if(response.isSuccessful && responseBody != null){ txtViewCiudadC.text = """ Location: ${responseBody.location.name}, ${responseBody.location.region}, ${responseBody.location.country} Local Time: ${responseBody.location.localtime} Current Temperature: ${responseBody.current.temp_c}°C Feels Like: ${responseBody.current.feelslike_c}°C """.trimIndent() } } override fun onFailure(call: Call<WeatherApp>, t: Throwable) { Log.i("FAIL", "Ha fallado") Log.e("API_RESPONSE", "Error fetching weather data", t) } }) } }
Destinos/app/src/main/java/com/example/destination/ExploreActivity.kt
2379295098
package com.example.destination import android.content.Intent import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.example.destination.model.DestinationManager import org.json.JSONObject import java.io.IOException import java.io.InputStream class ExploreActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_explore) val bundle = intent.getBundleExtra("bundle") val filter = findViewById<TextView>(R.id.filterApplied) val categoryChosen = bundle?.getString("filter") filter.text = "Destinos filtrados por: " + categoryChosen val destinationsList = findViewById<ListView>(R.id.destinationList) DestinationManager.instance.destinations = DestinationManager.instance.getDestinations(this) val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, DestinationManager.instance.buildAdapter(categoryChosen, this)) destinationsList.adapter = adapter destinationsList.setOnItemClickListener(object: AdapterView.OnItemClickListener { override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val intent = Intent(baseContext, DetailActivity::class.java) intent.putExtra("city", destinationsList.getItemAtPosition(position).toString()) startActivity(intent) } }) } }
SkeletonAndroid/app/src/androidTest/java/com/mshdabiola/skeletonandroid/ExampleInstrumentedTest.kt
3396154463
/* *abiola 2024 */ package com.mshdabiola.skeletonandroid // import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Test import kotlin.test.DefaultAsserter.assertEquals import kotlin.test.assertEquals /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ // @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.mshdabiola.skeletonandroid.debug", appContext.packageName) } }
SkeletonAndroid/app/src/test/java/com/mshdabiola/skeletonandroid/ExampleUnitTest.kt
1020774450
/* *abiola 2024 */ package com.mshdabiola.skeletonandroid import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/ui/SkAppState.kt
2119757256
/* *abiola 2022 */ package com.mshdabiola.skeletonandroid.ui import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.mshdabiola.data.util.NetworkMonitor import com.mshdabiola.ui.TrackDisposableJank import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn @Composable fun rememberSkAppState( windowSizeClass: WindowSizeClass, networkMonitor: NetworkMonitor, coroutineScope: CoroutineScope = rememberCoroutineScope(), navController: NavHostController = rememberNavController(), ): SkAppState { NavigationTrackingSideEffect(navController) return remember( navController, coroutineScope, windowSizeClass, networkMonitor, ) { SkAppState( navController, coroutineScope, windowSizeClass, networkMonitor, ) } } @Stable class SkAppState( val navController: NavHostController, val coroutineScope: CoroutineScope, val windowSizeClass: WindowSizeClass, networkMonitor: NetworkMonitor, ) { val currentDestination: NavDestination? @Composable get() = navController .currentBackStackEntryAsState().value?.destination // val shouldShowBottomBar: Boolean // get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact // val shouldShowNavRail: Boolean // get() = !shouldShowBottomBar val isOffline = networkMonitor.isOnline .map(Boolean::not) .stateIn( scope = coroutineScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = false, ) } @Composable private fun NavigationTrackingSideEffect(navController: NavHostController) { TrackDisposableJank(navController) { metricsHolder -> val listener = NavController.OnDestinationChangedListener { _, destination, _ -> metricsHolder.state?.putState("Navigation", destination.route.toString()) } navController.addOnDestinationChangedListener(listener) onDispose { navController.removeOnDestinationChangedListener(listener) } } }
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/ui/SkApp.kt
605899943
/* *abiola 2022 */ package com.mshdabiola.skeletonandroid.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarDuration.Indefinite import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult import androidx.compose.material3.Text import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.mshdabiola.data.util.NetworkMonitor import com.mshdabiola.designsystem.component.SkBackground import com.mshdabiola.designsystem.component.SkGradientBackground import com.mshdabiola.designsystem.theme.GradientColors import com.mshdabiola.designsystem.theme.LocalGradientColors import com.mshdabiola.detail.navigation.MAIN_ROUTE import com.mshdabiola.detail.navigation.navigateToDetail import com.mshdabiola.skeletonandroid.navigation.SkNavHost @OptIn( ExperimentalComposeUiApi::class, ExperimentalMaterial3Api::class, ) @Composable fun SkApp( windowSizeClass: WindowSizeClass, networkMonitor: NetworkMonitor, appState: SkAppState = rememberSkAppState( networkMonitor = networkMonitor, windowSizeClass = windowSizeClass, ), ) { val shouldShowGradientBackground = false SkBackground { SkGradientBackground( gradientColors = if (shouldShowGradientBackground) { LocalGradientColors.current } else { GradientColors() }, ) { val snackbarHostState = remember { SnackbarHostState() } val isOffline by appState.isOffline.collectAsStateWithLifecycle() // If user is not connected to the internet show a snack bar to inform them. val notConnectedMessage = "Not connected" LaunchedEffect(isOffline) { if (isOffline) { snackbarHostState.showSnackbar( message = notConnectedMessage, duration = Indefinite, ) } } Scaffold( modifier = Modifier.semantics { testTagsAsResourceId = true }, containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onBackground, contentWindowInsets = WindowInsets(0, 0, 0, 0), snackbarHost = { SnackbarHost(snackbarHostState) }, floatingActionButton = { if (appState.currentDestination?.route == MAIN_ROUTE) { ExtendedFloatingActionButton( modifier = Modifier .windowInsetsPadding(WindowInsets.safeDrawing) .testTag("add"), onClick = { appState.navController.navigateToDetail(0) }, ) { Icon(imageVector = Icons.Rounded.Add, contentDescription = "add note") // Spacer(modifier = ) Text(text = "Add note") } } }, ) { padding -> Column( Modifier .fillMaxSize() .padding(padding) .consumeWindowInsets(padding) .windowInsetsPadding( WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal), ), ) { SkNavHost(appState = appState, onShowSnackbar = { message, action -> snackbarHostState.showSnackbar( message = message, actionLabel = action, duration = SnackbarDuration.Short, ) == SnackbarResult.ActionPerformed }) } } } } }
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/MainActivity.kt
2656562935
/* *abiola 2024 */ package com.mshdabiola.skeletonandroid import android.graphics.Color import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.metrics.performance.JankStats import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.Firebase import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.remoteconfig.remoteConfig import com.google.firebase.remoteconfig.remoteConfigSettings import com.mshdabiola.analytics.AnalyticsHelper import com.mshdabiola.analytics.LocalAnalyticsHelper import com.mshdabiola.data.util.NetworkMonitor import com.mshdabiola.designsystem.theme.SkTheme import com.mshdabiola.model.Contrast import com.mshdabiola.model.DarkThemeConfig import com.mshdabiola.model.ThemeBrand import com.mshdabiola.skeletonandroid.ui.SkApp import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { @Inject lateinit var lazyStats: dagger.Lazy<JankStats> @Inject lateinit var networkMonitor: NetworkMonitor @Inject lateinit var analyticsHelper: AnalyticsHelper val viewModel: MainActivityViewModel by viewModels() @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // val splashScreen = installSplashScreen() installSplashScreen() var uiState: MainActivityUiState by mutableStateOf(MainActivityUiState.Loading) lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState .onEach { uiState = it } .collect() } } enableEdgeToEdge() // splashScreen.setKeepOnScreenCondition { // when (uiState) { // MainActivityUiState.Loading -> true // is MainActivityUiState.Success -> false // } // } val remoteConfig = Firebase.remoteConfig remoteConfig.setConfigSettingsAsync( remoteConfigSettings { minimumFetchIntervalInSeconds = 3600 }, ) remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults) // remoteConfig.fetchAndActivate() // .addOnCompleteListener(this) { task -> // if (task.isSuccessful) { // val updated = task.result // // val tr= remoteConfig.getBoolean("theme") // val name =remoteConfig.getString("name") // // Timber.e("Config params updated: %s", updated) // Timber.e("theme $tr name $name") // Toast.makeText(this, "Fetch and activate succeeded", // Toast.LENGTH_SHORT).show() // } else { // Toast.makeText(this, "Fetch failed", // Toast.LENGTH_SHORT).show() // } // } // // remoteConfig.addOnConfigUpdateListener(object : ConfigUpdateListener { // override fun onUpdate(configUpdate : ConfigUpdate) { // Timber.e("Updated keys: " + configUpdate.updatedKeys); // // if (configUpdate.updatedKeys.contains("name")) { // remoteConfig.activate().addOnCompleteListener { // Timber.e("new name ${remoteConfig.getString("name")}") // } // } // } // // override fun onError(error : FirebaseRemoteConfigException) { // Timber.e( "Config update error with code: " + error.code, error) // } // }) FirebaseMessaging.getInstance().token.addOnCompleteListener( OnCompleteListener { task -> if (!task.isSuccessful) { Timber.e("Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token val token = task.result // Log and toast Timber.e(token) // Toast.makeText(baseContext, token, Toast.LENGTH_SHORT).show() }, ) setContent { val darkTheme = shouldUseDarkTheme(uiState) // Update the edge to edge configuration to match the theme // This is the same parameters as the default enableEdgeToEdge call, but we manually // resolve whether or not to show dark theme using uiState, since it can be different // than the configuration's dark theme value based on the user preference. DisposableEffect(darkTheme) { enableEdgeToEdge( statusBarStyle = SystemBarStyle.auto( Color.TRANSPARENT, Color.TRANSPARENT, ) { darkTheme }, navigationBarStyle = SystemBarStyle.auto( lightScrim, darkScrim, ) { darkTheme }, ) onDispose {} } CompositionLocalProvider(LocalAnalyticsHelper provides analyticsHelper) { SkTheme( darkTheme = darkTheme, themeBrand = chooseTheme(uiState), themeContrast = chooseContrast(uiState), disableDynamicTheming = shouldDisableDynamicTheming(uiState), ) { SkApp( networkMonitor = networkMonitor, windowSizeClass = calculateWindowSizeClass(this), ) } } } } } @Composable private fun chooseTheme( uiState: MainActivityUiState, ): ThemeBrand = when (uiState) { MainActivityUiState.Loading -> ThemeBrand.DEFAULT is MainActivityUiState.Success -> uiState.userData.themeBrand } @Composable private fun chooseContrast( uiState: MainActivityUiState, ): Contrast = when (uiState) { MainActivityUiState.Loading -> Contrast.Normal is MainActivityUiState.Success -> uiState.userData.contrast } @Composable private fun shouldDisableDynamicTheming( uiState: MainActivityUiState, ): Boolean = when (uiState) { MainActivityUiState.Loading -> false is MainActivityUiState.Success -> !uiState.userData.useDynamicColor } @Composable private fun shouldUseDarkTheme( uiState: MainActivityUiState, ): Boolean = when (uiState) { MainActivityUiState.Loading -> isSystemInDarkTheme() is MainActivityUiState.Success -> when (uiState.userData.darkThemeConfig) { DarkThemeConfig.FOLLOW_SYSTEM -> isSystemInDarkTheme() DarkThemeConfig.LIGHT -> false DarkThemeConfig.DARK -> true } } private val lightScrim = Color.argb(0xe6, 0xFF, 0xFF, 0xFF) private val darkScrim = Color.argb(0x80, 0x1b, 0x1b, 0x1b)
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/di/JankStatsModule.kt
727716409
/* *abiola 2022 */ package com.mshdabiola.skeletonandroid.di import android.app.Activity import android.util.Log import android.view.Window import androidx.metrics.performance.JankStats import androidx.metrics.performance.JankStats.OnFrameListener import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityComponent @Module @InstallIn(ActivityComponent::class) object JankStatsModule { @Provides fun providesOnFrameListener(): OnFrameListener = OnFrameListener { frameData -> // Make sure to only log janky frames. if (frameData.isJank) { // We're currently logging this but would better report it to a backend. Log.v("NiA Jank", frameData.toString()) } } @Provides fun providesWindow(activity: Activity): Window = activity.window @Provides fun providesJankStats( window: Window, frameListener: OnFrameListener, ): JankStats = JankStats.createAndTrack(window, frameListener) }
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/MainActivityViewModel.kt
1416498226
/* *abiola 2022 */ package com.mshdabiola.skeletonandroid import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mshdabiola.data.repository.UserDataRepository import com.mshdabiola.model.UserData import com.mshdabiola.skeletonandroid.MainActivityUiState.Loading import com.mshdabiola.skeletonandroid.MainActivityUiState.Success import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class MainActivityViewModel @Inject constructor( userDataRepository: UserDataRepository, ) : ViewModel() { val uiState: StateFlow<MainActivityUiState> = userDataRepository.userData.map { Success(it) }.stateIn( scope = viewModelScope, initialValue = Loading, started = SharingStarted.WhileSubscribed(5_000), ) } sealed interface MainActivityUiState { data object Loading : MainActivityUiState data class Success(val userData: UserData) : MainActivityUiState }
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/MessageService.kt
3060531375
/* *abiola 2024 */ package com.mshdabiola.skeletonandroid // import androidx.work.Worker // import androidx.work.WorkerParameters import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.media.RingtoneManager import android.os.Build import androidx.core.app.NotificationCompat import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.google.firebase.messaging.RemoteMessage.Notification import timber.log.Timber import java.net.URL class MessageService : FirebaseMessagingService() { // [START receive_message] override fun onMessageReceived(remoteMessage: RemoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Timber.tag(TAG).d("From: %s", remoteMessage.from) // Check if message contains a data payload. // if (remoteMessage.data.isNotEmpty()) { // Log.d(TAG, "Message data payload: ${remoteMessage.data}") // // // Check if data needs to be processed by long running job // if (needsToBeScheduled()) { // // For long-running tasks (10 seconds or more) use WorkManager. // scheduleJob() // } else { // // Handle message within 10 seconds // handleNow(remoteMessage.) // } // } // Check if message contains a notification payload. remoteMessage.notification?.let { sendNotification(it, this) } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. } // [END receive_message] private fun needsToBeScheduled() = false // [START on_new_token] /** * Called if the FCM registration token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the * FCM registration token is initially generated so this is where you would retrieve the token. */ override fun onNewToken(token: String) { Timber.tag(TAG).d("Refreshed token: $token") // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // FCM registration token to your app server. sendRegistrationToServer(token) } private fun sendRegistrationToServer(token: String?) { // Implement this method to send token to your app server. Timber.tag(TAG).d("sendRegistrationTokenToServer $token") } // [END on_new_token] private fun scheduleJob() { // [START dispatch_job] // val work = OneTimeWorkRequest.Builder(MyWorker::class.java) // .build() // WorkManager.getInstance(this) // .beginWith(work) // .enqueue() // [END dispatch_job] } private fun sendNotification(notification: Notification, context: Context) { val intent = Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val requestCode = 0 val pendingIntent = PendingIntent.getActivity( this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE, ) Timber.e("notification image ${notification.imageUrl}") val channelId = "fcm_default_channel" val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this, channelId) .setColor(context.getColor(R.color.primary)) .setSmallIcon(R.drawable.ic_stat_name) .setContentTitle(notification.title) .setContentText(notification.body) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent) notification.imageUrl?.let { val bitmap = getBitmap(it.toString()) notificationBuilder .setLargeIcon(bitmap) .setStyle( NotificationCompat .BigPictureStyle() .bigPicture(bitmap) .bigLargeIcon(null as Bitmap?), ) } val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( channelId, context.getString(R.string.default_notification_channel_id), NotificationManager.IMPORTANCE_DEFAULT, ) notificationManager.createNotificationChannel(channel) } val notificationId = 0 notificationManager.notify(notificationId, notificationBuilder.build()) } fun getBitmap(uri: String): Bitmap? { return try { val input = URL(uri).openStream() val bitmap = BitmapFactory.decodeStream(input) input.close() Timber.e("download") bitmap } catch (e: Exception) { e.printStackTrace() null } } companion object { private const val TAG = "MyFirebaseMsgService" } // internal class MyWorker(appContext: Context, workerParams: WorkerParameters) : // Worker(appContext, workerParams) { // override fun doWork(): Result { // // TODO(developer): add long running task here. // return Result.success() // } // } }
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/navigation/SkNavHost.kt
3055645223
/* *abiola 2022 */ package com.mshdabiola.skeletonandroid.navigation import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.compose.NavHost import com.mshdabiola.detail.navigation.MAIN_ROUTE import com.mshdabiola.detail.navigation.detailScreen import com.mshdabiola.detail.navigation.mainScreen import com.mshdabiola.detail.navigation.navigateToDetail import com.mshdabiola.skeletonandroid.ui.SkAppState @Composable fun SkNavHost( appState: SkAppState, onShowSnackbar: suspend (String, String?) -> Boolean, modifier: Modifier = Modifier, startDestination: String = MAIN_ROUTE, ) { val navController = appState.navController NavHost( navController = navController, startDestination = startDestination, modifier = modifier, ) { mainScreen(onShowSnackbar = onShowSnackbar, onClicked = navController::navigateToDetail) detailScreen(onShowSnackbar, navController::popBackStack) } }
SkeletonAndroid/app/src/main/java/com/mshdabiola/skeletonandroid/SkeletonApplication.kt
2295561452
/* *abiola 2024 */ package com.mshdabiola.skeletonandroid import android.app.Application import dagger.hilt.android.HiltAndroidApp import timber.log.Timber @HiltAndroidApp class SkeletonApplication : Application() { override fun onCreate() { super.onCreate() if (packageName.contains("debug")) { Timber.plant(Timber.DebugTree()) Timber.e("log on app create") } } }
SkeletonAndroid/features/detail/src/androidTest/kotlin/com/mshdabiola/detail/DetailScreenTest.kt
2498705052
/* *abiola 2022 */ package com.mshdabiola.detail import androidx.activity.ComponentActivity import androidx.compose.ui.test.junit4.createAndroidComposeRule import org.junit.Rule import org.junit.Test class DetailScreenTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun loading_showsLoadingSpinner() { // composeTestRule.setContent { // } // // composeTestRule // .onNodeWithContentDescription( // composeTestRule.activity.resources.getString(R.string.feature_bookmarks_loading), // ) // .assertExists() } }
SkeletonAndroid/features/detail/src/test/kotlin/com/mshdabiola/detail/DetailViewNoteTest.kt
2412313614
/* *abiola 2022 */ package com.mshdabiola.detail import androidx.lifecycle.SavedStateHandle import com.mshdabiola.data.repository.fake.FakeNoteRepository import com.mshdabiola.detail.navigation.DETAIL_ID_ARG import com.mshdabiola.testing.repository.TestUserDataRepository import com.mshdabiola.testing.util.MainDispatcherRule import org.junit.Before import org.junit.Rule class DetailViewNoteTest { @get:Rule val dispatcherRule = MainDispatcherRule() private val userDataRepository = TestUserDataRepository() private lateinit var viewModel: DetailViewModel @Before fun setup() { viewModel = DetailViewModel( savedStateHandle = SavedStateHandle(mapOf(DETAIL_ID_ARG to 4)), noteRepository = FakeNoteRepository(), ) } // @Test // fun stateIsInitiallyLoading() = runTest { // } // @Test // fun oneBookmark_showsInFeed() = runTest { // val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.feedUiState.collect() } // // newsRepository.sendNewsResources(newsResourcesTestData) // userDataRepository.updateNewsResourceBookmark(newsResourcesTestData[0].id, true) // val item = viewModel.feedUiState.value // assertIs<Success>(item) // assertEquals(item.feed.size, 1) // // collectJob.cancel() // } }
SkeletonAndroid/features/detail/src/main/kotlin/com/mshdabiola/detail/DetailViewModel.kt
1083303409
/* *abiola 2022 */ package com.mshdabiola.detail import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mshdabiola.data.repository.NoteRepository import com.mshdabiola.detail.navigation.DetailArgs import com.mshdabiola.model.Note import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val noteRepository: NoteRepository, ) : ViewModel() { private val topicArgs: DetailArgs = DetailArgs(savedStateHandle) private val topicId = topicArgs.id private var _noteState = mutableStateOf(Note()) val noteState: State<Note> = _noteState init { viewModelScope.launch { if (topicId > 0) { val note = noteRepository.getOne(topicId) .first() if (note != null) { _noteState.value = note } } } viewModelScope.launch { snapshotFlow { noteState.value } .collectLatest { if (it.id != null) { noteRepository.upsert(it) } } } } var job: Job? = null fun onTitleChange(text: String) { _noteState.value = noteState.value.copy(title = text) if (noteState.value.id == null) { job?.cancel() job = viewModelScope.launch { val id = getId() _noteState.value = noteState.value.copy(id = id) } } } fun onContentChange(text: String) { _noteState.value = noteState.value.copy(content = text) if (noteState.value.id == null) { job?.cancel() job = viewModelScope.launch { val id = getId() _noteState.value = noteState.value.copy(id = id) } } } fun onDelete() { viewModelScope.launch { noteState.value.id?.let { noteRepository.delete(it) } } } suspend fun getId(): Long { return noteRepository.upsert(Note()) } }
SkeletonAndroid/features/detail/src/main/kotlin/com/mshdabiola/detail/navigation/DetailNavigation.kt
3832980130
/* *abiola 2022 */ package com.mshdabiola.detail.navigation import androidx.annotation.VisibleForTesting import androidx.compose.animation.AnimatedContentTransitionScope import androidx.lifecycle.SavedStateHandle import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.mshdabiola.detail.DetailRoute const val DETAIL_ROUTE = "detail_route" private val URL_CHARACTER_ENCODING = Charsets.UTF_8.name() @VisibleForTesting internal const val DETAIL_ID_ARG = "topicId" internal class DetailArgs(val id: Long) { constructor(savedStateHandle: SavedStateHandle) : this(checkNotNull<Long>(savedStateHandle[DETAIL_ID_ARG])) // this(URLDecoder.decode(checkNotNull(savedStateHandle[DETAIL_ID_ARG]), URL_CHARACTER_ENCODING)) } fun NavController.navigateToDetail(topicId: Long) { // val encodedId = URLEncoder.encode(topicId, URL_CHARACTER_ENCODING) navigate("$DETAIL_ROUTE/$topicId") { launchSingleTop = true } } fun NavGraphBuilder.detailScreen( onShowSnackbar: suspend (String, String?) -> Boolean, onBack: () -> Unit, ) { composable( route = "$DETAIL_ROUTE/{$DETAIL_ID_ARG}", arguments = listOf( navArgument(DETAIL_ID_ARG) { type = NavType.LongType }, ), enterTransition = { slideIntoContainer(towards = AnimatedContentTransitionScope.SlideDirection.Left) }, exitTransition = { slideOutOfContainer(towards = AnimatedContentTransitionScope.SlideDirection.Right) }, ) { DetailRoute(onShowSnackbar, onBack) } }
SkeletonAndroid/features/detail/src/main/kotlin/com/mshdabiola/detail/DetailScreen.kt
2830119791
/* *abiola 2022 */ package com.mshdabiola.detail import androidx.annotation.VisibleForTesting import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.mshdabiola.designsystem.component.DetailTopAppBar import com.mshdabiola.designsystem.component.SkTextField import com.mshdabiola.ui.TrackScreenViewEvent import kotlinx.coroutines.launch @Composable internal fun DetailRoute( onShowSnackbar: suspend (String, String?) -> Boolean, onBack: () -> Unit, modifier: Modifier = Modifier, viewModel: DetailViewModel = hiltViewModel(), ) { DetailScreen( onShowSnackbar = onShowSnackbar, modifier = modifier, title = viewModel.noteState.value.title, content = viewModel.noteState.value.content, onTitleChange = viewModel::onTitleChange, onContentChange = viewModel::onContentChange, onDelete = { viewModel.onDelete() onBack() }, onBack = onBack, ) } @OptIn(ExperimentalMaterial3Api::class) @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) @Composable internal fun DetailScreen( modifier: Modifier = Modifier, title: String = "", content: String = "", onTitleChange: (String) -> Unit = {}, onContentChange: (String) -> Unit = {}, onShowSnackbar: suspend (String, String?) -> Boolean = { _, _ -> false }, onBack: () -> Unit = {}, onDelete: () -> Unit = {}, ) { val coroutineScope = rememberCoroutineScope() Column(modifier) { DetailTopAppBar( onNavigationClick = onBack, onDeleteClick = onDelete, ) SkTextField( modifier = Modifier .fillMaxWidth() .testTag("detail:title"), value = title, onValueChange = onTitleChange, placeholder = "Title", maxNum = 1, imeAction = ImeAction.Next, ) SkTextField( modifier = Modifier .fillMaxWidth() .testTag("detail:content") .weight(1f), value = content, onValueChange = onContentChange, placeholder = "content", imeAction = ImeAction.Done, keyboardAction = { coroutineScope.launch { onShowSnackbar("Note Update", null) } }, ) } TrackScreenViewEvent(screenName = "Detail") } @Preview @Composable private fun DetailScreenPreview() { DetailScreen() }
SkeletonAndroid/features/main/src/androidTest/kotlin/com/mshdabiola/detail/MainScreenTest.kt
3851065832
/* *abiola 2022 */ package com.mshdabiola.detail import androidx.activity.ComponentActivity import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import com.mshdabiola.ui.MainState import com.mshdabiola.ui.NoteUiState import org.junit.Rule import org.junit.Test /** * UI tests for [MainScreen] composable. */ class MainScreenTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun enterText_showsShowText() { composeTestRule.setContent { MainScreen( mainState = MainState.Success( listOf( NoteUiState( id = 5257L, title = "Jacinto", description = "Charisma", ), // NoteUiState(id = 7450L, title = "Dewayne", description = "Justan"), // NoteUiState(id = 1352L, title = "Bjorn", description = "Daquan"), // NoteUiState(id = 4476L, title = "Tonya", description = "Ivelisse"), // NoteUiState(id = 6520L, title = "Raegan", description = "Katrena"), // NoteUiState(id = 5136L, title = "Markis", description = "Giles"), // NoteUiState(id = 6868L, title = "Virgilio", description = "Ashford"), // NoteUiState(id = 7100L, title = "Larae", description = "Krystyn"), // NoteUiState(id = 3210L, title = "Nigel", description = "Sergio"), // NoteUiState(id = 7830L, title = "Kristy", description = "Jacobi"), // NoteUiState(id = 1020L, title = "Kathlene", description = "Shlomo"), // NoteUiState(id = 3365L, title = "Corin", description = "Ross"), ), ), onClick = {}, onShowSnackbar = { _, _ -> false }, ) } composeTestRule .onNodeWithTag("main:list") .assertExists() } }
SkeletonAndroid/features/main/src/test/kotlin/com/mshdabiola/detail/MainViewNoteTest.kt
299885333
/* *abiola 2022 */ package com.mshdabiola.detail import com.mshdabiola.data.repository.fake.FakeNoteRepository import com.mshdabiola.testing.repository.TestUserDataRepository import com.mshdabiola.testing.util.MainDispatcherRule import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test class MainViewNoteTest { @get:Rule val dispatcherRule = MainDispatcherRule() private val userDataRepository = TestUserDataRepository() private lateinit var viewModel: MainViewModel @Before fun setup() { viewModel = MainViewModel( userDataRepository = userDataRepository, noteRepository = FakeNoteRepository(), ) } @Test fun stateIsInitiallyLoading() = runTest { // assertEquals(Loading, viewModel.feedUiMainState.value) } @Test fun oneBookmark_showsInFeed() = runTest { // val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.feedUiMainState.collect() } // // newsRepository.sendNewsResources(newsResourcesTestData) // userDataRepository.updateNewsResourceBookmark(newsResourcesTestData[0].id, true) // val item = viewModel.feedUiMainState.value // assertIs<Success>(item) // assertEquals(item.feed.size, 1) // // collectJob.cancel() } }
SkeletonAndroid/features/main/src/main/kotlin/com/mshdabiola/detail/MainViewModel.kt
1352719394
/* *abiola 2022 */ package com.mshdabiola.detail import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mshdabiola.data.repository.NoteRepository import com.mshdabiola.data.repository.UserDataRepository import com.mshdabiola.ui.MainState import com.mshdabiola.ui.NoteUiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val userDataRepository: UserDataRepository, private val noteRepository: NoteRepository, ) : ViewModel() { var shouldDisplayUndoBookmark by mutableStateOf(false) private var lastRemovedBookmarkId: String? = null val feedUiMainState: StateFlow<MainState> = noteRepository.getAll() .map { notes -> MainState.Success(notes.map { NoteUiState(it.id!!, it.title, it.content) }) } .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = MainState.Loading, ) }
SkeletonAndroid/features/main/src/main/kotlin/com/mshdabiola/detail/navigation/MainNavigation.kt
2775494301
/* *abiola 2022 */ package com.mshdabiola.detail.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavOptions import androidx.navigation.compose.composable import com.mshdabiola.detail.MainRoute const val MAIN_ROUTE = "main_route" fun NavController.navigateToMain(navOptions: NavOptions) = navigate(MAIN_ROUTE, navOptions) fun NavGraphBuilder.mainScreen( onShowSnackbar: suspend (String, String?) -> Boolean, onClicked: (Long) -> Unit, ) { composable(route = MAIN_ROUTE) { MainRoute(onClick = onClicked, onShowSnackbar) } }
SkeletonAndroid/features/main/src/main/kotlin/com/mshdabiola/detail/MainScreen.kt
4116544858
/* *abiola 2022 */ package com.mshdabiola.detail import androidx.annotation.VisibleForTesting import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.mshdabiola.designsystem.component.SkLoadingWheel import com.mshdabiola.designsystem.theme.LocalTintTheme import com.mshdabiola.designsystem.theme.SkTheme import com.mshdabiola.main.R import com.mshdabiola.ui.MainState import com.mshdabiola.ui.MainState.Loading import com.mshdabiola.ui.MainState.Success import com.mshdabiola.ui.NoteUiState import com.mshdabiola.ui.TrackScreenViewEvent import com.mshdabiola.ui.TrackScrollJank import com.mshdabiola.ui.noteItem @Composable internal fun MainRoute( onClick: (Long) -> Unit, onShowSnackbar: suspend (String, String?) -> Boolean, modifier: Modifier = Modifier, viewModel: MainViewModel = hiltViewModel(), ) { val feedState by viewModel.feedUiMainState.collectAsStateWithLifecycle() MainScreen( mainState = feedState, onShowSnackbar = onShowSnackbar, modifier = modifier, onClick = onClick, shouldDisplayUndoBookmark = viewModel.shouldDisplayUndoBookmark, undoBookmarkRemoval = {}, clearUndoState = {}, ) } @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) @Composable internal fun MainScreen( mainState: MainState, onClick: (Long) -> Unit, onShowSnackbar: suspend (String, String?) -> Boolean, modifier: Modifier = Modifier, shouldDisplayUndoBookmark: Boolean = false, undoBookmarkRemoval: () -> Unit = {}, clearUndoState: () -> Unit = {}, ) { val bookmarkRemovedMessage = stringResource(id = R.string.features_main_removed) val undoText = stringResource(id = R.string.features_main_undo) LaunchedEffect(shouldDisplayUndoBookmark) { if (shouldDisplayUndoBookmark) { val snackBarResult = onShowSnackbar(bookmarkRemovedMessage, undoText) if (snackBarResult) { undoBookmarkRemoval() } else { clearUndoState() } } } when (mainState) { Loading -> LoadingState(modifier) is Success -> if (mainState.noteUiStates.isNotEmpty()) { MainList( mainState, onClick, modifier, ) } else { EmptyState(modifier) } } TrackScreenViewEvent(screenName = "Main") } @Composable private fun LoadingState(modifier: Modifier = Modifier) { SkLoadingWheel( modifier = modifier .fillMaxWidth() .wrapContentSize() .testTag("main:loading"), contentDesc = stringResource(id = R.string.features_main_loading), ) } @Composable private fun MainList( feedMainState: MainState, onClick: (Long) -> Unit, modifier: Modifier = Modifier, ) { val scrollableState = rememberLazyListState() TrackScrollJank(scrollableState = scrollableState, stateName = "main:list") Box( modifier = modifier .fillMaxSize(), ) { LazyColumn( contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), state = scrollableState, modifier = Modifier .fillMaxSize() .testTag("main:list"), ) { noteItem( feedMainState = feedMainState, onClick = onClick, ) // item(span = StaggeredGridItemSpan.FullLine) { // Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing)) // } } } } @Composable private fun EmptyState(modifier: Modifier = Modifier) { Column( modifier = modifier .padding(16.dp) .fillMaxSize() .testTag("main:empty"), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { val iconTint = LocalTintTheme.current.iconTint Image( modifier = Modifier.fillMaxWidth(), painter = painterResource(id = R.drawable.features_main_img_empty_bookmarks), colorFilter = if (iconTint != Color.Unspecified) ColorFilter.tint(iconTint) else null, contentDescription = null, ) Spacer(modifier = Modifier.height(48.dp)) Text( text = stringResource(id = R.string.features_main_empty_error), modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, ) Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource(id = R.string.features_main_empty_description), modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodyMedium, ) } } @Preview @Composable private fun LoadingStatePreview() { SkTheme { LoadingState() } } @Preview @Composable private fun MainListPreview() { SkTheme { MainList( feedMainState = Success( listOf( NoteUiState( id = 5257L, title = "Jacinto", description = "Charisma", ), NoteUiState(id = 7450L, title = "Dewayne", description = "Justan"), NoteUiState(id = 1352L, title = "Bjorn", description = "Daquan"), NoteUiState(id = 4476L, title = "Tonya", description = "Ivelisse"), NoteUiState(id = 6520L, title = "Raegan", description = "Katrena"), NoteUiState(id = 5136L, title = "Markis", description = "Giles"), NoteUiState(id = 6868L, title = "Virgilio", description = "Ashford"), NoteUiState(id = 7100L, title = "Larae", description = "Krystyn"), NoteUiState(id = 3210L, title = "Nigel", description = "Sergio"), NoteUiState(id = 7830L, title = "Kristy", description = "Jacobi"), NoteUiState(id = 1020L, title = "Kathlene", description = "Shlomo"), NoteUiState(id = 3365L, title = "Corin", description = "Ross"), ), ), onClick = {}, ) } } @Preview @Composable private fun EmptyStatePreview() { SkTheme { EmptyState() } }
SkeletonAndroid/spotless/copyright.kt
2581638924
/* *abiola $YEAR */
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidFeatureConventionPlugin.kt
790146889
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.android.build.gradle.LibraryExtension import com.mshdabiola.app.configureGradleManagedDevices import com.mshdabiola.app.libs import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.project class AndroidFeatureConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { pluginManager.apply { apply("mshdabiola.android.library") apply("mshdabiola.android.hilt") } extensions.configure<LibraryExtension> { defaultConfig { testInstrumentationRunner = "com.mshdabiola.testing.TestRunner" } configureGradleManagedDevices(this) } dependencies { add("implementation", project(":modules:ui")) add("implementation", project(":modules:designsystem")) add("implementation", libs.findLibrary("androidx.navigation.compose").get()) add("implementation", libs.findLibrary("androidx.hilt.navigation.compose").get()) add("implementation", libs.findLibrary("androidx.lifecycle.runtimeCompose").get()) add("implementation", libs.findLibrary("androidx.lifecycle.viewModelCompose").get()) add("debugImplementation", libs.findLibrary("androidx.monitor").get()) } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidHiltConventionPlugin.kt
1778311017
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.mshdabiola.app.libs import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies class AndroidHiltConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.google.devtools.ksp") apply("dagger.hilt.android.plugin") } dependencies { "implementation"(libs.findLibrary("hilt.android").get()) "ksp"(libs.findLibrary("hilt.compiler").get()) } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidApplicationConventionPlugin.kt
1031277836
import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.android.build.gradle.BaseExtension import com.mshdabiola.app.configureBadgingTasks import com.mshdabiola.app.configureGradleManagedDevices import com.mshdabiola.app.configureKotlinAndroid import com.mshdabiola.app.configurePrintApksTask import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.getByType class AndroidApplicationConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.android.application") apply("org.jetbrains.kotlin.android") apply("mshdabiola.android.lint") apply("com.dropbox.dependency-guard") } extensions.configure<ApplicationExtension> { configureKotlinAndroid(this) defaultConfig.targetSdk = 34 configureGradleManagedDevices(this) } extensions.configure<ApplicationAndroidComponentsExtension> { configurePrintApksTask(this) configureBadgingTasks(extensions.getByType<BaseExtension>(), this) } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidApplicationComposeConventionPlugin.kt
4020736527
import com.android.build.api.dsl.ApplicationExtension import com.mshdabiola.app.configureAndroidCompose import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType class AndroidApplicationComposeConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { pluginManager.apply("com.android.application") val extension = extensions.getByType<ApplicationExtension>() configureAndroidCompose(extension) } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidApplicationJacocoConventionPlugin.kt
2832073008
import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.mshdabiola.app.configureJacoco import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType class AndroidApplicationJacocoConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("org.gradle.jacoco") apply("com.android.application") } val extension = extensions.getByType<ApplicationAndroidComponentsExtension>() configureJacoco(extension) } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidRoomConventionPlugin.kt
3899023509
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.devtools.ksp.gradle.KspExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.getByType import org.gradle.process.CommandLineArgumentProvider import java.io.File class AndroidRoomConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { pluginManager.apply("com.google.devtools.ksp") extensions.configure<KspExtension> { // The schemas directory contains a schema file for each version of the Room database. // This is required to enable Room auto migrations. // See https://developer.android.com/reference/kotlin/androidx/room/AutoMigration. arg(RoomSchemaArgProvider(File(projectDir, "schemas"))) } val libs = extensions.getByType<VersionCatalogsExtension>().named("libs") dependencies { add("implementation", libs.findLibrary("room.runtime").get()) add("implementation", libs.findLibrary("room.ktx").get()) add("implementation", libs.findLibrary("room.paging").get()) add("ksp", libs.findLibrary("room.compiler").get()) } } } /** * https://issuetracker.google.com/issues/132245929 * [Export schemas](https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schemas) */ class RoomSchemaArgProvider( @get:InputDirectory @get:PathSensitive(PathSensitivity.RELATIVE) val schemaDir: File, ) : CommandLineArgumentProvider { override fun asArguments() = listOf("room.schemaLocation=${schemaDir.path}") } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidTestConventionPlugin.kt
1029232730
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.android.build.gradle.TestExtension import com.mshdabiola.app.configureGradleManagedDevices import com.mshdabiola.app.configureKotlinAndroid import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure class AndroidTestConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.android.test") apply("org.jetbrains.kotlin.android") } extensions.configure<TestExtension> { configureKotlinAndroid(this) defaultConfig.targetSdk = 34 configureGradleManagedDevices(this) } } } }
SkeletonAndroid/build-logic/convention/src/main/kotlin/AndroidLintConventionPlugin.kt
1770886378
import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.dsl.LibraryExtension import com.android.build.api.dsl.Lint import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure class AndroidLintConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { when { pluginManager.hasPlugin("com.android.application") -> configure<ApplicationExtension> { lint(Lint::configure) } pluginManager.hasPlugin("com.android.library") -> configure<LibraryExtension> { lint(Lint::configure) } else -> { pluginManager.apply("com.android.lint") configure<Lint>(Lint::configure) } } } } } private fun Lint.configure() { xmlReport = true checkDependencies = true }