content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/** This class represents the Landing Screen and the elements it contains. */
class LandingScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<LandingScreen>(
semanticsProvider = semanticsProvider,
viewBuilderAction = { hasTestTag("LandingScreen") }) {
// Structural elements of the UI
val topBarLanding: KNode = child { hasTestTag("TopBarNavigation") }
val bottomBarLanding: KNode = child { hasTestTag("BottomNavigationMenu") }
val completeScreen: KNode = child { hasTestTag("CompleteScreen") }
val filterClick: KNode = child { hasTestTag("FilterClick") }
val recipeList: KNode = child { hasTestTag("RecipeList") }
val recipeCard: KNode = child { hasTestTag("RecipeCard") }
val userName: KNode = child { hasTestTag("UserName") }
val shareIcon: KNode = child { hasTestTag("ShareIcon") }
val saveIcon: KNode = child { hasTestTag("SaveIcon") }
val ratingButton: KNode = child { hasTestTag("Rating") }
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/LandingScreen.kt | 1349324729 |
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/** This class represents the Camera Screen and the elements it contains. */
class CameraScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<CameraScreen>(
semanticsProvider = semanticsProvider, viewBuilderAction = { hasTestTag("CameraScreen") }) {
// Structural elements of the UI
val photoButton: KNode = child { hasTestTag("PhotoButton") }
val galleryButton: KNode = child { hasTestTag("GalleryButton") }
val cameraPreview: KNode = child { hasTestTag("CameraPreview") }
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/CameraScreen.kt | 2770690219 |
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
class FriendsScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<FriendsScreen>(
semanticsProvider = semanticsProvider,
viewBuilderAction = { hasTestTag("FriendsScreen") }) {
val tabFollowers: KNode = child { hasTestTag("TabFollowers") }
val tabFollowing: KNode = child { hasTestTag("TabFollowing") }
val followersList: KNode = child { hasTestTag("FollowersList") }
val followingList: KNode = child { hasTestTag("FollowingList") }
val followerCard: KNode = child {
hasTestTag("FollowerCard")
} // You may need to iterate through the list for multiple cards
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/FriendsScreen.kt | 2788075812 |
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/**
* This class represents the Edit Profile Screen and the elements it contains within the UI. It
* provides direct access to UI components for testing.
*/
class EditProfileTestScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<EditProfileTestScreen>(
semanticsProvider = semanticsProvider,
viewBuilderAction = { hasTestTag("EditProfileScreen") }) {
// Structural elements of the UI for EditProfileScreen
val editPicture: KNode = child { hasTestTag("Edit_Picture") }
val nameInput: KNode = child { hasTestTag("NameInput") }
val usernameInput: KNode = child { hasTestTag("UsernameInput") }
val bioInput: KNode = child { hasTestTag("BioInput") }
val nameError: KNode = child { hasTestTag("NameError") }
val usernameError: KNode = child { hasTestTag("UsernameError") }
val bioError: KNode = child { hasTestTag("BioError") }
val saveButton: KNode = child { hasTestTag("EditSave") }
val editProfileContent: KNode = child { hasTestTag("EditProfileContent") }
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/EditProfileTestScreen.kt | 3387455714 |
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/** This class represents the Landing Screen and the elements it contains. */
class NotImplementedScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<NotImplementedScreen>(
semanticsProvider = semanticsProvider,
viewBuilderAction = { hasTestTag("NotImplementedScreen") }) {
// Structural elements of the UI
val topBarLanding: KNode = child { hasTestTag("TopBarNavigation") }
val bottomBarLanding: KNode = child { hasTestTag("BottomNavigationMenu") }
val middleText: KNode = child { hasTestTag("Text") }
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/NotImplementedScreen.kt | 4209845707 |
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/** This class represents the Login Screen and the elements it contains. */
class LoginScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<LoginScreen>(
semanticsProvider = semanticsProvider, viewBuilderAction = { hasTestTag("LoginScreen") }) {
// Structural elements of the UI
val loginTitle: KNode = child { hasTestTag("LoginTitle") }
val loginButton: KNode = child { hasTestTag("LoginButton") }
/** A function to set the test mode for the app. */
fun setTestMode(bool: Boolean) {
Testing.isTestMode = bool
}
/**
* A function to set the mocking for successful login.
*
* @param mockingSuccessfulLogin : a lambda function to mock successful login
*/
fun setLoginMockingForTests(mockingSuccessfulLogin: () -> Unit) {
Testing.mockSuccessfulLogin = mockingSuccessfulLogin
}
/** A testing object to set the test mode and mock successful login. */
object Testing {
var isTestMode = false
var mockSuccessfulLogin = {}
}
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/LoginScreen.kt | 4062851239 |
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/** This class represents the Create Screen and the elements it contains. */
class CreateScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<CreateScreen>(
semanticsProvider = semanticsProvider, viewBuilderAction = { hasTestTag("CreateScreen") }) {
// Structural elements of the UI
val topBarLanding: KNode = child { hasTestTag("TopBarNavigation") }
val bottomBarLanding: KNode = child { hasTestTag("BottomNavigationMenu") }
val cameraButton: KNode = child { hasTestTag("CameraButton") }
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/CreateScreen.kt | 4149405217 |
package com.android.feedme.screen
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import io.github.kakaocup.compose.node.element.ComposeScreen
import io.github.kakaocup.compose.node.element.KNode
/** This class represents the Profile Screen and the elements it contains. */
class ProfileScreen(semanticsProvider: SemanticsNodeInteractionsProvider) :
ComposeScreen<ProfileScreen>(
semanticsProvider = semanticsProvider,
viewBuilderAction = { hasTestTag("ProfileScreen") }) {
// Structural elements of the UI
val topBarProfile: KNode = child { hasTestTag("TopBarNavigation") }
val bottomBarProfile: KNode = child { hasTestTag("BottomNavigationMenu") }
val profileBox: KNode = child { hasTestTag("ProfileBox") }
val profileName: KNode = child { hasTestTag("ProfileName") }
val profileIcon: KNode = child { hasTestTag("ProfileIcon") }
val profileBio: KNode = child { hasTestTag("ProfileBio") }
val followerDisplayButton: KNode = child { hasTestTag("FollowerDisplayButton") }
val followingDisplayButton: KNode = child { hasTestTag("FollowingDisplayButton") }
val editButton: KNode = child { hasTestTag("EditButton") }
val shareButton: KNode = child { hasTestTag("ShareButton") }
val followerButton: KNode = child { hasTestTag("FollowButton") }
val followingButton: KNode = child { hasTestTag("FollowingButton") }
}
| feedme-android/app/src/androidTest/java/com/android/feedme/screen/ProfileScreen.kt | 1406460845 |
package com.android.feedme.ui
import android.os.Looper
import androidx.test.core.app.ApplicationProvider
import com.android.feedme.model.data.Profile
import com.android.feedme.model.data.ProfileRepository
import com.android.feedme.model.viewmodel.AuthViewModel
import com.google.android.gms.tasks.Tasks
import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import junit.framework.TestCase.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.anyString
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class AuthViewModelTest {
@Mock private lateinit var mockFirestore: FirebaseFirestore
@Mock private lateinit var mockDocumentReference: DocumentReference
@Mock private lateinit var mockCollectionReference: CollectionReference
@Mock private lateinit var mockDocumentSnapshot: DocumentSnapshot
private lateinit var profileRepository: ProfileRepository
private lateinit var authViewModel: AuthViewModel
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
if (FirebaseApp.getApps(ApplicationProvider.getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext())
}
ProfileRepository.initialize(mockFirestore)
profileRepository = ProfileRepository.instance
`when`(mockFirestore.collection("profiles")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(anyString())).thenReturn(mockDocumentReference)
authViewModel = AuthViewModel()
}
@Test
fun getProfile_Success() {
val profileId = "1"
val expectedProfile =
Profile(
profileId,
"John Doe",
"johndoe",
"[email protected]",
"A short bio",
"http://example.com/image.png",
listOf(),
listOf(),
listOf(),
listOf(),
listOf())
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockDocumentSnapshot))
`when`(mockDocumentSnapshot.toObject(Profile::class.java)).thenReturn(expectedProfile)
var bool = false
authViewModel.linkOrCreateProfile(
profileId, "johndoe", "[email protected]", "ss", { bool = true }, {})
shadowOf(Looper.getMainLooper()).idle()
authViewModel.linkOrCreateProfile(
"aaa", "johndoe", "[email protected]", "ss", { bool = true }, {})
shadowOf(Looper.getMainLooper()).idle()
authViewModel.linkOrCreateProfile(
profileId, "dd", "[email protected]", "ss", { bool = true }, {})
authViewModel.authenticateWithGoogle("johndoe", {}, {})
shadowOf(Looper.getMainLooper()).idle()
assertTrue(bool)
}
}
| feedme-android/app/src/test/java/com/android/feedme/ui/AuthViewModelTest.kt | 646832780 |
package com.android.feedme.model
import android.os.Looper
import androidx.test.core.app.ApplicationProvider
import com.android.feedme.model.data.Profile
import com.android.feedme.model.data.ProfileRepository
import com.android.feedme.model.viewmodel.ProfileViewModel
import com.google.android.gms.tasks.Tasks
import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertFalse
import junit.framework.TestCase.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.anyString
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class ProfileViewModelTest {
@Mock private lateinit var mockFirestore: FirebaseFirestore
@Mock private lateinit var mockDocumentReference: DocumentReference
@Mock private lateinit var mockCollectionReference: CollectionReference
@Mock private lateinit var mockDocumentSnapshot: DocumentSnapshot
private lateinit var profileRepository: ProfileRepository
private lateinit var profileViewModel: ProfileViewModel
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
if (FirebaseApp.getApps(ApplicationProvider.getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext())
}
ProfileRepository.initialize(mockFirestore)
profileRepository = ProfileRepository.instance
`when`(mockFirestore.collection("profiles")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(anyString())).thenReturn(mockDocumentReference)
profileViewModel = ProfileViewModel()
}
@Test
fun getProfile_Success() {
val profileId = "1"
val expectedProfile =
Profile(
profileId,
"John Doe",
"johndoe",
"[email protected]",
"A short bio",
"http://example.com/image.png",
listOf(),
listOf(),
listOf(),
listOf(),
listOf())
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockDocumentSnapshot))
`when`(mockDocumentSnapshot.toObject(Profile::class.java)).thenReturn(expectedProfile)
profileViewModel.fetchProfile("1")
shadowOf(Looper.getMainLooper()).idle()
assertTrue(profileViewModel.viewingUserProfile.value!!.email == expectedProfile.email)
}
@Test
fun isViewingProfile_ViewingUserIdNotNull_ReturnsTrue() {
profileViewModel.currentUserId = "1"
profileViewModel.viewingUserId = "2"
assertTrue(profileViewModel.isViewingProfile())
}
@Test
fun isViewingProfile_ViewingUserIdNull_ReturnsFalse() {
profileViewModel.currentUserId = "1"
profileViewModel.viewingUserId = null
assertFalse(profileViewModel.isViewingProfile())
}
@Test
fun isViewingProfile_ViewingUserIdNotNull_ThenNull_ReturnsFalse() {
profileViewModel.currentUserId = "1"
profileViewModel.viewingUserId = "2"
profileViewModel.removeViewingProfile()
assertFalse(profileViewModel.isViewingProfile())
}
@Test
fun profileToShow_ViewingProfile_ReturnsViewingProfile() {
profileViewModel.currentUserId = "1"
profileViewModel.viewingUserId = null
profileViewModel.setViewingProfile(Profile("2", "John", "blabla", "[email protected]"))
val profile = profileViewModel.profileToShow()
assertEquals("2", profile.id)
assertEquals("John", profile.name)
assertEquals("blabla", profile.username)
assertEquals("[email protected]", profile.email)
}
}
| feedme-android/app/src/test/java/com/android/feedme/ui/ProfileViewModelTest.kt | 3508266431 |
package com.android.feedme
import org.junit.Assert.*
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)
}
}
| feedme-android/app/src/test/java/com/android/feedme/ExampleUnitTest.kt | 1308677972 |
package com.android.feedme.model
import android.os.Looper
import androidx.test.core.app.ApplicationProvider
import com.android.feedme.model.data.Comment
import com.android.feedme.model.data.CommentRepository
import com.google.android.gms.tasks.Tasks
import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import java.time.Instant
import java.util.Date
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertNotNull
import junit.framework.TestCase.fail
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class CommentRepositoryTest {
@Mock private lateinit var mockFirestore: FirebaseFirestore
@Mock private lateinit var mockDocumentReference: DocumentReference
@Mock private lateinit var mockCollectionReference: CollectionReference
private lateinit var commentRepository: CommentRepository
@Before
fun setUp() {
// Initialize Mockito annotations
MockitoAnnotations.openMocks(this)
// Initialize Firebase only if absolutely necessary for the test
if (FirebaseApp.getApps(ApplicationProvider.getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext())
}
// Initialize your Database class with the mocked FirebaseFirestore instance
// Make sure your Database class accepts FirebaseFirestore as a constructor parameter
commentRepository = CommentRepository(mockFirestore)
// Setup your mocks as needed
`when`(mockFirestore.collection("comments")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(anyString())).thenReturn(mockDocumentReference)
}
@Test
fun addComment_Success() {
// Setup
val comment =
Comment(
"authorId",
"recipeId",
"photoURL",
5.0,
120.0,
"Title",
"Content",
Date.from(Instant.now()))
`when`(mockFirestore.collection("comments")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(comment.authorId)).thenReturn(mockDocumentReference)
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forResult(null)) // Simulate success
// Execute
var successCalled = false
commentRepository.addComment(comment, { successCalled = true }, {})
// This ensures all asynchronous operations complete
shadowOf(Looper.getMainLooper()).idle()
// Verify
verify(mockDocumentReference).set(any(Comment::class.java))
assertTrue("Success callback was not called", successCalled)
}
@Test
fun getComment_Success() {
// Setup
val commentId = "testCommentId"
val expectedComment =
Comment(
"authorId",
"recipeId",
"photoURL",
5.0,
120.0,
"Title",
"Content",
Date.from(Instant.now()))
val mockSnapshot = mock(DocumentSnapshot::class.java)
`when`(mockFirestore.collection("comments")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(commentId)).thenReturn(mockDocumentReference)
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockSnapshot))
`when`(mockSnapshot.toObject(Comment::class.java)).thenReturn(expectedComment)
// Execute & Verify
commentRepository.getComment(
commentId,
{ comment -> assertEquals(expectedComment, comment) },
{ fail("Failure callback was called") })
}
@Test
fun addComment_Failure() {
val comment =
Comment(
"authorId",
"recipeId",
"photoURL",
5.0,
120.0,
"Title",
"Content",
Date.from(Instant.now()))
val exception = Exception("Firestore set operation failed")
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forException(exception))
var failureCalled = false
commentRepository.addComment(
comment,
onSuccess = { fail("Success callback should not be called") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun getComment_Failure() {
val commentId = "nonexistentId"
val exception = Exception("Firestore get operation failed")
`when`(mockDocumentReference.get()).thenReturn(Tasks.forException(exception))
var failureCalled = false
commentRepository.getComment(
commentId,
onSuccess = { fail("Success callback should not be called") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun testSingletonInitialization() {
val mockFirestore = mock(FirebaseFirestore::class.java)
CommentRepository.initialize(mockFirestore)
assertNotNull("Singleton instance should be initialized", CommentRepository.instance)
}
}
| feedme-android/app/src/test/java/com/android/feedme/model/CommentRepositoryTest.kt | 1492454931 |
package com.android.feedme.model
import android.os.Looper
import androidx.test.core.app.ApplicationProvider
import com.android.feedme.model.data.Ingredient
import com.android.feedme.model.data.IngredientMetaData
import com.android.feedme.model.data.MeasureUnit
import com.android.feedme.model.data.Recipe
import com.android.feedme.model.data.RecipeRepository
import com.android.feedme.model.data.Step
import com.google.android.gms.tasks.Tasks
import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.*
import junit.framework.TestCase.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class RecipeRepositoryTest {
@Mock private lateinit var mockFirestore: FirebaseFirestore
@Mock private lateinit var mockDocumentReference: DocumentReference
@Mock private lateinit var mockCollectionReference: CollectionReference
@Mock private lateinit var mockDocumentSnapshot: DocumentSnapshot
@Mock private lateinit var mockIngredientsCollectionReference: CollectionReference
@Mock private lateinit var mockIngredientDocumentSnapshot: DocumentSnapshot
private lateinit var recipeRepository: RecipeRepository
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
if (FirebaseApp.getApps(ApplicationProvider.getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext())
}
recipeRepository = RecipeRepository(mockFirestore)
`when`(mockFirestore.collection("recipes")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(anyString())).thenReturn(mockDocumentReference)
// Additional mocking for ingredients collection
`when`(mockFirestore.collection("ingredients")).thenReturn(mockIngredientsCollectionReference)
`when`(mockIngredientsCollectionReference.document(anyString()))
.thenReturn(mockDocumentReference)
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockIngredientDocumentSnapshot))
`when`(mockFirestore.collection("recipes")).thenReturn(mock(CollectionReference::class.java))
`when`(mockFirestore.collection("recipes").document(anyString()))
.thenReturn(mockDocumentReference)
// Here's the critical part: ensure a Task<Void> is returned
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forResult(null))
}
@Test
fun addRecipe_Success() {
val recipe =
Recipe(
"1",
"Chocolate Cake",
"Delicious chocolate cake",
listOf(),
listOf(),
listOf("dessert"),
60.0,
4.5,
"user123",
"Easy",
"http://image.url")
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forResult(null))
var successCalled = false
recipeRepository.addRecipe(recipe, { successCalled = true }, {})
shadowOf(Looper.getMainLooper()).idle()
verify(mockDocumentReference).set(any(Map::class.java))
assertTrue("Success callback was not called", successCalled)
}
@Test
fun getRecipe_Success() {
val recipeId = "1"
val recipeMap: Map<String, Any> =
mapOf(
"recipeId" to recipeId,
"title" to "Chocolate Cake",
"description" to "A deliciously rich chocolate cake.",
"ingredients" to
listOf(
mapOf(
"ingredientId" to "flourId",
"quantity" to 2.0,
"measure" to MeasureUnit.CUP.name),
mapOf(
"ingredientId" to "sugarId",
"quantity" to 1.0,
"measure" to MeasureUnit.CUP.name),
mapOf(
"ingredientId" to "cocoaId",
"quantity" to 0.5,
"measure" to MeasureUnit.CUP.name)),
"steps" to
listOf(
mapOf(
"stepNumber" to 1,
"description" to "Mix dry ingredients.",
"title" to "Prepare Dry Mix"),
mapOf(
"stepNumber" to 2,
"description" to "Blend with wet ingredients.",
"title" to "Mix Ingredients"),
mapOf(
"stepNumber" to 3,
"description" to "Pour into pan and bake.",
"title" to "Bake")),
"tags" to listOf("dessert", "chocolate", "cake"),
"time" to 60.0,
"rating" to 4.5,
"userid" to "user123",
"difficulty" to "Easy",
"imageUrl" to "http://example.com/chocolate_cake.jpg")
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockDocumentSnapshot))
`when`(mockDocumentSnapshot.exists()).thenReturn(true)
`when`(mockDocumentSnapshot.data).thenReturn(recipeMap)
// Simulating ingredient fetch - this requires complex mocking or a simplification in testing
// approach
// For the purpose of this example, let's assume the fetchIngredients function is simplified or
// its execution is somehow mocked/controlled within the test
recipeRepository.getRecipe(
recipeId,
{ recipe ->
assertNotNull(recipe)
assertEquals(recipeId, recipe?.recipeId)
},
{ fail("Failure callback was called") })
shadowOf(Looper.getMainLooper()).idle()
}
@Test
fun addRecipe_Failure() {
val recipe =
Recipe(
"1",
"Chocolate Cake",
"Delicious chocolate cake",
listOf(),
listOf(),
listOf("dessert"),
60.0,
4.5,
"user123",
"Easy",
"http://image.url")
val exception = Exception("Firestore set operation failed")
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forException(exception))
var failureCalled = false
recipeRepository.addRecipe(
recipe,
onSuccess = { fail("Success callback should not be called") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun getRecipe_Failure() {
val recipeId = "1"
val exception = Exception("Firestore get operation failed")
`when`(mockDocumentReference.get()).thenReturn(Tasks.forException(exception))
var failureCalled = false
recipeRepository.getRecipe(
recipeId,
onSuccess = { fail("Success callback should not be called") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun testSingletonInitialization() {
val mockFirestore = mock(FirebaseFirestore::class.java)
RecipeRepository.initialize(mockFirestore)
assertNotNull("Singleton instance should be initialized", RecipeRepository.instance)
}
@Test
fun addRecipe_CorrectlySerializesRecipe() {
val recipe =
Recipe(
recipeId = "1",
title = "Chocolate Cake",
description = "Delicious chocolate cake recipe.",
ingredients =
listOf(
IngredientMetaData(
1.0, MeasureUnit.CUP, Ingredient("Flour", "Baking", "flourId")),
IngredientMetaData(
2.0,
MeasureUnit.TABLESPOON,
Ingredient("Cocoa Powder", "Baking", "cocoaId"))),
steps =
listOf(
Step(1, "Mix ingredients.", "Mix all dry ingredients together."),
Step(2, "Bake", "Bake in the oven for 45 minutes.")),
tags = listOf("dessert", "cake", "chocolate"),
time = 60.0,
rating = 4.5,
userid = "user123",
difficulty = "Medium",
imageUrl = "http://example.com/cake.jpg")
var successCalled = false
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockDocumentSnapshot))
`when`(mockDocumentSnapshot.exists()).thenReturn(true)
recipeRepository.addRecipe(recipe, onSuccess = { successCalled = true }, onFailure = {})
// Execute all tasks scheduled on the main thread to simulate the Firestore callback
shadowOf(Looper.getMainLooper()).idle()
verify(mockDocumentReference).set(any())
assertTrue("Success callback was not called as expected", successCalled)
}
@Test
fun addRecipe_Success2() {
// Preparing the ingredients
val ingredient1 = Ingredient("Flour", "Dry", "1")
val ingredientMetaData1 = IngredientMetaData(2.0, MeasureUnit.CUP, ingredient1)
val ingredient2 = Ingredient("Sugar", "Dry", "2")
val ingredientMetaData2 = IngredientMetaData(1.0, MeasureUnit.CUP, ingredient2)
// Preparing the steps
val step1 = Step(1, "Mix Ingredients", "Mix flour and sugar.")
val step2 = Step(2, "Bake", "Bake for 30 minutes at 350 degrees.")
// Crafting the recipe
val recipe =
Recipe(
"1",
"Chocolate Cake",
"A rich chocolate cake",
listOf(ingredientMetaData1, ingredientMetaData2),
listOf(step1, step2),
listOf("Dessert", "Chocolate"),
60.0,
5.0,
"userId123",
"Medium",
"http://example.com/chocolate_cake.jpg")
// Mocking Firestore response for a successful set operation
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forResult(null))
// Action: Attempt to add the recipe
var successCalled = false
recipeRepository.addRecipe(recipe, onSuccess = { successCalled = true }, onFailure = {})
// Ensuring all async operations complete
shadowOf(Looper.getMainLooper()).idle()
// Verification: Check if the Firestore set method was called
verify(mockDocumentReference).set(any())
// Assert: Verify the success callback was invoked
assertTrue("Expected the success callback to be invoked", successCalled)
}
}
| feedme-android/app/src/test/java/com/android/feedme/model/RecipeRepositoryTest.kt | 2365075289 |
package com.android.feedme.model
import android.os.Looper
import androidx.test.core.app.ApplicationProvider
import com.android.feedme.model.data.Ingredient
import com.android.feedme.model.data.IngredientMetaData
import com.android.feedme.model.data.IngredientsRepository
import com.google.android.gms.tasks.Tasks
import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.*
import junit.framework.TestCase.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class IngredientsRepositoryTest {
@Mock private lateinit var mockFirestore: FirebaseFirestore
@Mock private lateinit var mockDocumentReference: DocumentReference
@Mock private lateinit var mockCollectionReference: CollectionReference
@Mock private lateinit var mockDocumentSnapshot: DocumentSnapshot
private lateinit var ingredientsRepository: IngredientsRepository
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
if (FirebaseApp.getApps(ApplicationProvider.getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext())
}
ingredientsRepository = IngredientsRepository(mockFirestore)
`when`(mockFirestore.collection("ingredients")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(anyString())).thenReturn(mockDocumentReference)
}
@Test
fun addIngredient_Success() {
val ingredient = Ingredient("Sugar", "Sweetener", "sugarId")
`when`(mockDocumentReference.set(ingredient)).thenReturn(Tasks.forResult(null))
var successCalled = false
ingredientsRepository.addIngredient(ingredient, { successCalled = true }, {})
shadowOf(Looper.getMainLooper()).idle()
verify(mockDocumentReference).set(ingredient)
assertTrue("Success callback was not called", successCalled)
}
@Test
fun getIngredient_Success() {
val ingredientId = "sugarId"
val expectedIngredient = Ingredient("Sugar", "Sweetener", ingredientId)
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockDocumentSnapshot))
`when`(mockDocumentSnapshot.toObject(Ingredient::class.java)).thenReturn(expectedIngredient)
ingredientsRepository.getIngredient(
ingredientId,
{ ingredient -> assertEquals(expectedIngredient, ingredient) },
{ fail("Failure callback was called") })
shadowOf(Looper.getMainLooper()).idle()
}
@Test
fun getIngredients_Success() {
val ingredientIds = listOf("sugarId", "flourId")
val sugar = Ingredient("Sugar", "Sweetener", "sugarId")
val flour = Ingredient("Flour", "Baking", "flourId")
// Setup responses for fetching each ingredient by ID
`when`(mockFirestore.collection("ingredients")).thenReturn(mockCollectionReference)
// Mock fetching sugar and flour documents
val sugarDocumentSnapshot = Mockito.mock(DocumentSnapshot::class.java)
val flourDocumentSnapshot = Mockito.mock(DocumentSnapshot::class.java)
`when`(sugarDocumentSnapshot.toObject(Ingredient::class.java)).thenReturn(sugar)
`when`(flourDocumentSnapshot.toObject(Ingredient::class.java)).thenReturn(flour)
// Simulate fetching ingredients
`when`(mockCollectionReference.document("sugarId")).thenReturn(mockDocumentReference)
`when`(mockCollectionReference.document("flourId")).thenReturn(mockDocumentReference)
`when`(mockDocumentReference.get())
.thenReturn(Tasks.forResult(sugarDocumentSnapshot))
.thenReturn(Tasks.forResult(flourDocumentSnapshot))
// Capturing onSuccess callback execution
var ingredientsMetaDataResult: List<IngredientMetaData>? = null
ingredientsRepository.getIngredients(
ingredientIds,
onSuccess = { ingredients -> ingredientsMetaDataResult = ingredients },
onFailure = { /* Should NOT HAPPENED */})
// Wait for async tasks to complete
shadowOf(Looper.getMainLooper()).idle()
// Assertions
assertNotNull("IngredientsMetaData result should not be null", ingredientsMetaDataResult)
assertEquals("IngredientsMetaData list size incorrect", 2, ingredientsMetaDataResult?.size)
// Further assertions can be made regarding the contents of the ingredientsMetaDataResult list
}
@Test
fun addIngredient_Failure() {
val ingredient = Ingredient("Sugar", "Sweetener", "sugarId")
val exception = Exception("Firestore add failure")
`when`(mockDocumentReference.set(ingredient)).thenReturn(Tasks.forException(exception))
var failureCalled = false
ingredientsRepository.addIngredient(
ingredient,
onSuccess = { fail("Success callback should not be called on failure") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun getIngredient_Failure() {
val ingredientId = "nonexistentId"
val exception = Exception("Firestore operation failed")
`when`(mockDocumentReference.get()).thenReturn(Tasks.forException(exception))
var failureCalled = false
ingredientsRepository.getIngredient(
ingredientId,
onSuccess = { fail("Success callback should not be called") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun getIngredients_Failure() {
val ingredientIds = listOf("sugarId", "flourId")
val exception = Exception("Firestore fetch failed")
// Setup mocks to simulate a failure for any fetch attempt
`when`(mockDocumentReference.get()).thenReturn(Tasks.forException(exception))
var failureCalled = false
ingredientsRepository.getIngredients(
ingredientIds,
onSuccess = { fail("Success callback should not be called in failure scenario") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called as expected", failureCalled)
}
@Test
fun testSingletonInitialization() {
val mockFirestore = mock(FirebaseFirestore::class.java)
IngredientsRepository.initialize(mockFirestore)
assertNotNull("Singleton instance should be initialized", IngredientsRepository.instance)
}
}
| feedme-android/app/src/test/java/com/android/feedme/model/IngredientsRepositoryTest.kt | 1979081410 |
package com.android.feedme.model.data
import java.time.Instant
import java.util.Date
import org.junit.Assert.*
import org.junit.Test
class CommentTest {
@Test
fun createAndRetrieveCommentProperties() {
// Given
val comment =
Comment(
authorId = "user123",
recipeId = "recipe456",
photoURL = "https://example.com/photo.jpg",
rating = 4.5,
time = 120.0,
title = "Delicious!",
content = "This recipe is fantastic!",
creationDate = Date.from(Instant.now()))
// Then
assertEquals("user123", comment.authorId)
assertEquals("recipe456", comment.recipeId)
assertEquals("https://example.com/photo.jpg", comment.photoURL)
assertEquals(4.5, comment.rating, 0.0)
assertEquals("Delicious!", comment.title)
// Additional assertions can be made for other fields
}
}
| feedme-android/app/src/test/java/com/android/feedme/model/data/CommentTest.kt | 2970927491 |
package com.android.feedme.model.data
import org.junit.Assert.*
import org.junit.Test
class ProfileTest {
@Test
fun createAndRetrieveProfileProperties() {
// Given
val followers = listOf("user1", "user2")
val following = listOf("user3", "user4")
val filters = listOf("filter1", "filter2")
val recipeList = listOf("") // Assuming recipes are created elsewhere or mocked
val commentList = listOf("comment1", "comment2")
val profile =
Profile(
id = "1",
name = "John Doe",
username = "johndoe123",
email = "[email protected]",
description = "Food enthusiast",
imageUrl = "https://example.com/johndoe.jpg",
followers = followers,
following = following,
filter = filters,
recipeList = recipeList,
commentList = commentList)
// Then
assertEquals("John Doe", profile.name)
assertEquals("johndoe123", profile.username)
assertEquals("[email protected]", profile.email)
assertEquals("Food enthusiast", profile.description)
assertEquals(followers, profile.followers)
assertEquals(following, profile.following)
assertEquals(filters, profile.filter)
// Additional assertions for `recipeList` and `commentList` as needed
}
}
| feedme-android/app/src/test/java/com/android/feedme/model/data/ProfileTest.kt | 1767627501 |
package com.android.feedme.model.data
import org.junit.Assert.*
import org.junit.Test
class RecipeTest {
@Test
fun createAndRetrieveRecipeProperties() {
// Given
val steps = listOf(Step(1, "Mix ingredients", "Mixing"))
val ingredients =
listOf(IngredientMetaData(1.0, MeasureUnit.CUP, Ingredient("Flour", "Dry", "1")))
val recipe =
Recipe(
recipeId = "1",
title = "Simple Cake",
description = "A simple cake recipe.",
ingredients = ingredients,
steps = steps,
tags = listOf("dessert", "cake"),
time = 60.0,
rating = 4.5,
userid = "user123",
difficulty = "Easy",
imageUrl = "https://example.com/cake.jpg")
// When - Retrieving properties (implicitly in assertions)
// Then
assertEquals("1", recipe.recipeId)
assertEquals("Simple Cake", recipe.title)
assertEquals(1, recipe.steps.size)
assertEquals("Mix ingredients", recipe.steps.first().description)
assertEquals(MeasureUnit.CUP, recipe.ingredients.first().measure)
assertEquals(4.5, recipe.rating, 0.0)
// You can continue asserting other properties as needed
}
}
| feedme-android/app/src/test/java/com/android/feedme/model/data/RecipeTest.kt | 1289646000 |
package com.android.feedme.model
import android.os.Looper
import androidx.test.core.app.ApplicationProvider
import com.android.feedme.model.data.Profile
import com.android.feedme.model.data.ProfileRepository
import com.google.android.gms.tasks.Tasks
import com.google.firebase.FirebaseApp
import com.google.firebase.firestore.*
import junit.framework.TestCase.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class ProfileRepositoryTest {
@Mock private lateinit var mockFirestore: FirebaseFirestore
@Mock private lateinit var mockDocumentReference: DocumentReference
@Mock private lateinit var mockCollectionReference: CollectionReference
@Mock private lateinit var mockDocumentSnapshot: DocumentSnapshot
private lateinit var profileRepository: ProfileRepository
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
if (FirebaseApp.getApps(ApplicationProvider.getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext())
}
profileRepository = ProfileRepository(mockFirestore)
`when`(mockFirestore.collection("profiles")).thenReturn(mockCollectionReference)
`when`(mockCollectionReference.document(anyString())).thenReturn(mockDocumentReference)
}
@Test
fun addProfile_Success() {
val profile =
Profile(
"1",
"John Doe",
"johndoe",
"[email protected]",
"A short bio",
"http://example.com/image.png",
listOf(),
listOf(),
listOf(),
listOf(),
listOf())
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forResult(null))
var successCalled = false
profileRepository.addProfile(profile, { successCalled = true }, {})
shadowOf(Looper.getMainLooper()).idle()
verify(mockDocumentReference).set(profile)
assertTrue("Success callback was not called", successCalled)
}
@Test
fun getProfile_Success() {
val profileId = "1"
val expectedProfile =
Profile(
profileId,
"John Doe",
"johndoe",
"[email protected]",
"A short bio",
"http://example.com/image.png",
listOf(),
listOf(),
listOf(),
listOf(),
listOf())
`when`(mockDocumentReference.get()).thenReturn(Tasks.forResult(mockDocumentSnapshot))
`when`(mockDocumentSnapshot.toObject(Profile::class.java)).thenReturn(expectedProfile)
profileRepository.getProfile(
profileId,
{ profile -> assertEquals(expectedProfile, profile) },
{ fail("Failure callback was called") })
shadowOf(Looper.getMainLooper()).idle()
}
@Test
fun addProfile_Failure() {
val profile =
Profile(
"1",
"John Doe",
"johndoe",
"[email protected]",
"A short bio",
"http://example.com/image.png",
listOf(),
listOf(),
listOf(),
listOf(),
listOf())
val exception = Exception("Firestore failure")
`when`(mockDocumentReference.set(any())).thenReturn(Tasks.forException(exception))
var failureCalled = false
profileRepository.addProfile(
profile,
onSuccess = { fail("Success callback should not be called") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun getProfile_Failure() {
val profileId = "nonexistent"
val exception = Exception("Firestore failure")
`when`(mockDocumentReference.get()).thenReturn(Tasks.forException(exception))
var failureCalled = false
profileRepository.getProfile(
profileId,
onSuccess = { fail("Success callback should not be called") },
onFailure = { failureCalled = true })
shadowOf(Looper.getMainLooper()).idle()
assertTrue("Failure callback was not called", failureCalled)
}
@Test
fun testSingletonInitialization() {
val mockFirestore = mock(FirebaseFirestore::class.java)
ProfileRepository.initialize(mockFirestore)
assertNotNull("Singleton instance should be initialized", ProfileRepository.instance)
}
}
| feedme-android/app/src/test/java/com/android/feedme/model/ProfileRepositoryTest.kt | 583641136 |
package com.android.feedme.ui.home
import android.annotation.SuppressLint
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.outlined.Save
import androidx.compose.material.icons.outlined.Star
import androidx.compose.material.icons.outlined.Timer
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.android.feedme.model.data.Ingredient
import com.android.feedme.model.data.IngredientMetaData
import com.android.feedme.model.data.MeasureUnit
import com.android.feedme.model.data.Recipe
import com.android.feedme.model.data.Step
import com.android.feedme.model.viewmodel.RecipeViewModel
import com.android.feedme.ui.component.SearchBarFun
import com.android.feedme.ui.navigation.BottomNavigationMenu
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.Screen
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.android.feedme.ui.navigation.TopBarNavigation
import com.android.feedme.ui.theme.TemplateColor
import com.android.feedme.ui.theme.TextBarColor
/**
* Composable function that generates the landing page / landing screen
*
* @param navigationActions The [NavigationActions] instance for handling back navigation.
*/
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun LandingPage(
navigationActions: NavigationActions,
recipeViewModel: RecipeViewModel = RecipeViewModel()
) {
/* Note that this val is temporary for this sprint, we're awaiting the implementation of the
* ViewModels to properly do this part. */
val testRecipes: List<Recipe> =
listOf(
Recipe(
recipeId = "lasagna1",
title = "Tasty Lasagna",
description =
"Description of the recipe, writing a longer one to see if it fills up the whole space available. Still writing with no particular aim lol",
ingredients =
listOf(
IngredientMetaData(
quantity = 2.0,
measure = MeasureUnit.ML,
ingredient = Ingredient("Tomato", "Vegetables", "tomatoID"))),
steps =
listOf(
Step(
1,
"In a large, heavy pot, put the olive oil, garlic and parsley over medium high heat. When the garlic begins to brown, increase the heat and add the ground beef. Break up the beef, but keep it rather chunky. Sprinkle with about 1/2 tsp of salt. \n" +
"\n" +
"When the beef is beginning to dry up, add the tomatoes and stir well. Add more salt, then lower the heat and allow to simmer for about an hour, stirring from time to time. Taste for salt and add pepper.",
"Make the Meat Sauce")),
tags = listOf("Meat"),
time = 45.0,
rating = 4.5,
userid = "username",
difficulty = "Intermediate",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.mamablip.com%2Fstorage%2FLasagna%2520with%2520Meat%2520and%2520Tomato%2520Sauce_3481612355355.jpg&f=1&nofb=1&ipt=8e887ba99ce20a85fb867dabbe0206c1146ebf2f13548b5653a2778e3ea18c54&ipo=images"),
)
Scaffold(
modifier = Modifier.fillMaxSize().testTag("LandingScreen"),
topBar = { TopBarNavigation(title = "FeedMe") },
bottomBar = {
BottomNavigationMenu(Route.HOME, navigationActions::navigateTo, TOP_LEVEL_DESTINATIONS)
},
content = { RecipeDisplay(navigationActions, testRecipes, recipeViewModel) })
}
/**
* A function that iterates over the list of recipes and generates a card for each one
*
* @param recipes : the list of [Recipe] to be displayed
*/
@Composable
fun RecipeDisplay(
navigationActions: NavigationActions,
recipes: List<Recipe>,
recipeViewModel: RecipeViewModel
) {
Column(
modifier = Modifier.testTag("CompleteScreen").padding(top = 60.dp).background(Color.White)) {
// Search bar + filters icon
SearchBarFun()
// Scrollable list of recipes
LazyColumn(
modifier =
Modifier.testTag("RecipeList").padding(top = 10.dp).background(TextBarColor)) {
items(recipes) { recipe ->
// Recipe card
Card(
modifier =
Modifier.padding(16.dp)
.clickable(
onClick = {
// Set the selected recipe in the view model and navigate to the
// recipe screen
recipeViewModel.selectRecipe(recipe)
navigationActions.navigateTo(Screen.RECIPE)
})
.testTag("RecipeCard"),
elevation = CardDefaults.elevatedCardElevation()) {
AsyncImage(
model = recipe.imageUrl,
contentDescription = "Recipe Image",
contentScale = ContentScale.Fit,
modifier = Modifier.height(200.dp).fillMaxWidth())
Column(
modifier =
Modifier.fillMaxWidth()
.background(Color.White)
.padding(top = 16.dp, start = 16.dp, end = 16.dp)) {
// Time, rating, share and saving icon
Row(
modifier = Modifier.padding(4.dp).fillMaxWidth(),
horizontalArrangement = Arrangement.Absolute.Left,
verticalAlignment = Alignment.CenterVertically,
) {
// Rating
Row(
verticalAlignment = Alignment.CenterVertically,
modifier =
Modifier.padding(end = 20.dp)
.clickable { /* TODO () : access the comments */}
.testTag("Rating")) {
Icon(
imageVector = Icons.Outlined.Star,
contentDescription = "Rating",
modifier = Modifier.size(30.dp).padding(end = 6.dp))
Text(text = String.format("%.1f", recipe.rating))
}
// Cooking time
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Outlined.Timer,
contentDescription = null,
modifier = Modifier.size(24.dp).padding(end = 4.dp))
Text(
text = "${recipe.time.toInt()} '",
modifier = Modifier.padding(end = 8.dp),
)
}
// Share icon
IconButton(
onClick = { /* TODO() adding the options to share */},
modifier = Modifier.testTag("ShareIcon")) {
Icon(
imageVector = Icons.Default.Share,
contentDescription = null,
modifier = Modifier.size(24.dp).padding(4.dp))
}
Spacer(modifier = Modifier.weight(1f))
// Save icon
IconButton(
onClick = { /* TODO() add saving logic here */},
modifier = Modifier.testTag("SaveIcon")) {
Icon(
imageVector = Icons.Outlined.Save,
contentDescription = null,
modifier = Modifier.size(24.dp).padding(start = 4.dp))
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
// Title of the Recipe
Text(
text = recipe.title,
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
color = TemplateColor,
modifier = Modifier.padding(bottom = 10.dp, end = 10.dp))
Spacer(modifier = Modifier.weight(1f))
OutlinedButton(
onClick = {},
border = BorderStroke(1.dp, TemplateColor),
colors =
ButtonDefaults.outlinedButtonColors(
contentColor = TemplateColor),
) {
Text(recipe.difficulty)
}
}
Spacer(modifier = Modifier.height(10.dp))
// Description of the recipe
Text(
text = recipe.description,
modifier = Modifier.fillMaxWidth().height(50.dp),
color = TemplateColor)
Text(
"@${recipe.userid}",
color = TemplateColor,
modifier =
Modifier.padding(bottom = 10.dp)
.clickable(
onClick = { /* TODO : implement the clicking on username */})
.testTag("UserName"))
}
}
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/home/LandingScreen.kt | 977805419 |
package com.android.feedme.ui.home
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AccessTime
import androidx.compose.material.icons.rounded.Star
import androidx.compose.material.icons.twotone.Bookmark
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.android.feedme.model.data.IngredientMetaData
import com.android.feedme.model.data.Recipe
import com.android.feedme.model.data.Step
import com.android.feedme.model.viewmodel.RecipeViewModel
import com.android.feedme.ui.navigation.BottomNavigationMenu
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.android.feedme.ui.navigation.TopBarNavigation
import com.android.feedme.ui.theme.BlueUser
import com.android.feedme.ui.theme.YellowStar
/**
* Displays a full recipe view. The screen contains the [TopBarNavigation], the
* [BottomNavigationMenu] and the recipes display. The recipe display includes : an image, general
* information's (time, userId of the creator and rating), list of ingredients and list of steps to
* prepare the recipe.
*
* @param navigationActions Gives access to the navigation actions.
* @param recipeViewModel The [RecipeViewModel] to get the recipe from.
*/
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun RecipeFullDisplay(
navigationActions: NavigationActions,
recipeViewModel: RecipeViewModel = RecipeViewModel()
) {
val recipe = recipeViewModel.recipe.collectAsState().value
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopBarNavigation(
title = recipe?.title ?: "Not Found",
navAction = navigationActions,
rightIcon = Icons.TwoTone.Bookmark,
rightIconOnClickAction = { null /* TODO() Save recipe offline*/ })
},
bottomBar = {
BottomNavigationMenu(Route.HOME, navigationActions::navigateTo, TOP_LEVEL_DESTINATIONS)
},
content = { padding ->
if (recipe != null) {
LazyColumn(modifier = Modifier.padding(padding)) {
item { ImageDisplay(recipe = recipe) }
item { GeneralInfosDisplay(recipe = recipe) }
item { IngredientTitleDisplay() }
items(recipe.ingredients) { ingredient -> IngredientDisplay(ingredient = ingredient) }
item { IngredientStepsDividerDisplay() }
items(recipe.steps) { step -> StepDisplay(step = step) }
}
}
})
}
/**
* Displays the image associated with a recipe.
*
* @param recipe The [Recipe].
* @param modifier The modifier for the image layout.
*/
@Composable
fun ImageDisplay(recipe: Recipe, modifier: Modifier = Modifier) {
var ImageSuccessfulDownload = remember { mutableStateOf(false) }
AsyncImage(
model = recipe.imageUrl,
contentDescription = "Recipe Image",
modifier = modifier.fillMaxWidth().testTag("Recipe Image"),
onSuccess = { ImageSuccessfulDownload.value = true })
// Display a warning message if image couldn't be downloaded from internets
if (!ImageSuccessfulDownload.value) {
Text("Failed to download image", modifier = Modifier.testTag("Fail Image Download"))
}
}
/**
* Displays general information about a recipe : time, userId of the creator and rating.
*
* @param recipe The [Recipe] to display information for.
* @param modifier The [Modifier] for the layout of the row wrapping the content.
*/
@Composable
fun GeneralInfosDisplay(recipe: Recipe, modifier: Modifier = Modifier) {
Row(
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth().height(45.dp).testTag("General Infos Row")) {
// Recipe time
Spacer(modifier = Modifier.weight(1f))
Icon(
imageVector = Icons.Rounded.AccessTime,
contentDescription = "Time Icon",
modifier = Modifier.testTag("Time Icon"))
Text(
text = recipe.time.toString(),
modifier = Modifier.padding(start = 4.dp).testTag("Text Time"),
style = TextStyle(fontSize = 16.sp, fontWeight = FontWeight.Medium))
// Recipe creator's userId
Spacer(modifier = Modifier.weight(1f))
Text(
text = "By user ",
textAlign = TextAlign.Center,
style = TextStyle(fontSize = 16.sp, fontWeight = FontWeight.Medium))
Text(
text = recipe.userid,
textAlign = TextAlign.Center,
color = BlueUser,
style = TextStyle(fontSize = 16.sp, fontWeight = FontWeight.Medium))
Spacer(modifier = Modifier.weight(1f))
// Recipe rating
Icon(
imageVector = Icons.Rounded.Star,
contentDescription = "Rating Icon",
tint = YellowStar,
modifier = Modifier.testTag("Rating Icon"))
Text(
text = recipe.rating.toString(),
modifier = Modifier.padding(start = 4.dp).testTag("Text Rating"),
style = TextStyle(fontSize = 16.sp, fontWeight = FontWeight.Medium))
Spacer(modifier = Modifier.weight(1f))
}
HorizontalDivider(thickness = 2.dp, modifier = Modifier.testTag("Horizontal Divider 1"))
}
/**
* Displays the title for the ingredients section.
*
* @param modifier The [Modifier] for the text layout.
*/
@Composable
fun IngredientTitleDisplay(modifier: Modifier = Modifier) {
Text(
text = "Ingredients",
style = TextStyle(fontWeight = FontWeight.SemiBold, fontSize = 20.sp),
modifier = modifier.padding(start = 16.dp, top = 8.dp).testTag("Ingredient Title"))
}
/**
* Displays an ingredient with its quantity, measure, and name. Each ingredient is displayed as a
* text with a bullet point at the beginning.
*
* @param ingredient The [IngredientMetaData] to display.
* @param modifier The [Modifier] for the text layout.
*/
@Composable
fun IngredientDisplay(ingredient: IngredientMetaData, modifier: Modifier = Modifier) {
val bullet = "\u2022" // Bullet point unicode character
val ingredientText = "${ingredient.quantity} ${ingredient.measure} ${ingredient.ingredient.name}"
Text(
text =
buildAnnotatedString {
pushStyle(SpanStyle(fontWeight = FontWeight(1000)))
append(bullet)
append(" ")
pop()
append(ingredientText)
},
style = TextStyle(fontWeight = FontWeight.Normal, fontSize = 14.sp),
modifier = modifier.padding(top = 10.dp, start = 16.dp).testTag("Ingredient Description"))
}
/**
* Displays a horizontal divider to separate ingredient and step sections.
*
* @param modifier The [Modifier] for the divider layout.
*/
@Composable
fun IngredientStepsDividerDisplay(modifier: Modifier = Modifier) {
HorizontalDivider(
thickness = 2.dp,
modifier = modifier.padding(top = 8.dp, bottom = 8.dp).testTag("Horizontal Divider 2"))
}
/**
* Displays a [Step] of a [Recipe], including its number, title, and description.
*
* @param step The [Step] to display.
* @param modifier The [Modifier] for the column (containing description) layout.
*/
@Composable
fun StepDisplay(step: Step, modifier: Modifier = Modifier) {
// Step title
Text(
"Step ${step.stepNumber}: ${step.title}",
style = TextStyle(fontWeight = FontWeight.SemiBold, fontSize = 20.sp),
modifier = Modifier.padding(start = 16.dp, bottom = 8.dp).testTag("Step Title"))
Column(modifier = modifier) {
Text(
text = step.description,
style = MaterialTheme.typography.bodyMedium,
modifier =
modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp).testTag("Step Description"),
textAlign = TextAlign.Justify)
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/home/RecipeFullDisplay.kt | 3626464566 |
package com.android.feedme.ui.auth
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
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.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.android.feedme.R
import com.android.feedme.model.viewmodel.AuthViewModel
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import kotlinx.coroutines.launch
/**
* A composable function representing the login screen.
*
* This function provides a UI for users to sign in with Google authentication. It includes a Google
* sign-in button and handles authentication flow using Firebase authentication.
*
* @param navigationActions : the nav actions given in the MainActivity
*/
@Composable
fun LoginScreen(navigationActions: NavigationActions, authViewModel: AuthViewModel = viewModel()) {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
// Configuration for Google Sign-In
val gso =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.default_web_client_id))
.requestEmail()
.build()
val googleSignInClient = GoogleSignIn.getClient(context, gso)
// Activity Result Launcher for Google Sign-In
val googleSignInLauncher =
rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult(),
onResult = { result ->
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
try {
val account = task.getResult(ApiException::class.java)
account?.idToken?.let { idToken ->
coroutineScope.launch {
authViewModel.authenticateWithGoogle(
idToken = idToken,
onSuccess = {
navigationActions.navigateTo(TOP_LEVEL_DESTINATIONS[0])
// Navigate to next screen or show success message
},
onFailure = { exception ->
// Log error or show error message
Log.e("LoginScreen", "Authentication failed", exception)
})
}
}
} catch (e: ApiException) {
// Handle API exception
Log.e("LoginScreen", "Sign in failed", e)
}
})
Column(
modifier = Modifier.fillMaxSize().padding(16.dp).testTag("LoginScreen"),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally) {
Image(
painter = painterResource(id = R.drawable.sign_in_logo),
contentDescription = "Sign-in Logo",
modifier = Modifier.width(189.dp).height(189.dp),
contentScale = ContentScale.FillBounds)
Spacer(modifier = Modifier.height(40.dp))
Text(
text = "Welcome",
modifier = Modifier.testTag("LoginTitle"),
// M3/display/large
style =
TextStyle(
fontSize = 57.sp,
lineHeight = 64.sp,
fontWeight = FontWeight(400),
color = Color(0xFF191C1E),
textAlign = TextAlign.Center,
))
Spacer(modifier = Modifier.height(176.dp))
Button(
onClick = {
if (Testing.isTestMode) {
Testing.mockSuccessfulLogin()
navigationActions.navigateTo(Route.HOME)
} else {
googleSignInLauncher.launch(googleSignInClient.signInIntent)
}
},
modifier =
Modifier.width(250.dp)
.height(40.dp)
.background(color = Color(0xFFFFFFFF), shape = RoundedCornerShape(size = 20.dp))
.testTag("LoginButton"),
colors = ButtonDefaults.buttonColors(Color.White),
contentPadding = PaddingValues(2.dp),
shape = RoundedCornerShape(20.dp),
border = BorderStroke(2.dp, Color(0xFFDADCE0))) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
// Replace R.drawable.ic_google_logo with the actual resource ID for
// the Google logo
Image(
painter = painterResource(id = R.drawable.google_logo),
contentDescription = null, // Provide a meaningful content description
modifier = Modifier.size(24.dp))
Spacer(modifier = Modifier.width(4.dp))
Text(
modifier = Modifier.width(125.dp).height(17.dp),
text = "Sign In with Google",
fontSize = 14.sp,
lineHeight = 17.sp,
fontWeight = FontWeight(500),
color = Color(0xFF3C4043),
textAlign = TextAlign.Center,
letterSpacing = 0.25.sp,
)
}
}
}
}
/** A function to set the test mode for the app. */
fun setTestMode(bool: Boolean) {
Testing.isTestMode = bool
}
/**
* A function to set the mocking for successful login.
*
* @param mockingSuccessfulLogin : a lambda function to mock successful login
*/
fun setLoginMockingForTests(mockingSuccessfulLogin: () -> Unit) {
Testing.mockSuccessfulLogin = mockingSuccessfulLogin
}
/** A testing object to set the test mode and mock successful login. */
object Testing {
var isTestMode = false
var mockSuccessfulLogin = {}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/auth/LoginScreen.kt | 2385644943 |
package com.android.feedme.ui.camera
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Matrix
import android.util.Log
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.view.CameraController
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
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.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Photo
import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.android.feedme.model.viewmodel.CameraViewModel
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.TopBarNavigation
import kotlinx.coroutines.launch
/**
* A composable function representing the camera screen.
*
* This function displays a UI for camera functionality, allowing users to capture photos. It
* manages camera permissions, sets up a live camera preview, and includes UI elements for capturing
* images and viewing them in a gallery. Utilizes CameraX for camera operations and Jetpack Compose
* for the UI components.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CameraScreen(navigationActions: NavigationActions) {
val applicationContext = LocalContext.current
// Request camera permission if not already granted
if (!hasRequiredPermissions(applicationContext)) {
ActivityCompat.requestPermissions(
applicationContext as Activity, arrayOf(Manifest.permission.CAMERA), 0)
}
// Set up the camera controller, view model, and coroutine scope
val scope = rememberCoroutineScope()
val scaffoldState = rememberBottomSheetScaffoldState()
val controller = remember {
LifecycleCameraController(applicationContext).apply {
setEnabledUseCases(CameraController.IMAGE_CAPTURE)
}
}
val viewModel = viewModel<CameraViewModel>()
val bitmaps by viewModel.bitmaps.collectAsState()
val photoSavedMessageVisible by viewModel.photoSavedMessageVisible.collectAsState()
BottomSheetScaffold(
modifier = Modifier.testTag("CameraScreen"),
topBar = { TopBarNavigation(title = "Camera", navigationActions, null) },
scaffoldState = scaffoldState,
sheetPeekHeight = 0.dp,
sheetContent = {
PhotoBottomSheetContent(bitmaps = bitmaps, modifier = Modifier.fillMaxWidth())
}) { padding ->
Box(modifier = Modifier.fillMaxSize().padding(padding)) {
CameraPreview(controller = controller, modifier = Modifier.fillMaxSize())
Row(
modifier = Modifier.fillMaxWidth().align(Alignment.BottomCenter).padding(16.dp),
horizontalArrangement = Arrangement.SpaceAround) {
IconButton(
modifier = Modifier.testTag("GalleryButton"),
// Open the local gallery when the gallery button is clicked
onClick = { scope.launch { scaffoldState.bottomSheetState.expand() } }) {
Icon(imageVector = Icons.Default.Photo, contentDescription = "Open gallery")
}
IconButton(
modifier = Modifier.testTag("PhotoButton"),
// Take a photo when the photo button is clicked
onClick = {
takePhoto(
controller = controller,
onPhotoTaken = viewModel::onTakePhoto,
showText = viewModel::onPhotoSaved,
context = applicationContext)
}) {
Icon(
imageVector = Icons.Default.PhotoCamera,
contentDescription = "Take photo")
}
}
// Show the message box if the photo was taken
if (photoSavedMessageVisible) {
Log.d("CameraScreen", "Photo saved message visible")
// Show the message box
Box(
modifier =
Modifier.padding(16.dp)
.background(
Color.Black.copy(alpha = 0.7f), shape = RoundedCornerShape(8.dp))
.padding(horizontal = 24.dp, vertical = 16.dp)
.align(Alignment.BottomCenter)) {
Text(
text = "Photo saved",
color = Color.White,
modifier = Modifier.testTag("PhotoSavedMessage"))
}
}
}
}
}
/** Create a new [LifecycleCameraController] to control the camera. */
fun takePhoto(
controller: LifecycleCameraController,
onPhotoTaken: (Bitmap) -> Unit,
showText: () -> Unit,
context: Context
) {
controller.takePicture(
ContextCompat.getMainExecutor(context),
object : ImageCapture.OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
super.onCaptureSuccess(image)
// Rotate the image to match the device's orientation
val matrix = Matrix().apply { postRotate(image.imageInfo.rotationDegrees.toFloat()) }
val rotatedBitmap =
Bitmap.createBitmap(image.toBitmap(), 0, 0, image.width, image.height, matrix, true)
onPhotoTaken(rotatedBitmap)
showText()
}
// Log an error if the photo couldn't be taken
override fun onError(exception: ImageCaptureException) {
super.onError(exception)
Log.e("Camera", "Couldn't take photo: ", exception)
}
})
}
/** Check if the app has the required permissions to use the camera. */
fun hasRequiredPermissions(context: Context): Boolean {
return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
}
/** Composable that displays the camera preview. */
@Composable
fun CameraPreview(controller: LifecycleCameraController, modifier: Modifier = Modifier) {
val lifecycleOwner = LocalLifecycleOwner.current
// Display the camera preview using the CameraX PreviewView
AndroidView(
factory = {
PreviewView(it).apply {
this.controller = controller
controller.bindToLifecycle(lifecycleOwner)
}
},
modifier = modifier.testTag("CameraPreview"))
}
@Composable
fun PhotoBottomSheetContent(bitmaps: List<Bitmap>, modifier: Modifier = Modifier) {
// Show a message if there are no photos
if (bitmaps.isEmpty()) {
Box(modifier = modifier.padding(16.dp), contentAlignment = Alignment.Center) {
Text(text = "There are no photos yet")
}
} else {
// Display the photos in a grid
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Fixed(2),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalItemSpacing = 16.dp,
contentPadding = PaddingValues(16.dp),
modifier = modifier) {
items(bitmaps) { bitmap ->
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Photo",
modifier = Modifier.clip(RoundedCornerShape(10.dp)))
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/camera/Camera.kt | 2757932150 |
package com.android.feedme.ui.navigation
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
/**
* Displays a bottom navigation bar with tabs based on provided destinations.
*
* This composable function creates a bottom navigation menu, marking the current selection and
* handling tab selection changes. It dynamically generates navigation tabs from a list of top-level
* destinations, providing a consistent navigation experience.
*
* @param selectedItem The ID of the currently active tab.
* @param onTabSelect Callback for handling tab selection changes.
* @param tabList List of top-level destinations for tab creation.
*/
@Composable
fun BottomNavigationMenu(
selectedItem: String,
onTabSelect: (TopLevelDestination) -> Unit,
tabList: List<TopLevelDestination>,
) {
NavigationBar(modifier = Modifier.testTag("BottomNavigationMenu")) {
tabList.forEach { replyDestination ->
NavigationBarItem(
selected = selectedItem == replyDestination.route,
onClick = { onTabSelect(replyDestination) },
icon = {
Icon(imageVector = replyDestination.icon, contentDescription = replyDestination.textId)
},
label = { Text(replyDestination.textId) },
modifier = Modifier.testTag(replyDestination.textId))
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/navigation/BottomNavigationMenu.kt | 519030974 |
package com.android.feedme.ui.navigation
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
/**
* Handles navigation within an app's composable navigation graph.
*
* Utilizes a `NavHostController` to perform navigation actions, offering methods to navigate to
* various app destinations with enhanced features like state preservation and avoiding duplicate
* destinations in the stack.
*
* @param navController The controller managing app navigation.
*/
class NavigationActions(private val navController: NavHostController) {
/**
* Navigates to the specified [TopLevelDestination] destination.
*
* @param destination The top level destination to navigate to.
*/
fun navigateTo(destination: TopLevelDestination) {
navController.navigate(destination.route) {
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
inclusive = true
}
// Avoid multiple copies of the same destination when reselecting same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
}
/**
* Navigates to the specified route.
*
* @param subRoute The route to navigate to.
*/
fun navigateTo(subRoute: String) {
// When calling this method, the back bottom would be available to go back using goBack()
navController.navigate(subRoute)
}
/** Navigates back to the previous destination in the navigation stack. */
fun goBack() {
navController.popBackStack()
}
/**
* Checks if there is a previous destination in the navigation stack that the app can navigate
* back to.
*
* @return True if there is a previous destination to navigate back to, false otherwise.
*/
fun canGoBack(): Boolean {
return navController.previousBackStackEntry != null
}
}
/** Contains route constants used for navigating within the app's top destinations */
object Route {
const val AUTHENTICATION = "Authentication"
const val HOME = "Home"
const val EXPLORE = "Explore"
const val CREATE = "Create"
const val PROFILE = "Profile"
const val SETTINGS = "Settings"
}
/** Contains sub-route constants used for navigating within the app's screens */
object Screen {
const val AUTHENTICATION = "Authentication Screen"
const val HOME = "Home Screen"
const val EXPLORE = "Explore Screen"
const val CREATE = "Create Screen"
const val PROFILE = "Profile/{profileId}"
const val SETTINGS = "Settings Screen"
const val CAMERA = "Camera"
const val EDIT_PROFILE = "Edit Profile"
const val FRIENDS = "Friends/{showFollowers}"
const val RECIPE = "Recipe/{recipeId}"
}
/**
* Represents a top-level destination within the app navigation.
*
* @property route The route associated with the destination.
* @property icon The icon associated with the destination.
* @property textId The resource ID of the text associated with the destination.
*/
data class TopLevelDestination(val route: String, val icon: ImageVector, val textId: String)
/** List of top-level destinations within the app navigation. */
val TOP_LEVEL_DESTINATIONS =
listOf(
TopLevelDestination(route = Route.HOME, icon = Icons.Default.Home, textId = "Home"),
TopLevelDestination(route = Route.EXPLORE, icon = Icons.Default.Search, textId = "Explore"),
TopLevelDestination(route = Route.CREATE, icon = Icons.Default.Add, textId = "Create"),
TopLevelDestination(
route = Route.PROFILE, icon = Icons.Default.AccountCircle, textId = "Profile"),
TopLevelDestination(
route = Route.SETTINGS, icon = Icons.Default.Settings, textId = "Settings"))
| feedme-android/app/src/main/java/com/android/feedme/ui/navigation/NavigationActions.kt | 1155703731 |
package com.android.feedme.ui.navigation
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.android.feedme.ui.theme.TemplateColor
import com.android.feedme.ui.theme.TextBarColor
/**
* TopBarNavigation is a composable function used to display a top navigation bar. The left icon
* (which is a back arrow) will appear only if the navAction can pop back; otherwise, it won't be
* displayed, even if it isn't null.
*
* @param title The title text to be displayed in the center of the top bar.
* @param navAction The navigation action instance for handling back navigation. Default is null.
* @param rightIcon The icon to be displayed on the right side of the top bar. Default is null.
* @param rightIconOnClickAction The action to be performed when the right icon is clicked. Default
* is Unit. No action is taken if rightIcon is null.
*/
@Composable
fun TopBarNavigation(
title: String,
navAction: NavigationActions? = null,
rightIcon: ImageVector? = null,
rightIconOnClickAction: (() -> Unit) = {}
) {
Box(
modifier =
Modifier.fillMaxWidth()
.height(60.dp)
.testTag("TopBarNavigation")
.background(TemplateColor),
contentAlignment = Alignment.Center) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically) {
// LeftIconBox
Box(
modifier = Modifier.weight(1f).testTag("LeftIconBox"),
contentAlignment = Alignment.CenterStart) {
if (navAction != null && navAction.canGoBack()) {
IconButton(
modifier = Modifier.testTag("LeftIconButton"),
onClick = { navAction.goBack() },
) {
Icon(
modifier = Modifier.testTag("LeftIcon"),
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "BackArrow",
tint = TextBarColor)
}
}
}
// TitleBox
Box(
modifier = Modifier.weight(1f).testTag("TitleBox"),
contentAlignment = Alignment.Center) {
Text(
modifier = Modifier.testTag("TitleText"),
text = title,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = TextBarColor,
textAlign = TextAlign.Center)
}
// RightIconBox
Box(
modifier = Modifier.weight(1f).testTag("RightIconBox"),
contentAlignment = Alignment.CenterEnd) {
if (rightIcon != null) {
IconButton(
onClick = { rightIconOnClickAction },
modifier = Modifier.testTag("RightIconButton")) {
Icon(
modifier = Modifier.testTag("RightIcon"),
imageVector = rightIcon,
contentDescription = "Right Icon",
tint = TextBarColor)
}
}
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/navigation/TopBarNavigation.kt | 4119218535 |
package com.android.feedme.ui.component
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.movableContentOf
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
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.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import com.android.feedme.model.data.Ingredient
import com.android.feedme.model.data.IngredientMetaData
import com.android.feedme.model.data.MeasureUnit
import com.android.feedme.ui.theme.InValidInput
import com.android.feedme.ui.theme.NoInput
import com.android.feedme.ui.theme.ValidInput
/**
* Composable function for displaying a list of ingredients.
*
* @param modifier the modifier for this composable.
* @param list the list of [IngredientMetaData] items to display. Default is null.
*/
@Composable
fun IngredientList(
modifier: Modifier = Modifier,
list: MutableList<IngredientMetaData>? = null,
) {
val totalIngredients = remember { mutableIntStateOf(1 + (list?.size ?: 0)) }
val listOfIngredients = remember { mutableStateListOf<IngredientMetaData?>() }
// If (totalCompleteIngredients == totalIngredients - 1) then all ingredients are Complete
val totalCompleteIngredients = remember { mutableIntStateOf(0) }
list?.let { listOfIngredients.addAll(it) }
listOfIngredients.add(null)
LazyColumn(modifier = modifier.testTag("LazyList")) {
this.items(totalIngredients.intValue) { index ->
val movableContent = movableContentOf {
IngredientInput(listOfIngredients[index]) { before, now, newIngredient ->
if (now != IngredientInputState.COMPLETE && before == IngredientInputState.COMPLETE) {
listOfIngredients[index] = newIngredient
totalCompleteIngredients.intValue -= 1
}
if (now == IngredientInputState.COMPLETE &&
before == IngredientInputState.SEMI_COMPLETE) {
listOfIngredients[index] = newIngredient
totalCompleteIngredients.intValue += 1
}
if (now == IngredientInputState.SEMI_COMPLETE &&
before == IngredientInputState.SEMI_COMPLETE) {
listOfIngredients[index] = newIngredient
}
if (now == IngredientInputState.SEMI_COMPLETE && before == IngredientInputState.EMPTY) {
listOfIngredients[index] = newIngredient
listOfIngredients.add(null)
totalIngredients.intValue += 1
}
if (now == IngredientInputState.EMPTY && before != IngredientInputState.EMPTY) {
listOfIngredients.removeAt(index)
totalIngredients.intValue -= 1
}
}
}
movableContent()
}
}
}
/**
* Composable function for displaying an input field for ingredient details.
*
* @param ingredient the [IngredientMetaData] to display in the input fields.
* @param action the action to perform on input changes.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun IngredientInput(
ingredient: IngredientMetaData? = null,
action: (IngredientInputState?, IngredientInputState?, IngredientMetaData?) -> Unit
) {
var name by remember { mutableStateOf(ingredient?.ingredient?.name ?: " ") }
var quantity by remember { mutableDoubleStateOf(ingredient?.quantity ?: 0.0) }
var dose by remember { mutableStateOf(ingredient?.measure ?: MeasureUnit.EMPTY) }
val isComplete by remember {
mutableStateOf(name.isNotBlank() && dose != MeasureUnit.EMPTY && quantity != 0.0)
}
var state by remember {
mutableStateOf(
if (isComplete) IngredientInputState.COMPLETE
else if (ingredient != null) IngredientInputState.SEMI_COMPLETE
else IngredientInputState.EMPTY)
}
var isDropdownVisible by remember { mutableStateOf(false) }
val suggestionIngredients =
listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5") // Your list of items
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp).height(70.dp),
verticalAlignment = Alignment.CenterVertically) {
// Ingredients Box
Box(modifier = Modifier.weight(1.5f).height(60.dp).testTag("IngredientsBox")) {
OutlinedTextField(
colors = colorOfInputBoxes(state),
value = name,
isError = name == " " && state != IngredientInputState.EMPTY,
onValueChange = {
name = it
isDropdownVisible = true
},
singleLine = true,
modifier = Modifier.padding(end = 0.dp).testTag("IngredientsInput"),
placeholder = { Text(text = "...") },
label = {
Text(text = "Ingredient", modifier = Modifier.background(color = Color.Transparent))
})
DropdownMenu(
modifier = Modifier.height(120.dp),
expanded = isDropdownVisible && name.isNotEmpty(),
onDismissRequest = { isDropdownVisible = false },
properties =
PopupProperties(
focusable = false, dismissOnClickOutside = false, dismissOnBackPress = false),
) {
suggestionIngredients.forEach { item ->
DropdownMenuItem(
modifier = Modifier.testTag("IngredientOption"),
text = { Text(text = item) },
onClick = {
name = item
isDropdownVisible = false
val beforeState = state
if (name != " ") {
state =
if (isComplete) IngredientInputState.COMPLETE
else IngredientInputState.SEMI_COMPLETE
action(
beforeState,
state,
IngredientMetaData(quantity, dose, Ingredient(name, "", "")))
}
})
}
}
}
Spacer(modifier = Modifier.width(8.dp))
// Quantity
OutlinedTextField(
colors = colorOfInputBoxes(state),
isError = quantity == 0.0 && state != IngredientInputState.EMPTY,
value = if (quantity == 0.0) " " else quantity.toString(),
onValueChange = { // Check if the input is a valid number
if (it.isNotEmpty() && it.toDoubleOrNull() != null && it.toDouble() >= 0.0) {
quantity = it.toDouble()
if (quantity != 0.0) {
action(state, state, IngredientMetaData(quantity, dose, Ingredient(name, "", "")))
}
}
},
singleLine = true,
modifier = Modifier.weight(1f).height(60.dp).testTag("QuantityInput"),
placeholder = { Text(text = "...") },
label = {
Text(text = "Quantity", modifier = Modifier.background(color = Color.Transparent))
})
Spacer(modifier = Modifier.width(8.dp))
// Dose
var expanded by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(
modifier = Modifier.weight(1f).height(60.dp).testTag("DoseBox"),
expanded = expanded,
onExpandedChange = { expanded = !expanded }) {
OutlinedTextField(
colors = colorOfInputBoxes(state),
isError = dose == MeasureUnit.EMPTY && state != IngredientInputState.EMPTY,
readOnly = true,
value = if (dose != MeasureUnit.EMPTY) dose.toString() else " ",
onValueChange = {},
label = { Text("Dose") },
modifier = Modifier.menuAnchor().testTag("DoseInput"))
ExposedDropdownMenu(
modifier = Modifier.height(120.dp),
expanded = expanded,
onDismissRequest = { expanded = false }) {
MeasureUnit.values().forEach { selectionOption ->
DropdownMenuItem(
text = { Text(text = selectionOption.toString()) },
onClick = {
dose = selectionOption
expanded = false
if (dose != MeasureUnit.EMPTY) {
val beforeState = state
state =
if (isComplete) IngredientInputState.COMPLETE
else IngredientInputState.SEMI_COMPLETE
action(
beforeState,
state,
IngredientMetaData(quantity, dose, Ingredient(name, "", "")))
}
})
}
}
}
// Delete button for removing the ingredient
if (state == IngredientInputState.SEMI_COMPLETE || state == IngredientInputState.COMPLETE) {
IconButton(
modifier = Modifier.testTag("DeleteIconButton"),
onClick = {
action(
state,
IngredientInputState.EMPTY,
IngredientMetaData(quantity, dose, Ingredient(name, "", "")))
}) {
Icon(
imageVector = Icons.Default.DeleteForever,
contentDescription = null,
modifier = Modifier.size(48.dp).height(55.dp))
}
}
}
}
/**
* Function to determine the colors of input boxes based on input state.
*
* @param state the state of the input.
* @return [TextFieldColors] object representing the colors of input boxes.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun colorOfInputBoxes(state: IngredientInputState): TextFieldColors {
return ExposedDropdownMenuDefaults.textFieldColors(
unfocusedContainerColor = if (state != IngredientInputState.EMPTY) ValidInput else NoInput,
focusedContainerColor = if (state != IngredientInputState.EMPTY) ValidInput else NoInput,
errorContainerColor = InValidInput)
}
/** Enum class representing the state of an ingredient input. */
enum class IngredientInputState {
EMPTY,
SEMI_COMPLETE,
COMPLETE
}
| feedme-android/app/src/main/java/com/android/feedme/ui/component/IngredientList.kt | 2309972376 |
package com.android.feedme.ui.component
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.android.feedme.R
import com.android.feedme.model.data.Comment
import com.android.feedme.ui.theme.BlueUser
/**
* Composable function to display a list of small comments.
*
* This function creates a LazyColumn to display a list of comments on below the other. Each comment
* is displayed using the [CommentCard] composable.
*
* @param listComment The list of [Comment] to be displayed.
*/
@Composable
fun SmallCommentsDisplay(listComment: List<Comment>, modifier: Modifier = Modifier) {
LazyColumn(modifier = modifier) { items(listComment) { item -> CommentCard(comment = item) } }
}
/**
* Composable function to display a single comment.
*
* This function creates a Surface with a Row layout to display a comment. It contains an image
* representing the commenter, along with the author's name, the comment's title, and the comment's
* content.
*
* @param comment The [Comment] object to be displayed.
*/
@Composable
fun CommentCard(comment: Comment) {
Surface(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
color = Color.White,
shape = RoundedCornerShape(8.dp),
border = BorderStroke(2.dp, Color.Black)) {
Row(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
// Recipe image
Image(
painter = painterResource(id = R.drawable.test_image_pasta),
contentDescription = "Recipe Image",
modifier = Modifier.size(100.dp).aspectRatio(1f).clip(RoundedCornerShape(8.dp)),
contentScale = ContentScale.Crop)
Spacer(modifier = Modifier.width(10.dp))
// Author + title + description
Column(
modifier =
Modifier.fillMaxWidth()
.padding(start = 16.dp)
.align(Alignment.CenterVertically)) {
// Comment authorId
Text(
text = comment.authorId,
style = MaterialTheme.typography.bodyMedium,
color = BlueUser,
fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.height(8.dp))
// Comment title
Text(
text = comment.title,
style = MaterialTheme.typography.titleLarge,
maxLines = 2,
overflow = TextOverflow.Ellipsis)
Spacer(modifier = Modifier.height(8.dp))
// Comment description
Text(
text = comment.content,
style = MaterialTheme.typography.bodyMedium,
maxLines = 3,
overflow = TextOverflow.Ellipsis)
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/component/SmallCommentsDisplay.kt | 1895399308 |
package com.android.feedme.ui.component
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.SearchBar
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
/**
* Composable function for the Search Bar.
*
* This function displays the search bar on both the landing and saved pages.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchBarFun() {
var query by remember { mutableStateOf("") }
var active by remember { mutableStateOf(false) }
// Search bar + filters icon
Row(modifier = Modifier.background(Color.White), verticalAlignment = Alignment.CenterVertically) {
SearchBar(
query = query,
active = active,
onActiveChange = { active = it },
onQueryChange = { query = it },
onSearch = {
active = false
/* TODO() add filtering logic here */
},
leadingIcon = {
Icon(
Icons.Default.Menu,
"Menu Icon",
modifier = Modifier.testTag("FilterClick").clickable {})
},
trailingIcon = {
if (active) {
Icon(
modifier =
Modifier.clickable {
query = ""
active = false
/* TODO() add filtering logic here */
},
imageVector = Icons.Default.Close,
contentDescription = "Close Icon")
} else {
Icon(Icons.Default.Search, contentDescription = "Search Icon")
}
},
placeholder = { Text("Search Recipe") },
modifier = Modifier.fillMaxWidth().padding(10.dp).height(50.dp).testTag("SearchBar")) {}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/component/SearchBar.kt | 3349426348 |
package com.android.feedme.ui.component
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.twotone.Star
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.android.feedme.model.data.Recipe
import com.android.feedme.ui.theme.YellowStar
/**
* Composable function to display a list of recipes as small thumbnails with additional information.
* Each thumbnail includes an image, rating, cooking time, and title. Thumbnails are displayed two
* by two in a column. If the image couldn't be downloaded from internet a message is displayed
* instead.
*
* @param listRecipe List of Recipe objects to be displayed.
*/
@Composable
fun SmallThumbnailsDisplay(listRecipe: List<Recipe>) {
// Calculate the width of each image based on the screen width
val NB_IMAGE_PER_LINE = 2
val IMAGE_WIDTH = LocalConfiguration.current.screenWidthDp / NB_IMAGE_PER_LINE
var ImageSuccessfulDownload = remember { mutableStateOf(false) }
LazyVerticalGrid(columns = GridCells.Adaptive(minSize = IMAGE_WIDTH.dp)) {
items(listRecipe.size) { i ->
Column(
horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(3.dp)) {
// Recipe photo, downloaded from internet
AsyncImage(
model = listRecipe[i].imageUrl,
contentDescription = "Recipe Image",
modifier = Modifier.testTag("Recipe Image"),
onSuccess = { ImageSuccessfulDownload.value = true })
// Display a warning message if image couldn't be downloaded from internets
if (!ImageSuccessfulDownload.value) {
Text("Failed to download image", modifier = Modifier.testTag("Fail Image Download"))
}
Row(verticalAlignment = Alignment.CenterVertically) {
// Star icon for ratings
Icon(
imageVector = Icons.TwoTone.Star,
contentDescription = "Star Icon",
tint = YellowStar,
modifier = Modifier.padding(end = 3.dp))
// Recipe rating
Text(listRecipe[i].rating.toString(), modifier = Modifier.padding(end = 10.dp))
// Clock icon for the time
// There is no clock icon in Material, so for now i'm using the "build" icon
Icon(
imageVector = Icons.Outlined.Info,
contentDescription = "Info Icon",
modifier = Modifier.padding(end = 3.dp))
// Recipe time
Text(listRecipe[i].time.toString(), modifier = Modifier.padding(end = 45.dp))
// Save button, to keep the recipe accessible even offline
// There is no save icon in Material, so for now i'm using the "build" icon
IconButton(onClick = { /*TODO call to the database function for saving recipes*/}) {
Icon(imageVector = Icons.Outlined.Build, contentDescription = "Save Icon")
}
}
// Recipe Title
Text(text = listRecipe[i].title)
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/component/SmallTumbnailsDisplay.kt | 3179224770 |
package com.android.feedme.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import com.android.feedme.ui.navigation.BottomNavigationMenu
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.android.feedme.ui.navigation.TopBarNavigation
/**
* Screen that is displayed when a feature is not implemented.
*
* @param navigationActions The navigation actions instance for handling back navigation.
*/
@Composable
fun NotImplementedScreen(navigationActions: NavigationActions, selectedItem: String) {
Scaffold(
modifier = Modifier.testTag("NotImplementedScreen"),
topBar = { TopBarNavigation(title = "Not Implemented", navAction = null) },
bottomBar = {
BottomNavigationMenu(
selectedItem = selectedItem,
onTabSelect = navigationActions::navigateTo,
tabList = TOP_LEVEL_DESTINATIONS)
},
content = { paddingValues ->
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().padding(paddingValues)) {
Text(
text = "This feature is not implemented yet. Please check back later.",
modifier = Modifier.padding(20.dp).testTag("Text"))
}
})
}
| feedme-android/app/src/main/java/com/android/feedme/ui/NotImplementedScreen.kt | 1394825717 |
package com.android.feedme.ui.profile
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.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.android.feedme.R
import com.android.feedme.model.data.Profile
import com.android.feedme.model.viewmodel.ProfileViewModel
import com.android.feedme.ui.navigation.BottomNavigationMenu
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.android.feedme.ui.navigation.TopBarNavigation
val demoProfiles =
listOf(
Profile(
id = "1",
name = "John Doe",
username = "john_doe",
imageUrl = "https://example.com/image1.jpg"),
Profile(
id = "2",
name = "Jane Smith",
username = "jane_smith",
imageUrl = "https://example.com/image2.jpg"))
val demoProfiles2 =
listOf(
Profile(
id = "1",
name = "Michel Doe",
username = "john_doe",
imageUrl = "https://example.com/image3.jpg"),
Profile(
id = "2",
name = "Michel Smith",
username = "jane_smith",
imageUrl = "https://example.com/image4.jpg"),
// Generate more profile
)
/**
* Composable that displays either a list of followers or following based on the selected tab. It
* includes a tabbed interface to switch between the "Followers" and "Following" lists.
*
* @param navigationActions Provides navigation actions for handling user interactions with the
* navigation bar.
* @param profileViewModel The view model that provides the profile data.
* @param mode Determines the initial tab selection: 0 for Followers, 1 for Following, 4242 for
* testing.
*/
@Composable
fun FriendsScreen(
navigationActions: NavigationActions,
profileViewModel: ProfileViewModel = ProfileViewModel(),
mode: Int = 0,
) {
var selectedTabIndex by remember { mutableIntStateOf(mode) }
val tabTitles = listOf("Followers", "Following")
// Now, collect followers and following as state to display them
val followers =
if (mode == 4242 || profileViewModel.isViewingProfile())
profileViewModel.viewingUserFollowers.collectAsState()
else profileViewModel.currentUserFollowers.collectAsState()
val following =
if (mode == 4242 || profileViewModel.isViewingProfile())
profileViewModel.viewingUserFollowing.collectAsState()
else profileViewModel.currentUserFollowing.collectAsState()
if (selectedTabIndex == 4242) selectedTabIndex = 0
Scaffold(
modifier = Modifier.fillMaxSize().testTag("FriendsScreen"),
topBar = { TopBarNavigation(title = "Friends", navigationActions, null) },
bottomBar = {
BottomNavigationMenu(
Route.PROFILE,
{ top ->
profileViewModel.removeViewingProfile()
navigationActions.navigateTo(top)
},
TOP_LEVEL_DESTINATIONS)
},
content = { innerPadding ->
Column(modifier = Modifier.padding(innerPadding)) {
TabRow(
selectedTabIndex = selectedTabIndex,
containerColor = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface) {
tabTitles.forEachIndexed { index, title ->
Tab(
text = { Text(title) },
selected = selectedTabIndex == index,
onClick = { selectedTabIndex = index },
modifier =
Modifier.testTag(if (index == 0) "TabFollowers" else "TabFollowing"))
}
}
when (selectedTabIndex) {
0 ->
FollowersList(followers.value, "FollowersList", navigationActions, profileViewModel)
1 ->
FollowersList(following.value, "FollowingList", navigationActions, profileViewModel)
}
}
})
}
/**
* Displays a lazy scrolling list of user profiles.
*
* @param profiles The list of profiles to be displayed.
* @param tag A testing tag used for UI tests to identify the list view.
*/
@Composable
fun FollowersList(
profiles: List<Profile>,
tag: String,
navigationActions: NavigationActions,
profileViewModel: ProfileViewModel
) {
LazyColumn(modifier = Modifier.fillMaxSize().testTag(tag)) {
items(profiles) { profile ->
FollowerCard(profile = profile, navigationActions, profileViewModel)
}
}
}
/**
* A card representation for a user profile, displaying the user's picture, name, and username. It
* also provides a 'Remove' button and an options menu for further actions.
*
* @param profile The profile data of the user.
*/
@Composable
fun FollowerCard(
profile: Profile,
navigationActions: NavigationActions,
profileViewModel: ProfileViewModel
) {
Card(
modifier =
Modifier.padding(4.dp)
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.5f))
.testTag("FollowerCard") // Applying a semi-transparent background
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier =
Modifier.fillMaxWidth().clickable {
/*TODO Navigate to profile view of follower*/
profileViewModel.setViewingProfile(profile)
navigationActions.navigateTo(Route.PROFILE + "/" + profile.id)
}) {
Image(
painter =
painterResource(
id =
R.drawable
.user_logo), // Assuming google_logo is your default profile icon
contentDescription = "Profile Image",
modifier = Modifier.padding(horizontal = 10.dp).size(50.dp).clip(CircleShape),
)
Column(modifier = Modifier.padding(10.dp).weight(1f)) {
Text(text = profile.name, fontSize = 14.sp)
Text(
text = "@" + profile.username,
fontSize = 10.sp,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f))
}
Spacer(modifier = Modifier.weight(0.1f))
Box(modifier = Modifier.align(Alignment.CenterVertically)) {
Row {
Button(
onClick = { /* TODO: Implement action */},
Modifier.padding(top = 4.dp, bottom = 4.dp, end = 0.dp)) {
Text(text = "Remove")
}
IconButton(onClick = { /* TODO: Implement action */}) {
Icon(imageVector = Icons.Filled.MoreVert, contentDescription = "Options")
}
}
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/profile/FriendsScreen.kt | 2164336795 |
package com.android.feedme.ui.profile
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.platform.testTag
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.android.feedme.model.data.Profile
import com.android.feedme.model.viewmodel.ProfileViewModel
import com.android.feedme.ui.navigation.BottomNavigationMenu
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.android.feedme.ui.navigation.TopBarNavigation
/**
* Composable function that provides the main screen layout for editing a user's profile.
*
* This function sets up the Scaffold layout which includes a top bar, bottom navigation, and the
* content for editing the profile, handled by [EditProfileContent].
*
* @param navigationActions A set of actions to handle navigation events.
* @param profileViewModel The ViewModel that handles fetching and updating the user's profile data.
*/
@Composable
fun EditProfileScreen(navigationActions: NavigationActions, profileViewModel: ProfileViewModel) {
Scaffold(
modifier = Modifier.fillMaxSize().testTag("EditProfileScreen"),
topBar = { TopBarNavigation(title = "Edit Profile", navigationActions) },
bottomBar = {
BottomNavigationMenu(Route.PROFILE, navigationActions::navigateTo, TOP_LEVEL_DESTINATIONS)
},
content = { padding -> EditProfileContent(padding, profileViewModel, navigationActions) },
)
}
/**
* Composable function that displays and manages the profile editing form.
*
* This function creates a form where users can edit their profile details such as name, username,
* and bio. The form validates inputs and shows errors when necessary. It allows the user to save
* the changes which updates the profile information in the backend via the [profileViewModel].
*
* @param padding The padding to apply around the content area defined by the Scaffold in
* [EditProfileScreen].
* @param profileViewModel ViewModel that contains the logic for loading and saving the user's
* profile.
* @param navigationActions Actions to handle navigation based on user interaction.
*/
@Composable
fun EditProfileContent(
padding: PaddingValues,
profileViewModel: ProfileViewModel,
navigationActions: NavigationActions
) {
val profile = profileViewModel.currentUserProfile.collectAsState().value ?: Profile()
var name by remember { mutableStateOf(profile.name) }
var username by remember { mutableStateOf(profile.username) }
var bio by remember { mutableStateOf(profile.description) }
var nameError by remember { mutableStateOf<String?>(null) }
var usernameError by remember { mutableStateOf<String?>(null) }
var bioError by remember { mutableStateOf<String?>(null) }
val minNameSize = 3
val maxNameSize = 15
val bioMaxSize = 100
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier =
Modifier.padding(24.dp).padding(padding).fillMaxSize().testTag("EditProfileContent")) {
Column(
modifier =
Modifier.padding(bottom = 20.dp, top = 20.dp).testTag("Edit_Picture").clickable {
// TODO: Implement image picker
},
) {
UserProfilePicture()
Text(
text = "Edit Picture",
style = TextStyle(fontSize = 16.sp),
modifier = Modifier.padding(top = 8.dp))
}
OutlinedTextField(
value = name,
onValueChange = {
name = it
nameError =
when {
it.isBlank() -> "Name cannot be empty"
it.length < minNameSize -> "Name must be at least $minNameSize characters"
it.length > maxNameSize -> "Name must be no more than $maxNameSize characters"
else -> null
}
},
label = { Text("Name") },
isError = nameError != null,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp).testTag("NameInput"))
if (nameError != null) {
Text(
nameError!!,
color = MaterialTheme.colorScheme.error,
style = TextStyle(fontSize = 12.sp),
modifier = Modifier.testTag("NameError"))
}
OutlinedTextField(
value = username,
onValueChange = {
username = it
usernameError =
when {
it.isBlank() -> "Username cannot be empty"
it.contains(" ") -> "Username cannot contain spaces"
!it.matches("^[\\w_]*$".toRegex()) ->
"Username must be alphanumeric or underscores"
it.length < minNameSize -> "Username must be at least $minNameSize characters"
it.length > maxNameSize ->
"Username must be no more than $maxNameSize characters"
else -> null
}
},
label = { Text("Username") },
isError = usernameError != null,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp).testTag("UsernameInput"))
if (usernameError != null) {
Text(
usernameError!!,
color = MaterialTheme.colorScheme.error,
style = TextStyle(fontSize = 12.sp),
modifier = Modifier.testTag("UsernameError"))
}
OutlinedTextField(
value = bio,
onValueChange = {
bio = it
bioError =
if (it.length > bioMaxSize) "Bio must be no more than $bioMaxSize characters"
else null
},
label = { Text("Bio") },
isError = bioError != null,
singleLine = false,
modifier =
Modifier.fillMaxWidth().height(125.dp).padding(top = 4.dp).testTag("BioInput"))
if (bioError != null) {
Text(
bioError!!,
color = MaterialTheme.colorScheme.error,
style = TextStyle(fontSize = 12.sp),
modifier = Modifier.testTag("BioError"))
}
Button(
modifier = Modifier.fillMaxWidth().padding(top = 16.dp).testTag("EditSave"),
onClick = {
if (nameError == null &&
usernameError == null &&
name.isNotEmpty() &&
username.isNotEmpty()) {
profileViewModel.setProfile(
Profile(
profile.id,
name,
username,
profile.email,
bio,
profile.imageUrl,
profile.followers,
profile.following,
profile.filter,
profile.recipeList,
profile.commentList))
navigationActions.navigateTo(Route.PROFILE)
}
},
enabled =
name.isNotEmpty() &&
username.isNotEmpty() &&
nameError == null &&
usernameError == null) {
Text("Save")
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/profile/EditProfileScreen.kt | 235406463 |
package com.android.feedme.ui.profile
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
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.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
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.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.android.feedme.R
import com.android.feedme.model.data.Profile
import com.android.feedme.model.viewmodel.ProfileViewModel
import com.android.feedme.ui.navigation.BottomNavigationMenu
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.Screen
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.android.feedme.ui.navigation.TopBarNavigation
import com.android.feedme.ui.theme.DarkGrey
import com.android.feedme.ui.theme.FollowButton
import com.android.feedme.ui.theme.FollowButtonBorder
import com.android.feedme.ui.theme.FollowingButton
import com.android.feedme.ui.theme.TextBarColor
/**
* A composable function that generates the profile screen.
*
* This function provides the UI interface of the profile page, which includes the profile box,
* recipe page of the user, and the comments of the user.
*
* @param navigationActions: NavigationActions object to handle navigation events
* @param profileViewModel: ProfileViewModel object to interact with profile data
* @param profileID: Optional profile ID if viewing another user's profile
*/
@Composable
fun ProfileScreen(
navigationActions: NavigationActions,
profileViewModel: ProfileViewModel,
) {
Scaffold(
modifier = Modifier.fillMaxSize().testTag("ProfileScreen"),
topBar = { TopBarNavigation(title = "Profile") },
bottomBar = {
BottomNavigationMenu(
Route.PROFILE,
{ top ->
profileViewModel.removeViewingProfile()
navigationActions.navigateTo(top)
},
TOP_LEVEL_DESTINATIONS)
},
content = { padding ->
ProfileBox(padding, profileViewModel.profileToShow(), navigationActions, profileViewModel)
})
}
/**
* A composable function that represents the profile box.
*
* This function provides the UI interface of the profile box of the user, which includes the name,
* username, biography, followers, and following of the user.
*
* @param padding: Padding around the profile box depending on the format of the phone
* @param profile: Extract the needed information from the user's profile in the database
* @param navigationActions: NavigationActions object to handle navigation events
* @param isViewingProfile: Flag indicating whether the profile being viewed is the current user's
* or not
*/
@Composable
fun ProfileBox(
padding: PaddingValues,
profile: Profile,
navigationActions: NavigationActions,
profileViewModel: ProfileViewModel
) { // TODO add font
Column(
modifier = Modifier.padding(padding).testTag("ProfileBox"),
verticalArrangement = Arrangement.Top) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 20.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically) {
UserProfilePicture()
Spacer(modifier = Modifier.width(20.dp))
UserNameBox(profile)
Spacer(modifier = Modifier.width(5.dp))
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically) {
FollowersButton(profile, navigationActions)
FollowingButton(profile, navigationActions)
}
}
UserBio(profile)
ProfileButtons(navigationActions, profile, profileViewModel)
}
}
/** A composable function that generates the user's profile picture. */
@Composable
fun UserProfilePicture() {
Image(
modifier = Modifier.width(100.dp).height(100.dp).clip(CircleShape).testTag("ProfileIcon"),
painter = painterResource(id = R.drawable.user_logo),
contentDescription = "User Profile Image",
contentScale = ContentScale.FillBounds)
}
/**
* A composable function that generates the user's name and username
*
* @param profile: extract the needed information from the user's profile in the database
*/
@Composable
fun UserNameBox(profile: Profile) {
Column(modifier = Modifier.width(100.dp).testTag("ProfileName")) {
Text(text = profile.name, style = textStyle(17, 15, 700), overflow = TextOverflow.Ellipsis)
Spacer(modifier = Modifier.height(10.dp))
Text(
text = "@" + profile.username,
style = textStyle(14, 15, 700, TextAlign.Left),
overflow = TextOverflow.Ellipsis)
}
}
/**
* A composable function that generates the user's followers.
*
* @param profile: Extract the needed information from the user's profile in the database
* @param navigationActions: NavigationActions object to handle navigation events
*/
@Composable
fun FollowersButton(profile: Profile, navigationActions: NavigationActions) {
TextButton(
modifier = Modifier.testTag("FollowerDisplayButton"),
onClick = { navigationActions.navigateTo("friends/0") }) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center) {
Text(text = "Followers", style = textStyle(10, 20, 600))
Spacer(modifier = Modifier.height(5.dp))
Text(text = profile.followers.size.toString(), style = textStyle(10, 30, 600))
}
}
}
/**
* A composable function that generates the user's following.
*
* @param profile: Extract the needed information from the user's profile in the database
* @param navigationActions: NavigationActions object to handle navigation events
*/
@Composable
fun FollowingButton(profile: Profile, navigationActions: NavigationActions) {
TextButton(
modifier = Modifier.testTag("FollowingDisplayButton"),
onClick = { navigationActions.navigateTo("friends/1") }) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center) {
Text(text = "Following", style = textStyle(10, 20, 600))
Spacer(modifier = Modifier.height(5.dp))
Text(text = profile.following.size.toString(), style = textStyle(10, 30, 600))
}
}
}
/**
* A composable function that generates the user's biography
*
* @param profile: extract the needed information from the user's profile in the database
*/
@Composable
fun UserBio(profile: Profile) {
Text(
modifier = Modifier.padding(horizontal = 18.dp).testTag("ProfileBio"),
text = profile.description,
style = textStyle(13, 15, 400, TextAlign.Justify))
}
/**
* A composable function that generates the (Edit profile or Follower) and (Share profile) buttons.
*
* @param navigationActions: NavigationActions object to handle navigation events
* @param profile: Extract the needed information from the user's profile in the database
* @param isViewingProfile: Flag indicating whether the profile being viewed is the current user's
* or not
*/
@Composable
fun ProfileButtons(
navigationActions: NavigationActions,
profile: Profile,
profileViewModel: ProfileViewModel
) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 20.dp),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically) {
if (!profileViewModel.isViewingProfile()) {
OutlinedButton(
modifier = Modifier.testTag("EditButton"),
border = BorderStroke(2.dp, FollowButtonBorder),
onClick = { navigationActions.navigateTo(Screen.EDIT_PROFILE) }) {
Text(
modifier = Modifier.width(110.dp).height(13.dp),
text = "Edit Profile",
fontWeight = FontWeight.Bold,
style = textStyle())
}
} else {
val isFollowing = remember {
mutableStateOf(profile.followers.contains(profileViewModel.currentUserId))
}
if (isFollowing.value) {
OutlinedButton(
colors = ButtonDefaults.buttonColors(containerColor = FollowingButton),
border = BorderStroke(2.dp, FollowButtonBorder),
modifier = Modifier.testTag("FollowingButton"),
onClick = {
isFollowing.value = false
/*TODO ADD follower*/
}) {
Text(
modifier = Modifier.width(110.dp).height(13.dp),
text = "Following",
fontWeight = FontWeight.Bold,
style = textStyle())
}
} else {
OutlinedButton(
colors = ButtonDefaults.buttonColors(containerColor = FollowButton),
border = BorderStroke(2.dp, FollowButtonBorder),
modifier = Modifier.testTag("FollowButton"),
onClick = {
isFollowing.value = true
/*TODO REMOVE follower*/
}) {
Text(
color = TextBarColor,
modifier = Modifier.width(110.dp).height(13.dp),
text = "Follow",
fontWeight = FontWeight.Bold,
style = textStyle(color = TextBarColor))
}
}
}
OutlinedButton(
modifier = Modifier.testTag("ShareButton"),
border = BorderStroke(2.dp, FollowButtonBorder),
onClick = {
/*TODO*/
}) {
Text(
modifier = Modifier.width(110.dp),
text = "Share Profile",
fontWeight = FontWeight.Bold,
style = textStyle())
}
}
}
/**
* A composable helper function that generates the font style for the Text.
*
* @param fontSize: Font size of the text (default is 13 sp)
* @param height: Line height of the text (default is 0 sp, which means automatic line height)
* @param weight: Font weight of the text (default is 400)
* @param align: Text alignment (default is TextAlign.Center)
* @param color: Text color (default is DarkGrey)
*/
@Composable
fun textStyle(
fontSize: Int = 13,
height: Int = 0,
weight: Int = 400,
align: TextAlign = TextAlign.Center,
color: Color = DarkGrey
): TextStyle {
return TextStyle(
fontSize = fontSize.sp,
lineHeight = height.sp,
fontWeight = FontWeight(weight),
color = DarkGrey,
textAlign = align)
}
| feedme-android/app/src/main/java/com/android/feedme/ui/profile/ProfileScreen.kt | 212938879 |
package com.android.feedme.ui.theme
import androidx.compose.material3.CardColors
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)
val DarkGrey = Color(0xFF191C1E)
val YellowStar = Color(0xFFFFE600)
val TemplateColor = Color(0xFF002C47)
private val cardColor = Color(0xC9C2E1EE)
val CardBackground = CardColors(cardColor, cardColor, cardColor, cardColor)
val TextBarColor = Color(0xFFFFFFFF)
val BlueUser = Color(0xff0008bf)
val FollowButton = Color(0xFF0008C2)
val FollowingButton = Color(0xFFFFFFFF)
val FollowButtonBorder = Color(0xFF8FC0A9)
val NoInput = Color(0xFFE6DFEB)
val InValidInput = Color(0xFFFFB3B3)
val ValidInput = Color(0xFFC1FFC4)
| feedme-android/app/src/main/java/com/android/feedme/ui/theme/Color.kt | 363975919 |
package com.android.feedme.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 feedmeAppTheme(
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)
}
| feedme-android/app/src/main/java/com/android/feedme/ui/theme/Theme.kt | 113123668 |
package com.android.feedme.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
)
*/
)
| feedme-android/app/src/main/java/com/android/feedme/ui/theme/Type.kt | 3347485718 |
package com.android.feedme.ui
import android.annotation.SuppressLint
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.android.feedme.R
import com.android.feedme.ui.component.IngredientList
import com.android.feedme.ui.navigation.BottomNavigationMenu
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.Screen
import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS
import com.android.feedme.ui.navigation.TopBarNavigation
/**
* Composable function for the Create Screen.
*
* @param navigationActions actions for navigating to different screens.
*/
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun CreateScreen(navigationActions: NavigationActions) {
Scaffold(
modifier = Modifier.testTag("CreateScreen"),
topBar = { TopBarNavigation(title = "Find Recipe") },
bottomBar = {
BottomNavigationMenu(
selectedItem = Route.CREATE,
onTabSelect = navigationActions::navigateTo,
tabList = TOP_LEVEL_DESTINATIONS)
}) {
Column(
modifier = Modifier.fillMaxSize().padding(it).padding(top = 10.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally) {
// Title
Text(
text = "Ingredients",
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold,
)
// Camera Button
OutlinedButton(
modifier =
Modifier.fillMaxWidth()
.padding(horizontal = 20.dp)
.padding(bottom = 20.dp)
.testTag("CameraButton"),
shape = RoundedCornerShape(size = 10.dp),
onClick = { navigationActions.navigateTo(Screen.CAMERA) },
border = BorderStroke(width = 2.dp, color = Color.Black)) {
Icon(
painter = painterResource(id = R.drawable.camera),
contentDescription = "Add Icon",
tint = Color(0xFF4E5FFB),
modifier = Modifier.size(24.dp))
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Scan with Camera",
style =
TextStyle(
fontSize = 16.sp,
lineHeight = 20.sp,
fontWeight = FontWeight(700),
color = Color(0xFF4E5FFB),
textAlign = TextAlign.Center,
letterSpacing = 0.25.sp,
))
}
// Line separator
Image(
modifier =
Modifier.border(width = 4.dp, color = Color(0xFF8C8C8C))
.padding(4.dp)
.width(180.dp)
.height(0.dp),
painter = painterResource(id = R.drawable.line_8),
contentDescription = "Line Seperator",
contentScale = ContentScale.None)
// List Of Ingredients
IngredientList()
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/ui/CreateScreen.kt | 4134064204 |
package com.android.feedme
import android.annotation.SuppressLint
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.ui.Modifier
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navigation
import androidx.navigation.compose.rememberNavController
import com.android.feedme.model.data.ProfileRepository
import com.android.feedme.model.data.RecipeRepository
import com.android.feedme.model.viewmodel.ProfileViewModel
import com.android.feedme.model.viewmodel.RecipeViewModel
import com.android.feedme.resources.C
import com.android.feedme.ui.CreateScreen
import com.android.feedme.ui.NotImplementedScreen
import com.android.feedme.ui.auth.LoginScreen
import com.android.feedme.ui.camera.CameraScreen
import com.android.feedme.ui.home.LandingPage
import com.android.feedme.ui.home.RecipeFullDisplay
import com.android.feedme.ui.navigation.NavigationActions
import com.android.feedme.ui.navigation.Route
import com.android.feedme.ui.navigation.Screen
import com.android.feedme.ui.profile.EditProfileScreen
import com.android.feedme.ui.profile.FriendsScreen
import com.android.feedme.ui.profile.ProfileScreen
import com.android.feedme.ui.theme.feedmeAppTheme
import com.google.firebase.firestore.FirebaseFirestore
class MainActivity : ComponentActivity() {
@SuppressLint("UnrememberedGetBackStackEntry")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize Firebase
val firebase = FirebaseFirestore.getInstance()
ProfileRepository.initialize(firebase)
RecipeRepository.initialize(firebase)
setContent {
feedmeAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize().semantics { testTag = C.Tag.main_screen_container },
color = MaterialTheme.colorScheme.background) {
// Navigation host for the app
val navController = rememberNavController()
val navigationActions = NavigationActions(navController)
val profileViewModel: ProfileViewModel = viewModel<ProfileViewModel>()
// Set up the nested navigation graph
NavHost(navController = navController, startDestination = Route.AUTHENTICATION) {
navigation(startDestination = Screen.AUTHENTICATION, route = Route.AUTHENTICATION) {
composable(Screen.AUTHENTICATION) { LoginScreen(navigationActions) }
}
navigation(startDestination = Screen.HOME, route = Route.HOME) {
composable(Screen.HOME) {
// Create a shared view model for Recipe
val recipeViewModel = viewModel<RecipeViewModel>()
LandingPage(navigationActions, recipeViewModel)
}
composable(Screen.RECIPE) {
// Link the shared view model to the composable
val navBackStackEntry = navController.getBackStackEntry(Screen.HOME)
val recipeViewModel = viewModel<RecipeViewModel>(navBackStackEntry)
RecipeFullDisplay(navigationActions, recipeViewModel)
}
}
navigation(startDestination = Screen.EXPLORE, route = Route.EXPLORE) {
composable(Screen.EXPLORE) {
NotImplementedScreen(navigationActions, Route.EXPLORE)
}
}
navigation(startDestination = Screen.CREATE, route = Route.CREATE) {
composable(Screen.CREATE) { CreateScreen(navigationActions) }
composable(Screen.CAMERA) { CameraScreen(navigationActions) }
}
navigation(startDestination = Screen.PROFILE, route = Route.PROFILE) {
composable(Screen.PROFILE) { ProfileScreen(navigationActions, profileViewModel) }
composable(Screen.EDIT_PROFILE) {
EditProfileScreen(navigationActions, profileViewModel)
}
composable(Screen.FRIENDS) { backStackEntry ->
backStackEntry.arguments?.getString("showFollowers")?.let {
FriendsScreen(navigationActions, profileViewModel, it.toInt())
}
}
}
navigation(startDestination = Screen.SETTINGS, route = Route.SETTINGS) {
composable(Screen.SETTINGS) {
NotImplementedScreen(navigationActions, Route.SETTINGS)
}
}
}
}
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/MainActivity.kt | 1406812118 |
package com.android.feedme.resources
// Like R, but C
object C {
object Tag {
const val greeting = "main_screen_greeting"
const val greeting_robo = "second_screen_greeting"
const val main_screen_container = "main_screen_container"
const val second_screen_container = "second_screen_container"
}
}
| feedme-android/app/src/main/java/com/android/feedme/resources/C.kt | 578182533 |
package com.android.feedme.model.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.feedme.model.data.Profile
import com.android.feedme.model.data.ProfileRepository
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
/**
* ViewModel for handling authentication processes, specifically Google authentication in this
* context.
*/
class AuthViewModel : ViewModel() {
/**
* Authenticates a user with Google using an ID token.
*
* @param idToken The Google ID Token used to authenticate the user with Firebase Authentication.
* @param onSuccess Callback to be invoked when authentication is successful.
* @param onFailure Callback to be invoked when authentication fails with an exception.
*/
fun authenticateWithGoogle(
idToken: String,
onSuccess: () -> Unit,
onFailure: (Exception) -> Unit
) {
// Create a Google sign-in credential using the provided Google ID token.
val credential = GoogleAuthProvider.getCredential(idToken, null)
// Start a coroutine in the ViewModel's scope.
viewModelScope.launch {
try {
// Attempt to sign in with the Google credential and wait for the result.
val authResult = FirebaseAuth.getInstance().signInWithCredential(credential).await()
// Process the sign-in result.
authResult.user?.let { firebaseUser ->
val googleId = firebaseUser.uid
val name = firebaseUser.displayName.orEmpty()
val email = firebaseUser.email.orEmpty()
val photoUrl = firebaseUser.photoUrl.toString()
// Try to link or create a profile based on the Firebase User details.
linkOrCreateProfile(googleId, name, email, photoUrl, onSuccess, onFailure)
} ?: onFailure(Exception("Firebase User is null")) // Handle null user case.
} catch (e: Exception) {
// Handle exceptions during the sign-in process.
onFailure(e)
}
}
}
/**
* Links to an existing profile or creates a new one based on Google user data.
*
* @param googleId The unique identifier for the Google user.
* @param name The display name of the Google user.
* @param email The email address of the Google user.
* @param photoUrl The URL of the Google user's profile photo.
* @param onSuccess Callback to be invoked when linking or creation is successful.
* @param onFailure Callback to be invoked when linking or creation fails with an exception.
*/
fun linkOrCreateProfile(
googleId: String,
name: String?,
email: String?,
photoUrl: String?,
onSuccess: () -> Unit,
onFailure: (Exception) -> Unit
) {
viewModelScope.launch {
ProfileRepository.instance.getProfile(
googleId,
onSuccess = { existingProfile ->
if (existingProfile != null) {
onSuccess()
} else {
makeNewProfile(googleId, name, email, photoUrl, onSuccess, onFailure)
}
},
onFailure = onFailure)
}
}
/**
* Creates a new profile and adds it to Firestore.
*
* @param googleId The unique identifier for the Google user.
* @param name The display name of the user (nullable).
* @param email The email address of the user (nullable).
* @param photoUrl The URL of the user's profile photo (nullable).
* @param onSuccess Callback to be invoked when the profile is successfully added.
* @param onFailure Callback to be invoked when adding the profile fails with an exception.
*/
private fun makeNewProfile(
googleId: String,
name: String?,
email: String?,
photoUrl: String?,
onSuccess: () -> Unit,
onFailure: (Exception) -> Unit
) {
val newProfile =
Profile(
id = googleId,
name = name ?: "",
username = name ?: "",
email = email ?: "",
description = "",
imageUrl = photoUrl ?: "",
followers = listOf(),
following = listOf(),
filter = listOf(),
recipeList = listOf(),
commentList = listOf())
// Add the newly created profile to the Firestore database.
ProfileRepository.instance.addProfile(newProfile, onSuccess, onFailure)
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/viewmodel/AuthViewModel.kt | 4112186416 |
package com.android.feedme.model.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.feedme.model.data.Profile
import com.android.feedme.model.data.ProfileRepository
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
/**
* A class that generates the profile view model
*
* This class provides the link between the Profile database and the rest of the code. It can be
* used in order to extract the profile information of the connected user
*/
class ProfileViewModel : ViewModel() {
private val repository = ProfileRepository.instance
// Current User
var currentUserId: String? = null
private val _currentUserProfile = MutableStateFlow<Profile?>(null)
val currentUserProfile: StateFlow<Profile?> = _currentUserProfile
private val _currentUserFollowers = MutableStateFlow<List<Profile>>(listOf(Profile()))
private val _currentUserFollowing = MutableStateFlow<List<Profile>>(listOf(Profile()))
val currentUserFollowers: StateFlow<List<Profile>> = _currentUserFollowers
val currentUserFollowing: StateFlow<List<Profile>> = _currentUserFollowing
// Viewing User
var viewingUserId: String? = null
private val _viewingUserProfile = MutableStateFlow<Profile?>(null)
private val _viewingUserFollowing = MutableStateFlow<List<Profile>>(listOf(Profile()))
private val _viewingUserFollowers = MutableStateFlow<List<Profile>>(listOf(Profile()))
val viewingUserProfile: StateFlow<Profile?> = _viewingUserProfile
val viewingUserFollowing: StateFlow<List<Profile>> = _viewingUserFollowing
val viewingUserFollowers: StateFlow<List<Profile>> = _viewingUserFollowers
init {
// Listen to FirebaseAuth state changes
FirebaseAuth.getInstance().addAuthStateListener { firebaseAuth ->
val user = firebaseAuth.currentUser
user?.uid?.let {
currentUserId = it
fetchCurrentUserProfile()
}
}
}
/**
* A function that fetches the profile during Login
*
* @param id: the unique ID of the profile we want to fetch
*/
fun fetchProfile(id: String) {
viewModelScope.launch {
repository.getProfile(
id,
onSuccess = { profile ->
_viewingUserProfile.value = profile
viewingUserId = id
if (profile != null) {
fetchProfiles(profile.followers, _viewingUserFollowers)
fetchProfiles(profile.following, _viewingUserFollowing)
}
},
onFailure = {
// Handle failure
throw error("Profile was not fetched during Login")
})
}
}
fun fetchCurrentUserProfile() {
viewModelScope.launch {
repository.getProfile(
currentUserId!!,
onSuccess = { profile ->
_currentUserProfile.value = profile
if (profile != null) {
fetchProfiles(profile.followers, _currentUserFollowers)
fetchProfiles(profile.following, _currentUserFollowing)
}
},
onFailure = {
// Handle failure
throw error("Profile was not fetched during Login")
})
}
}
/**
* A function that set local profile in the database
*
* @param profile: the profile to set in the database
*/
fun setProfile(profile: Profile) {
viewModelScope.launch {
repository.addProfile(
profile,
onSuccess = { _currentUserProfile.value = profile },
onFailure = {
// Handle failure
throw error("Profile could not get updated")
})
}
}
/**
* A function that fetches the profiles of the given Ids
*
* @param ids: the unique IDs of the profiles we want to fetch
* @param fetchProfile: the MutableStateFlow that will store the fetched profiles
*/
private fun fetchProfiles(ids: List<String>, fetchProfile: MutableStateFlow<List<Profile>>) {
// Check if we actually need to fetch the profiles
val currentIds = fetchProfile.value.map { it.id }.toSet()
if (currentIds != ids.toSet() && ids.isNotEmpty()) {
Log.d("ProfileViewModel", "Fetching profiles: $ids")
viewModelScope.launch {
repository.getProfiles(
ids,
onSuccess = { profiles ->
// Avoid unnecessary updates
if (fetchProfile.value != profiles) {
fetchProfile.value = profiles
} else {
Log.d("ProfileViewModel", "Profiles already fetched")
}
},
onFailure = {
// Handle failure
throw error("Profiles were not fetched")
})
}
}
}
/**
* Returns the profile to show based on if there is viewingUserId is null or not. If null it will
* show currentUser (the one logged in)
*
* @return The profile to show.
* @throws Exception If no profile is available.
*/
fun profileToShow(): Profile {
return (if (isViewingProfile()) viewingUserProfile.value else currentUserProfile.value)
?: throw Exception(
"No Profile to fetch, the current user ID is : $currentUserId, The issue comes from the fact that Firebase has no Profile with that ID")
}
/**
* Checks if the current user is viewing another user's profile. Will only be true if
* viewingUserId is not null
*
* @return True if the current user is viewing another user's profile, false otherwise.
* @throws Exception If no current user ID is available. Should never happen.
*/
fun isViewingProfile(): Boolean {
var isViewingProfile = false
if (viewingUserId != null && currentUserId != null && currentUserId != viewingUserId) {
isViewingProfile = true
} else if (currentUserId == null) {
// Should never occur
throw Exception(
"Not Signed-in : No Current FirebaseUser is sign-in. Database isn't accessible if no one is signed-in")
}
return isViewingProfile
}
/** Removes the viewing profile. */
fun removeViewingProfile() {
viewingUserId = null
}
/**
* Sets the viewing profile.
*
* @param profile The profile to set as the viewing profile.
*/
fun setViewingProfile(profile: Profile) {
_viewingUserProfile.value = profile
viewingUserId = profile.id
fetchProfiles(profile.followers, _viewingUserFollowers)
fetchProfiles(profile.following, _currentUserFollowing)
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/viewmodel/ProfileViewModel.kt | 177858389 |
package com.android.feedme.model.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.feedme.model.data.Recipe
import com.android.feedme.model.data.RecipeRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
/**
* A class that generates the recipe view model
*
* This class provides the link between the Recipe database and the rest of the code. It can be used
* in order to extract the recipe information
*/
class RecipeViewModel : ViewModel() {
private val repository = RecipeRepository.instance
private val _recipe = MutableStateFlow<Recipe?>(null)
val recipe: StateFlow<Recipe?> = _recipe
/**
* A function that selects a recipe to be displayed
*
* @param recipe: the recipe to be displayed
*/
fun selectRecipe(recipe: Recipe) {
_recipe.value = recipe
}
/**
* A function that sets the recipe in the database
*
* @param recipe: the recipe to set in the database
*/
fun setRecipe(recipe: Recipe) {
viewModelScope.launch {
repository.addRecipe(
recipe,
onSuccess = { _recipe.value = recipe },
onFailure = {
// Handle failure
throw error("Recipe could not get updated")
})
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/viewmodel/RecipeViewModel.kt | 1205604419 |
package com.android.feedme.model.viewmodel
import android.graphics.Bitmap
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class CameraViewModel : ViewModel() {
// Keep a list of bitmaps taken by the user
private val _bitmaps = MutableStateFlow<List<Bitmap>>(emptyList())
val bitmaps = _bitmaps.asStateFlow()
// Keep track of whether the photo saved message should be shown
private val _photoSavedMessageVisible = MutableStateFlow<Boolean>(false)
val photoSavedMessageVisible = _photoSavedMessageVisible.asStateFlow()
/**
* This function is called when the user taps the photo button in the CameraScreen. It adds the
* bitmap to the list of bitmaps in the _bitmaps state.
*/
fun onTakePhoto(bitmap: Bitmap) {
_bitmaps.value += bitmap
}
/**
* This function is called when the user taps the save button in the CameraScreen. It sets the
* _photoSavedMessageVisible state to true, which triggers a message to be shown to the user. The
* message is hidden after 3 seconds.
*/
fun onPhotoSaved() {
_photoSavedMessageVisible.value = true
// Launch a coroutine to hide the message after 3 seconds (3000 milliseconds)
viewModelScope.launch {
delay(3000)
_photoSavedMessageVisible.value = false
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/viewmodel/CameraViewModel.kt | 23001418 |
package com.android.feedme.model.data
import com.google.firebase.firestore.FirebaseFirestore
class RecipeRepository(private val db: FirebaseFirestore) {
private val ingredientsRepository = IngredientsRepository(db)
private val collectionPath = "recipes"
companion object {
// Placeholder for the singleton instance
lateinit var instance: RecipeRepository
private set
// Initialization method to be called once, e.g., in your Application class
fun initialize(db: FirebaseFirestore) {
instance = RecipeRepository(db)
}
}
/**
* Adds a recipe to the Firestore database.
*
* This method serializes the Recipe object into a map, replacing complex objects like Ingredient
* with their IDs, and then stores it in Firestore under the recipes collection.
*
* @param recipe The Recipe object to be added to Firestore.
* @param onSuccess A callback invoked upon successful addition of the recipe.
* @param onFailure A callback invoked upon failure to add the recipe, with an exception.
*/
fun addRecipe(recipe: Recipe, onSuccess: () -> Unit, onFailure: (Exception) -> Unit) {
// Convert Recipe to a map, replacing Ingredient objects with their IDs
val recipeMap = recipeToMap(recipe)
db.collection(collectionPath)
.document(recipe.recipeId)
.set(recipeMap)
.addOnSuccessListener { onSuccess() }
.addOnFailureListener { onFailure(it) }
}
/**
* Retrieves a recipe from Firestore by its ID.
*
* Fetches the recipe document from Firestore, deserializes it back into a Recipe object, and then
* invokes the onSuccess callback with it. If the recipe is not found or an error occurs,
* onFailure is called with an exception.
*
* @param recipeId The ID of the recipe to retrieve.
* @param onSuccess A callback invoked with the retrieved Recipe object upon success.
* @param onFailure A callback invoked upon failure to retrieve the recipe, with an exception.
*/
fun getRecipe(recipeId: String, onSuccess: (Recipe?) -> Unit, onFailure: (Exception) -> Unit) {
db.collection(collectionPath)
.document(recipeId)
.get()
.addOnSuccessListener { documentSnapshot ->
val recipeMap =
documentSnapshot.data
?: return@addOnSuccessListener onFailure(Exception("Recipe not found"))
// Reconstruct the Recipe object, fetching Ingredient objects as needed
mapToRecipe(recipeMap, onSuccess, onFailure)
}
.addOnFailureListener { onFailure(it) }
}
private fun recipeToMap(recipe: Recipe): Map<String, Any> {
return mapOf(
"recipeId" to recipe.recipeId,
"title" to recipe.title,
"description" to recipe.description,
"ingredients" to recipe.ingredients.map { it.ingredient.id },
"steps" to recipe.steps.map { it.toMap() },
"tags" to recipe.tags,
"time" to recipe.time,
"rating" to recipe.rating,
"userid" to recipe.userid,
"difficulty" to recipe.difficulty,
"imageUrl" to recipe.imageUrl)
}
private fun IngredientMetaData.toMap(): Map<String, Any> =
mapOf(
"quantity" to this.quantity,
"measure" to this.measure.name, // Store the measure as a string
"ingredientId" to this.ingredient.id)
private fun Step.toMap(): Map<String, Any> =
mapOf(
"stepNumber" to this.stepNumber, "description" to this.description, "title" to this.title)
private fun mapToRecipe(
map: Map<String, Any>,
onSuccess: (Recipe?) -> Unit,
onFailure: (Exception) -> Unit
) {
// Attempt to safely extract the list of ingredient IDs
val rawIngredientsList = map["ingredients"]
val ingredientIds =
if (rawIngredientsList is List<*>) {
rawIngredientsList.mapNotNull { (it as? Map<*, *>)?.get("ingredientId") as? String }
} else {
listOf<String>()
}
// Safely process the tags
val rawTagsList = map["tags"]
val tags =
if (rawTagsList is List<*>) {
rawTagsList.mapNotNull { it as? String }
} else {
listOf()
}
ingredientsRepository.getIngredients(
ingredientIds,
onSuccess = { ingredients ->
try {
// Safely process the steps
val rawStepsList = map["steps"]
val steps =
if (rawStepsList is List<*>) {
rawStepsList.mapNotNull { rawStep ->
(rawStep as? Map<*, *>)?.let { stepMap ->
val stepNumber = (stepMap["stepNumber"] as? Number)?.toInt()
val description = stepMap["description"] as? String
val title = stepMap["title"] as? String
if (stepNumber != null && description != null && title != null) {
Step(stepNumber, description, title)
} else null
}
}
} else {
listOf<Step>()
}
// Construct the Recipe object
val recipe =
Recipe(
recipeId = map["recipeId"] as? String ?: "",
title = map["title"] as? String ?: "",
description = map["description"] as? String ?: "",
ingredients = ingredients,
steps = steps,
tags = tags,
time = (map["time"] as? Number)?.toDouble() ?: 0.0,
rating = (map["rating"] as? Number)?.toDouble() ?: 0.0,
userid = map["userid"] as? String ?: "",
difficulty = map["difficulty"] as? String ?: "",
imageUrl = map["imageUrl"] as? String ?: "")
onSuccess(recipe)
} catch (e: Exception) {
onFailure(e)
}
},
onFailure = onFailure)
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/data/RecipeRepository.kt | 2775713204 |
package com.android.feedme.model.data
import com.google.firebase.firestore.FirebaseFirestore
/**
* A repository class for managing comments in Firebase Firestore.
*
* This class provides methods to add and retrieve comments from Firestore. It follows the singleton
* pattern to ensure a single instance of the repository is used throughout the application.
*
* @property db The Firestore database instance used for comment operations.
*/
class CommentRepository(private val db: FirebaseFirestore) {
companion object {
/** The singleton instance of CommentRepository. */
lateinit var instance: CommentRepository
private set
/**
* Initializes the singleton instance of CommentRepository. This method should be called once,
* typically during application startup.
*
* @param db The FirebaseFirestore instance to be used by the repository.
*/
fun initialize(db: FirebaseFirestore) {
instance = CommentRepository(db)
}
}
/**
* Adds a comment to Firestore.
*
* @param comment The Comment object to be added.
* @param onSuccess Callback invoked on successful addition of the comment.
* @param onFailure Callback invoked on failure to add the comment, with an exception.
*/
fun addComment(comment: Comment, onSuccess: () -> Unit, onFailure: (Exception) -> Unit) {
db.collection("comments")
.document(comment.authorId)
.set(comment)
.addOnSuccessListener { onSuccess() }
.addOnFailureListener { exception -> onFailure(exception) }
}
/**
* Retrieves a comment from Firestore by its ID.
*
* @param commentId The ID of the comment to be retrieved.
* @param onSuccess Callback invoked on successful retrieval of the comment, with the comment
* object.
* @param onFailure Callback invoked on failure to retrieve the comment, with an exception.
*/
fun getComment(commentId: String, onSuccess: (Comment?) -> Unit, onFailure: (Exception) -> Unit) {
db.collection("comments")
.document(commentId)
.get()
.addOnSuccessListener { documentSnapshot ->
val comment = documentSnapshot.toObject(Comment::class.java)
onSuccess(comment)
}
.addOnFailureListener { exception -> onFailure(exception) }
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/data/CommentRepository.kt | 265950332 |
package com.android.feedme.model.data
data class Recipe(
val recipeId: String, // Unique identifier for the recipe
val title: String, // Title of the recipe
val description: String, // Description of the recipe for the thumbnail
val ingredients: List<IngredientMetaData>, // List of ingredients with quantity and measure
val steps: List<Step>, // List of steps to prepare the recipe
val tags: List<String>, // List of tags for the recipe
val time: Double, // Time to prepare the recipe
val rating: Double, // Rating of the recipe
val userid: String, // User id of the recipe creator
val difficulty: String, // Difficulty level of the recipe
val imageUrl: String // Image URL of the recipe
)
data class Step(
val stepNumber: Int,
val description: String, // description of the step
val title: String // title of the step
)
data class IngredientMetaData(
val quantity: Double, // Quantity of the ingredient
val measure: MeasureUnit, // Measure unit of the ingredient
val ingredient: Ingredient // Ingredient object
)
enum class MeasureUnit {
TEASPOON,
TABLESPOON,
CUP,
G,
KG,
L,
ML,
NONE,
EMPTY
// Add more units as needed
}
| feedme-android/app/src/main/java/com/android/feedme/model/data/Recipe.kt | 2919073294 |
package com.android.feedme.model.data
import java.util.Date
data class Comment(
val authorId: String,
val recipeId: String,
val photoURL: String,
val rating: Double,
val time: Double,
val title: String,
val content: String,
val creationDate: Date
)
| feedme-android/app/src/main/java/com/android/feedme/model/data/Comment.kt | 1568529380 |
package com.android.feedme.model.data
import com.google.firebase.firestore.FirebaseFirestore
/**
* A repository class for managing ingredient documents in Firebase Firestore.
*
* This class provides methods for adding, retrieving a single ingredient, and retrieving multiple
* ingredients from Firestore. It uses a singleton pattern to ensure consistent use of the Firestore
* instance throughout the application.
*
* @property db The Firestore database instance used for ingredient operations.
*/
class IngredientsRepository(private val db: FirebaseFirestore) {
companion object {
/** The singleton instance of IngredientsRepository. */
lateinit var instance: IngredientsRepository
private set
/**
* Initializes the singleton instance of IngredientsRepository. This method should be called
* once, typically during application startup, to ensure the repository is ready for use.
*
* @param db The FirebaseFirestore instance to be used by the repository.
*/
fun initialize(db: FirebaseFirestore) {
instance = IngredientsRepository(db)
}
}
private val collectionPath = "ingredients"
/**
* Adds an ingredient to Firestore.
*
* @param ingredient The Ingredient object to be added.
* @param onSuccess Callback invoked on successful addition of the ingredient.
* @param onFailure Callback invoked on failure to add the ingredient, with an exception.
*/
fun addIngredient(ingredient: Ingredient, onSuccess: () -> Unit, onFailure: (Exception) -> Unit) {
db.collection(collectionPath)
.document(ingredient.id)
.set(ingredient)
.addOnSuccessListener { onSuccess() }
.addOnFailureListener { exception -> onFailure(exception) }
}
/**
* Retrieves a single ingredient by its ID from Firestore.
*
* @param ingredientId The ID of the ingredient to retrieve.
* @param onSuccess Callback invoked with the retrieved Ingredient object on success.
* @param onFailure Callback invoked on failure to retrieve the ingredient, with an exception.
*/
fun getIngredient(
ingredientId: String,
onSuccess: (Ingredient?) -> Unit,
onFailure: (Exception) -> Unit
) {
db.collection(collectionPath)
.document(ingredientId)
.get()
.addOnSuccessListener { documentSnapshot ->
val ingredient = documentSnapshot.toObject(Ingredient::class.java)
onSuccess(ingredient)
}
.addOnFailureListener { exception -> onFailure(exception) }
}
/**
* Retrieves multiple ingredients by their IDs from Firestore.
*
* This method handles both the successful retrieval of all ingredients and the case where one or
* more ingredient retrievals fail.
*
* @param ingredientIds The list of ingredient IDs to retrieve.
* @param onSuccess Callback invoked with a list of IngredientMetaData objects on success.
* @param onFailure Callback invoked on failure to retrieve one or more ingredients, with an
* exception.
*/
fun getIngredients(
ingredientIds: List<String>,
onSuccess: (List<IngredientMetaData>) -> Unit,
onFailure: (Exception) -> Unit
) {
val ingredients = mutableListOf<IngredientMetaData>()
if (ingredientIds.isEmpty()) {
onSuccess(ingredients) // Immediate success for empty input
return
}
var completedRequests = 0
var hasFailed = false
ingredientIds.forEach { id ->
db.collection(collectionPath)
.document(id)
.get()
.addOnSuccessListener { documentSnapshot ->
val ingredient = documentSnapshot.toObject(Ingredient::class.java)
if (ingredient != null) {
ingredients.add(IngredientMetaData(1.0, MeasureUnit.CUP, ingredient))
}
completedRequests++
if (completedRequests == ingredientIds.size && !hasFailed) {
onSuccess(ingredients)
}
}
.addOnFailureListener { exception ->
if (!hasFailed) {
hasFailed = true
onFailure(exception) // Report failure on the first occurrence
}
}
}
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/data/IngredientsRepository.kt | 1447562175 |
package com.android.feedme.model.data
import com.google.firebase.firestore.FirebaseFirestore
/**
* A repository class for managing user profiles in Firebase Firestore.
*
* Provides functionalities to add and retrieve user profiles. Utilizes a singleton pattern for
* using a single instance throughout the application to interact with the Firestore database.
*
* @property db The Firestore database instance used for profile operations.
*/
class ProfileRepository(private val db: FirebaseFirestore) {
companion object {
/** The singleton instance of the ProfileRepository. */
lateinit var instance: ProfileRepository
private set
/**
* Initializes the singleton instance of ProfileRepository with a Firestore database instance.
* This method should be called once, typically during the application's initialization phase.
*
* @param db The FirebaseFirestore instance for database operations.
*/
fun initialize(db: FirebaseFirestore) {
instance = ProfileRepository(db)
}
}
private val collectionPath = "profiles"
/**
* Adds a user profile to Firestore.
*
* This method saves the profile document in the Firestore collection specified by
* [collectionPath]. On successful addition, [onSuccess] is called; if an error occurs,
* [onFailure] is invoked with the exception.
*
* @param profile The Profile object to be added to Firestore.
* @param onSuccess A callback function invoked on successful addition of the profile.
* @param onFailure A callback function invoked on failure to add the profile, with an exception.
*/
fun addProfile(profile: Profile, onSuccess: () -> Unit, onFailure: (Exception) -> Unit) {
db.collection(collectionPath)
.document(profile.id)
.set(profile)
.addOnSuccessListener { onSuccess() }
.addOnFailureListener { exception -> onFailure(exception) }
}
/**
* Retrieves a user profile from Firestore by its document ID.
*
* Fetches the profile document with the given [id] from the Firestore collection specified by
* [collectionPath]. If successful, [onSuccess] is called with the retrieved Profile object; if an
* error occurs or the document does not exist, [onFailure] is invoked.
*
* @param id The document ID of the profile to retrieve.
* @param onSuccess A callback function invoked with the retrieved Profile object on success.
* @param onFailure A callback function invoked on failure to retrieve the profile, with an
* exception.
*/
fun getProfile(id: String, onSuccess: (Profile?) -> Unit, onFailure: (Exception) -> Unit) {
db.collection(collectionPath)
.document(id)
.get()
.addOnSuccessListener { documentSnapshot ->
val profile = documentSnapshot.toObject(Profile::class.java)
onSuccess(profile)
}
.addOnFailureListener { exception -> onFailure(exception) }
}
/** Fetch all the profiles of the given List of Ids */
fun getProfiles(
ids: List<String>,
onSuccess: (List<Profile>) -> Unit,
onFailure: (Exception) -> Unit
) {
db.collection(collectionPath)
.whereIn("id", ids)
.get()
.addOnSuccessListener { querySnapshot ->
val profiles = querySnapshot.toObjects(Profile::class.java)
onSuccess(profiles)
}
.addOnFailureListener { exception -> onFailure(exception) }
}
}
| feedme-android/app/src/main/java/com/android/feedme/model/data/ProfileRepository.kt | 1621258140 |
package com.android.feedme.model.data
data class Ingredient(val name: String, val type: String, val id: String)
| feedme-android/app/src/main/java/com/android/feedme/model/data/Ingredient.kt | 2916818706 |
package com.android.feedme.model.data
data class Profile(
val id: String = "ID_DEFAULT",
val name: String = "NAME_DEFAULT",
val username: String = "USERNAME_DEFAULT",
val email: String = "EMAIL_DEFAULT",
val description: String = "BIO_DEFAULT",
val imageUrl: String = "URL_DEFAULT",
val followers: List<String> = listOf(),
val following: List<String> = listOf(),
val filter: List<String> = listOf(), // Setting of alergie / setting
val recipeList: List<String> = listOf(), // Assuming this is a list of recipe IDs
// TODO ADD recipeSave / RecipeCreated
val commentList: List<String> = listOf()
)
| feedme-android/app/src/main/java/com/android/feedme/model/data/Profile.kt | 2144598534 |
package name.modid
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.item.v1.FabricItemSettings
import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings
import net.minecraft.block.Block
import net.minecraft.block.BlockState
import net.minecraft.entity.EntityType
import net.minecraft.entity.passive.CowEntity
import net.minecraft.entity.passive.PassiveEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.BlockItem
import net.minecraft.item.Item
import net.minecraft.registry.Registries
import net.minecraft.registry.Registry
import net.minecraft.sound.SoundCategory
import net.minecraft.sound.SoundEvent
import net.minecraft.text.Text
import net.minecraft.util.Identifier
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import org.slf4j.LoggerFactory
object Xishitpost : ModInitializer {
private val logger = LoggerFactory.getLogger("xi-shitpost")
val customItem: Item = Registry.register(
Registries.ITEM,
Identifier("tutorial", "custom_item"),
Item(FabricItemSettings()))
val aidanBlock: AidanBlock = AidanBlock(FabricBlockSettings.create().strength(4.0f))
override fun onInitialize() {
// This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized.
// Proceed with mild caution.
logger.info("Hello Fabric world!")
Registry.register(Registries.BLOCK, Identifier("tutorial", "aidan_block"), aidanBlock)
Registry.register(
Registries.ITEM,
Identifier("tutorial", "aidan_block"),
BlockItem(aidanBlock, FabricItemSettings())
)
Registry.register(
Registries.SOUND_EVENT,
aidanBlock.pipeSoundId,
aidanBlock.pipeSoundEvent
)
}
}
class AidanBlock(settings: Settings) : Block(settings) {
val pipeSoundId: Identifier = Identifier("tutorial:my_sound")
val pipeSoundEvent: SoundEvent = SoundEvent.of(pipeSoundId)
override fun onBreak(world: World?, pos: BlockPos?, state: BlockState?, player: PlayerEntity?): BlockState {
if (!world!!.isClient()) {
player!!.sendMessage(Text.literal(
"TREAT ME LIKE WHITE TEES"
))
world.playSound(
null,
pos,
pipeSoundEvent,
SoundCategory.BLOCKS,
10f,
1f
)
}
return state!!
}
}
| mcfunny/src/main/kotlin/name/modid/Xishitpost.kt | 3824430600 |
package name.modid
import net.fabricmc.api.ClientModInitializer
object XishitpostClient : ClientModInitializer {
override fun onInitializeClient() {
// This entrypoint is suitable for setting up client-specific logic, such as rendering.
}
} | mcfunny/src/client/kotlin/name/modid/XishitpostClient.kt | 1156725386 |
fun main(args: Array<String>) {
var sun: Array<Double> = arrayOf(1.0, 2.0, 3.0, 4.0, -5.0, -6.0, 2.0, 1.0, -4.0, 0.5, -3.0, 4.0, -7.0, 9.0, -9.0,)
var bool: Boolean = false
var dob: Double = 0.0
var bit: Int = 0
for (i in sun){
if (i<0){
bool = true
}
if(bool==true &&i>0){
dob += i
bit += 1
}
}
println(dob/bit)
}
| HomeWork3/src/main/kotlin/Main.kt | 3996604014 |
package com.example.chap1_challenge1
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.chap1_challenge1", appContext.packageName)
}
} | 4001116-synrgy7-mia-shape-ch1/app/src/androidTest/java/com/example/chap1_challenge1/ExampleInstrumentedTest.kt | 3332781584 |
package com.example.chap1_challenge1
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)
}
} | 4001116-synrgy7-mia-shape-ch1/app/src/test/java/com/example/chap1_challenge1/ExampleUnitTest.kt | 301523070 |
package com.example.challenge1
interface Shape{
fun create()
}
class FilledTriangle(val component: Char, val rows: Byte) : Shape {
override fun create() {
for (i in 1..rows) {
for (j in 1..(rows - i)) print(" ")
for (j in 1..<2 * i) print(component)
println()
}
}
}
class FilledTriangleUpsideDown(val component: Char, val rows: Byte) : Shape {
override fun create() {
for (i in rows downTo 1) {
for (j in 1..(rows - i)) print(" ")
for (j in 1..<2 * i) print(component)
println()
}
}
}
class FilledKite(val component: Char, val rows: Byte) : Shape {
override fun create() {
for (i in 1..rows) {
for (j in 1..rows - i) print(" ")
for (j in 1..<2 * i) print(component)
println()
}
for (i in rows - 1 downTo 1) {
for (j in 1..rows - i) print(" ")
for (j in 1..<2 * i) print(component)
println()
}
}
}
class X(val component: Char, val rows: Byte) : Shape {
override fun create() {
for (i in 1..rows) {
for (j in 1..rows) {
if (i == j || j == rows - i + 1) print(component) else print(" ")
}
println()
}
}
}
class StrokeTriangle(val component: Char, val rows: Byte) : Shape {
override fun create() {
for (i in 1..<rows) {
for (j in 1..<rows + i) {
if ((j == rows + (i-2) && i > 1) || j == rows - (i-1)) print(component)
print(" ")
}
println()
}
for (x in 1..rows) {
print(component)
print(" ")
}
println()
}
} | 4001116-synrgy7-mia-shape-ch1/app/src/main/java/com/example/chap1_challenge1/Shape.kt | 625564525 |
package com.example.challenge1
fun Char.isTryAgain() : Boolean{
if (this == 'Y' || this == 'y') return true
return false
} | 4001116-synrgy7-mia-shape-ch1/app/src/main/java/com/example/chap1_challenge1/ExtensionFun.kt | 3589946651 |
import com.example.challenge1.FilledKite
import com.example.challenge1.FilledTriangle
import com.example.challenge1.FilledTriangleUpsideDown
import com.example.challenge1.StrokeTriangle
import com.example.challenge1.X
import com.example.challenge1.checkChosenNumber
import com.example.challenge1.checkRow
import com.example.challenge1.inputComponent
import com.example.challenge1.inputNumber
import com.example.challenge1.inputRows
import com.example.challenge1.inputTryAgain
import com.example.challenge1.isTryAgain
import com.example.challenge1.showChoices
fun main() {
var chosenNumber: Int?
var rows: Byte?
do {
showChoices()
do {
chosenNumber = inputNumber()
checkChosenNumber(chosenNumber)
} while (chosenNumber !in 1..5)
do {
rows = inputRows()
checkRow(rows)
} while (rows == null || rows <= 0)
val component = inputComponent()
val chosenShape = when (chosenNumber) {
1 -> FilledTriangle(component, rows)
2 -> FilledTriangleUpsideDown(component, rows)
3 -> FilledKite(component, rows)
4 -> X(component, rows)
else -> StrokeTriangle(component, rows)
}
chosenShape.create()
val again = inputTryAgain()
} while (again.isTryAgain())
} | 4001116-synrgy7-mia-shape-ch1/app/src/main/java/com/example/chap1_challenge1/Main.kt | 1647055138 |
package com.example.challenge1
fun inputNumber(): Int? {
print("Masukkan nomor bentuk pilihan: ")
return readln().toIntOrNull()
}
fun inputRows(): Byte? {
print("Tentukan ukuran bentuk (baris): ")
return readln().toByteOrNull()
}
fun inputComponent(): Char {
print("Tentukan huruf/simbol/angka untuk menyusun bentuk: ")
return readln()[0]
}
fun inputTryAgain(): Char {
print("Ketik 'Y' untuk mencoba lagi: ")
return readln()[0]
}
fun checkChosenNumber (nomorPilihan: Int?){
if (nomorPilihan !in 1..5 || nomorPilihan == null) println("tolong ya...pilihannya cuma 1 sampai 5 aja 😡\n".uppercase())
}
fun checkRow(jumlahBaris: Byte?){
if (jumlahBaris == null || jumlahBaris <= 0) println("waduh...mohon masukkan nilai berupa angka positif ya agar bentuk bisa dibuat 😇\n".uppercase())
}
fun showChoices(){
println(
"""Pilihan Bentuk :
1. [Filled] Segitiga
2. [Filled] Segitiga Terbalik
3. [Filled] Layang-layang
4. Huruf X
5. [Stroke] Segitiga
""".trimMargin()
)
} | 4001116-synrgy7-mia-shape-ch1/app/src/main/java/com/example/chap1_challenge1/Functions.kt | 2158564727 |
package com.example.historyapp_st10443445
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
private lateinit var scenario: ActivityScenario<MainActivity>
@Before
fun setUp() {
scenario = ActivityScenario.launch(MainActivity::class.java)
}
@After
fun tearDown() {
scenario.close()
}
@Test
fun testValidInput() {
val validYear = "1990"
onView(withId(R.id.edtYear))
.perform(typeText(validYear), closeSoftKeyboard())
onView(withId(R.id.btnResults))
.perform(click())
onView(withId(R.id.txtResults))
.check(matches(withText("In $validYear: ")))
}
@Test
fun testInvalidInput() {
val invalidYear = "abcd"
onView(withId(R.id.edtYear))
.perform(typeText(invalidYear), closeSoftKeyboard())
onView(withId(R.id.btnResults))
.perform(click())
onView(withId(R.id.txtResults))
.check(matches(withText("No event has been found from input of your age.")))
}
} | Assingment_1_ST10443445/app/src/androidTest/java/com/example/historyapp_st10443445/ExampleInstrumentedTest.kt | 1261437827 |
package com.example.historyapp_st10443445
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)
}
} | Assingment_1_ST10443445/app/src/test/java/com/example/historyapp_st10443445/ExampleUnitTest.kt | 2526480060 |
package com.example.historyapp_st10443445
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.accessibility.AccessibilityManager.AudioDescriptionRequestedChangeListener
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
//List of Historical events
enum class HistoricalEvent(val year: Int, val description: String) {
EVENT_1(99, "Bob Barker's passed away"),
EVENT_2(95, "Nelson Mandela passed away"),
EVENT_3(80, "John Lewis passed away"),
EVENT_4(70, "Henry Ford II passed away"),
EVENT_5(60, "Robin Williams passed away"),
EVENT_6(50, "Michael Jackson passed away"),
EVENT_7(40, "Paul Walker passed away"),
EVENT_8(30, "Bob Marley passed away"),
EVENT_9(20, "Cameron Boyce passed away"),
EVENT_10(25, "Jimi Hendrix passed away"),
}
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//declaring variables
val edtBirthYear = findViewById<EditText>(R.id.edtYear)
val btnResults = findViewById<Button>(R.id.btnResults)
val btnClear = findViewById<Button>(R.id.btnClear)
val txtResults = findViewById<TextView>(R.id.txtResults)
//If user press results button
btnResults?.setOnClickListener ()
{
val birthYear = edtBirthYear.text.toString().toInt()
if (birthYear != null && birthYear in 20 .. 100) {
val eventYears = HistoricalEvent.values().map { it.year }
val events = when(birthYear)
{
//This statement will show if users age is the same as the death historical event
in eventYears -> {
val event = HistoricalEvent.values().find { it.year == birthYear }
listOf("In $birthYear: ${event?.description ?: "event"}")
}
//This statemant will shoe if your age is one year before historical event
in eventYears.map { it - 1 } -> {
val event = HistoricalEvent.values().find { it.year == birthYear + 1 }
listOf("Your birth year is one year after the Historical event" + "${event?.description ?: "event"}")
}
//This statemant will show if your age is one year after historical event
in eventYears.map { it + 1 } -> {
val event = HistoricalEvent.values().find { it.year == birthYear - 1 }
listOf("Your birth year is one year before the Historical event" + "${event?.description ?: "event"}")
}
else -> listOf("No History events found for $birthYear")
}
txtResults.text = events.joinToString("\n")
}else {
txtResults.text = "No event has been found from input of your age."
}
}
//when you press the clear button
btnClear?.setOnClickListener(){
edtBirthYear.text.clear()
txtResults.text = ""
}
}
} | Assingment_1_ST10443445/app/src/main/java/com/example/historyapp_st10443445/MainActivity.kt | 781835993 |
package com.maxflask.electricansbible
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.maxflask.electricansbible", appContext.packageName)
}
} | ElectricansBible/ElectricansBible/app/src/androidTest/java/com/maxflask/electricansbible/ExampleInstrumentedTest.kt | 2198504526 |
package com.maxflask.electricansbible
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)
}
} | ElectricansBible/ElectricansBible/app/src/test/java/com/maxflask/electricansbible/ExampleUnitTest.kt | 3060249654 |
package com.maxflask.electricansbible.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) | ElectricansBible/ElectricansBible/app/src/main/java/com/maxflask/electricansbible/ui/theme/Color.kt | 4118943581 |
package com.maxflask.electricansbible.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 ElectricansBibleTheme(
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
)
} | ElectricansBible/ElectricansBible/app/src/main/java/com/maxflask/electricansbible/ui/theme/Theme.kt | 2100814149 |
package com.maxflask.electricansbible.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
)
*/
) | ElectricansBible/ElectricansBible/app/src/main/java/com/maxflask/electricansbible/ui/theme/Type.kt | 638534144 |
package com.maxflask.electricansbible
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import com.maxflask.electricansbible.ui.theme.ElectricansBibleTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.io.BufferedReader
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ElectricansBibleTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
BookReaderApp()
}
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BookReaderApp() {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
val context = LocalContext.current
var books = remember { mutableStateOf(listOf<String>()) }
val selectedBook = remember { mutableStateOf("") }
val chapters = remember { mutableStateOf(listOf<String>()) }
books.value = listOf("ПОТЭЭ", "Охрана труда")
LaunchedEffect(selectedBook.value) {
chapters.value = loadChapters(context, selectedBook.value)
}
ModalNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DrawerContent(books.value, selectedBook, drawerState, scope)
},
scrimColor = Color(0xFF7B1FA2).copy(alpha = 0.9f) // Фиолетовый с прозрачностью
) {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = { Text("Библия электриков") },
navigationIcon = {
IconButton(onClick = {
scope.launch { drawerState.open() }
}) {
Icon(Icons.Filled.Menu, contentDescription = "Menu")
}
}
)
},
containerColor = colorResource(id = R.color.fiolet)
) { paddingValues ->
ChapterList(chapters.value, paddingValues)
}
}
}
@Composable
fun DrawerContent(
books: List<String>,
selectedBook: MutableState<String>,
drawerState: DrawerState,
scope: CoroutineScope
) {
Column() {
Image(
painter = painterResource(id = R.drawable.logo),
contentDescription = "Book Cover",
modifier = Modifier
.height(128.dp)
.width(128.dp)
.padding(5.dp),
alpha = 1f
)
LazyColumn {
items(books) { item ->
Column(
modifier = Modifier
.padding(5.dp)
.clip(RoundedCornerShape(1.dp))
.border(1.dp, Color.Gray)
.fillMaxWidth()
) {
Text(
text = item,
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.clickable {
selectedBook.value = item
scope.launch { drawerState.close() }
}
)
}
}
}
}
}
@Composable
fun ChapterList(chapters: List<String>, paddingValues: PaddingValues) {
LazyColumn(modifier = Modifier.padding(paddingValues)) {
items(chapters.size) { index ->
Column(modifier = Modifier.fillMaxWidth().padding(5.dp).border(1.dp, Color.Gray,
RoundedCornerShape(5.dp)
)) {
Text(text = chapters[index], modifier = Modifier.padding(8.dp))
}
}
}
}
fun loadChapters(context: Context, bookName: String): List<String> {
return try {
context.assets.open("$bookName.txt").bufferedReader().use(BufferedReader::readLines)
} catch (e: Exception) {
listOf("Error loading file: ${e.message}")
}
} | ElectricansBible/ElectricansBible/app/src/main/java/com/maxflask/electricansbible/MainActivity.kt | 3764668704 |
package com.example.mimec24
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.mimec24", appContext.packageName)
}
} | MIMEC24/app/src/androidTest/java/com/example/mimec24/ExampleInstrumentedTest.kt | 1830609641 |
package com.example.mimec24
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)
}
} | MIMEC24/app/src/test/java/com/example/mimec24/ExampleUnitTest.kt | 405708985 |
package com.example.mimec24
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.example.mimec24.databinding.ActivityInicioMBinding
class inicioM : AppCompatActivity() {
private lateinit var binding : ActivityInicioMBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityInicioMBinding.inflate(layoutInflater)
setContentView(binding.root)
replaceFragment(InicioNM())
binding.bottomNavigationView.setOnItemSelectedListener{
when(it.itemId){
R.id.home-> replaceFragment(InicioNM())
R.id.maps-> replaceFragment(MapaM())
R.id.agregar-> replaceFragment(agregar())
R.id.chat -> replaceFragment(chat())
R.id.profile -> replaceFragment(PerfilM())
else->{
}
}
true
}
}
private fun replaceFragment(fragment: Fragment){
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.frame_layout,fragment)
fragmentTransaction.commit()
}
} | MIMEC24/app/src/main/java/com/example/mimec24/inicioM.kt | 3335797260 |
package com.example.mimec24
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class ProfileActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
}
} | MIMEC24/app/src/main/java/com/example/mimec24/ProfileActivity.kt | 2656807027 |
package com.example.mimec24
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
private lateinit var btnU: Button
private lateinit var btnM: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnU = findViewById<Button>(R.id.btnU)
btnM = findViewById<Button>(R.id.btnM)
btnU.setOnClickListener{Login()}
btnM.setOnClickListener{Login2()}
}
private fun Login(){
val login = Intent(this, LoginUActivity::class.java)
startActivity(login)
}
private fun Login2(){
val log2 = Intent(this, LoginMActivity::class.java)
startActivity(log2)
}
} | MIMEC24/app/src/main/java/com/example/mimec24/MainActivity.kt | 810949003 |
package com.example.mimec24
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [InicioNM.newInstance] factory method to
* create an instance of this fragment.
*/
class InicioNM : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio_n_m, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment InicioNM.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
InicioNM().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | MIMEC24/app/src/main/java/com/example/mimec24/InicioNM.kt | 1939509801 |
package com.example.mimec24
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [chat.newInstance] factory method to
* create an instance of this fragment.
*/
class chat : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chat, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment chat.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
chat().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | MIMEC24/app/src/main/java/com/example/mimec24/chat.kt | 1607997943 |
package com.example.mimec24
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class LoginMActivity : AppCompatActivity() {
private lateinit var txtReg2: TextView
private lateinit var iniS: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_mactivity)
txtReg2 = findViewById(R.id.txtReg2)
txtReg2.setOnClickListener{Reg2()}
iniS = findViewById(R.id.iniS)
iniS.setOnClickListener{IniS()}
}
private fun Reg2(){
val ini = Intent (this, RegisterMActivity::class.java)
startActivity(ini)
}
private fun IniS(){
val ini = Intent (this, inicioM::class.java)
startActivity(ini)
}
} | MIMEC24/app/src/main/java/com/example/mimec24/LoginMActivity.kt | 3026552994 |
package com.example.mimec24
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class RegisterUActivity : AppCompatActivity() {
private lateinit var txtIni: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_uactivity)
setContentView(R.layout.activity_register_uactivity)
txtIni = findViewById(R.id.txtIni)
txtIni.setOnClickListener{Ini()}
}
private fun Ini(){
val reg = Intent (this, LoginUActivity::class.java)
startActivity(reg)
}
} | MIMEC24/app/src/main/java/com/example/mimec24/RegisterUActivity.kt | 2517006025 |
package com.example.mimec24
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class LoginUActivity : AppCompatActivity() {
private lateinit var txtRegistro: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_uactivity)
txtRegistro = findViewById<TextView>(R.id.txtRegistro)
txtRegistro.setOnClickListener{Registro()}
}
private fun Registro(){
val reg = Intent(this, RegisterUActivity::class.java)
startActivity(reg)
}
} | MIMEC24/app/src/main/java/com/example/mimec24/LoginUActivity.kt | 1941069681 |
package com.example.mimec24
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class RegisterMActivity : AppCompatActivity() {
private lateinit var txtIni2: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_mactivity)
txtIni2 = findViewById(R.id.txtIni2)
txtIni2.setOnClickListener{Ini2()}
}
private fun Ini2(){
val ini2 = Intent(this, LoginMActivity::class.java)
startActivity(ini2)
}
} | MIMEC24/app/src/main/java/com/example/mimec24/RegisterMActivity.kt | 4249149721 |
package com.example.mimec24
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
class Splash_screen : AppCompatActivity() {
private lateinit var imgLogo: ImageView
private lateinit var txtTitulo: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
imgLogo = findViewById<ImageView>(R.id.imgLogo)
txtTitulo = findViewById<TextView>(R.id.txtTitulo)
imgLogo.alpha= 0f
imgLogo.animate().setDuration(2500).alpha(1f).withEndAction {
val i = Intent(this, MainActivity::class.java)
startActivity(i)
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
finish()
}
txtTitulo.alpha= 0f
txtTitulo.animate().setDuration(2500).alpha(1f).withEndAction {
val i = Intent(this, MainActivity::class.java)
startActivity(i)
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out)
finish()
}
}
} | MIMEC24/app/src/main/java/com/example/mimec24/Splash_screen.kt | 2064766920 |
package com.example.mimec24
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [PerfilM.newInstance] factory method to
* create an instance of this fragment.
*/
class PerfilM : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_perfil_m, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment PerfilM.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
PerfilM().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | MIMEC24/app/src/main/java/com/example/mimec24/PerfilM.kt | 4199903361 |
package com.example.mimec24
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [MapaM.newInstance] factory method to
* create an instance of this fragment.
*/
class MapaM : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_mapa_m, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MapaM.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
MapaM().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | MIMEC24/app/src/main/java/com/example/mimec24/MapaM.kt | 2238842231 |
package com.example.mimec24
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [agregar.newInstance] factory method to
* create an instance of this fragment.
*/
class agregar : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Add.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
agregar().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | MIMEC24/app/src/main/java/com/example/mimec24/agregar.kt | 620297670 |
package com.srenes.mathq
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.srenes.mathq", appContext.packageName)
}
} | mathQ/app/src/androidTest/java/com/srenes/mathq/ExampleInstrumentedTest.kt | 3429399407 |
package com.srenes.mathq
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)
}
} | mathQ/app/src/test/java/com/srenes/mathq/ExampleUnitTest.kt | 1925558309 |
package com.srenes.mathq
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | mathQ/app/src/main/java/com/srenes/mathq/MainActivity.kt | 3308765178 |
package org.pebiblioteca
fun main() {
println("Hello World!")
} | pro-2324-u4u5u6-biblio-pe-ftrugon/src/main/kotlin/Main.kt | 220205571 |
package com.example.build_scrollable_list
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.build_scrollable_list", appContext.packageName)
}
} | Build_Scrollable_List/app/src/androidTest/java/com/example/build_scrollable_list/ExampleInstrumentedTest.kt | 2681152143 |
package com.example.build_scrollable_list
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)
}
} | Build_Scrollable_List/app/src/test/java/com/example/build_scrollable_list/ExampleUnitTest.kt | 751360923 |
package com.example.build_scrollable_list.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) | Build_Scrollable_List/app/src/main/java/com/example/build_scrollable_list/ui/theme/Color.kt | 484389309 |
package com.example.build_scrollable_list.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 Build_Scrollable_ListTheme(
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
)
} | Build_Scrollable_List/app/src/main/java/com/example/build_scrollable_list/ui/theme/Theme.kt | 2172419986 |
package com.example.build_scrollable_list.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
)
*/
) | Build_Scrollable_List/app/src/main/java/com/example/build_scrollable_list/ui/theme/Type.kt | 1390414315 |
package com.example.build_scrollable_list
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
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.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.build_scrollable_list.ui.theme.Build_Scrollable_ListTheme
import com.example.build_scrollable_list.model.Affirmation
import androidx.compose.ui.platform.LocalContext
import com.example.build_scrollable_list.data.Datasource
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Build_Scrollable_ListTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
AffirmationApp()
}
}
}
}
}
@Composable
fun AffirmationApp() {
AffirmationList(affirmationList = Datasource().loadAffirmations())
}
@Composable
fun AffirmationList(affirmationList: List<Affirmation>,
modifier: Modifier = Modifier) {
/*LazyColumn(modifier = modifier) {
items(affirmationList) { affirmation ->
AffirmationCard(affirmation = affirmation,
modifier = Modifier.padding(8.dp))
}
}*/
LazyVerticalGrid(columns = GridCells.Fixed(2),
contentPadding = PaddingValues(horizontal = 16.dp,
vertical = 8.dp,),
horizontalArrangement = Arrangement.spacedBy(5.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)) {
items(affirmationList) {
AffirmationCard(affirmation = it,
modifier = modifier)
}
}
}
@Composable
fun AffirmationCard(affirmation: Affirmation,
modifier: Modifier = Modifier) {
Card(modifier = modifier) {
Column(modifier = modifier) {
Image(
painter = painterResource(id = affirmation.imageResourceId),
contentDescription = stringResource(id = affirmation.stringResourceId),
modifier = modifier
.fillMaxWidth()
// .height(194.dp),
.height(100.dp),
contentScale = ContentScale.Crop)
Text(
text = LocalContext.current.getString(affirmation.stringResourceId),
modifier = Modifier.padding(16.dp),
style = MaterialTheme.typography.bodySmall,
maxLines = 2
)
}
}
}
@Preview(showBackground = true)
@Composable
fun AffirmationPreview() {
Build_Scrollable_ListTheme {
//AffirmationCard(Affirmation(R.string.affirmation1, R.drawable.image1))
AffirmationApp()
}
} | Build_Scrollable_List/app/src/main/java/com/example/build_scrollable_list/MainActivity.kt | 1327953117 |
package com.example.build_scrollable_list.model
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
data class Affirmation(
@StringRes val stringResourceId: Int,
@DrawableRes val imageResourceId: Int
)
| Build_Scrollable_List/app/src/main/java/com/example/build_scrollable_list/model/Affirmation.kt | 3597915780 |
package com.example.build_scrollable_list.data
import com.example.build_scrollable_list.model.Affirmation
import com.example.build_scrollable_list.R
class Datasource() {
fun loadAffirmations(): List<Affirmation> {
return listOf<Affirmation>(
Affirmation(R.string.affirmation1, R.drawable.image1),
Affirmation(R.string.affirmation2, R.drawable.image2),
Affirmation(R.string.affirmation3, R.drawable.image3),
Affirmation(R.string.affirmation4, R.drawable.image4),
Affirmation(R.string.affirmation5, R.drawable.image5),
Affirmation(R.string.affirmation6, R.drawable.image6),
Affirmation(R.string.affirmation7, R.drawable.image7),
Affirmation(R.string.affirmation8, R.drawable.image8),
Affirmation(R.string.affirmation9, R.drawable.image9),
Affirmation(R.string.affirmation10, R.drawable.image10)
)
}
} | Build_Scrollable_List/app/src/main/java/com/example/build_scrollable_list/data/Datasource.kt | 3624361626 |
package com.example.homeworkkotlin6n
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.homeworkkotlin6n", appContext.packageName)
}
} | HomeWorkKotlin6n/app/src/androidTest/java/com/example/homeworkkotlin6n/ExampleInstrumentedTest.kt | 1000383106 |
package com.example.homeworkkotlin6n
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)
}
} | HomeWorkKotlin6n/app/src/test/java/com/example/homeworkkotlin6n/ExampleUnitTest.kt | 900786861 |
package com.example.homeworkkotlin6n
import androidx.annotation.DrawableRes
data class Animals(
@DrawableRes val animalImage: Int, //Картинка
val name: String, //Имя
val claws: String, //Когти
val beak: String //Клюв
)
| HomeWorkKotlin6n/app/src/main/java/com/example/homeworkkotlin6n/Animals.kt | 620984542 |
package com.example.homeworkkotlin6n
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | HomeWorkKotlin6n/app/src/main/java/com/example/homeworkkotlin6n/MainActivity.kt | 2243816628 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.