content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonArray
import kotlin.test.DefaultAsserter.fail
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
//@org.junit.runner.RunWith(org.junit.runners.Parameterized::class)
abstract class AbstractTest {
abstract fun data(): Collection<PatchTestCase>
@Test
fun test() {
val testData = data()
for (p in testData) {
if (p.isOperation) {
testOpertaion(p)
} else {
testError(p)
}
}
}
private fun testOpertaion(p: PatchTestCase) {
val node: JsonObject = p.getNode()
val first: JsonElement = node.get("node")!!
val second: JsonElement = node.get("expected")!!
val patch: JsonElement = node.get("op")!!
val message = if (node.containsKey("message")) node.get("message").toString() else ""
val secondPrime: JsonElement =
JsonPatch.apply(patch.jsonArray, first)
assertEquals(secondPrime, second, message)
}
private fun testError(p:PatchTestCase) {
val node: JsonObject = p.getNode()
val first: JsonElement = node.get("node")!!
val patch: JsonElement = node.get("op")!!
try {
JsonPatch.apply(patch.jsonArray, first)
assertFails {
fail("Failure expected: " + node.get("message"))
}
}
catch (e: Exception) {
println("-> AssertFails with: ${e.message}")
}
}
} | kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/AbstractTest.kt | 1588180576 |
/*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import resources.testdata.TestData_ADD
import kotlin.test.Test
class AddOperationTest : AbstractTest() {
//@org.junit.runners.Parameterized.Parameters
override fun data(): Collection<PatchTestCase> {
return PatchTestCase.load(TestData_ADD)
}
@Test
fun childTest() {
test()
}
} | kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/AddOperationTest.kt | 4242187629 |
package com.reidsync.kxjsonpatch
import com.reidsync.kxjsonpatch.utils.GsonObjectMapper
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import resources.testdata.TestData_DIFF
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
/*
* Copyright 2016 flipkart.com kjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* @author ctranxuan (streamdata.io).
*/
class JsonDiffTest2 {
var objectMapper = GsonObjectMapper()
lateinit var jsonNode: JsonArray
@BeforeTest
fun setUp() {
jsonNode = objectMapper.readTree(TestData_DIFF).jsonArray
}
@Test
fun testPatchAppliedCleanly() {
for (i in 0 until jsonNode.size) {
val first: JsonElement = jsonNode.get(i).jsonObject.get("first")!!
val second: JsonElement = jsonNode.get(i).jsonObject.get("second")!!
val patch: JsonArray = jsonNode.get(i).jsonObject.get("patch")!!.jsonArray
val message: String = jsonNode.get(i).jsonObject.get("message").toString()
println("Test # $i")
println(first)
println(second)
println(patch)
val secondPrime: JsonElement = JsonPatch.apply(patch, first)
println(secondPrime)
assertEquals(secondPrime, second, message)
}
}
} | kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/JsonDiffTest2.kt | 2974546370 |
/*
* Copyright 2016 flipkart.com zjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reidsync.kxjsonpatch
import com.reidsync.kxjsonpatch.utils.GsonObjectMapper
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.jsonArray
import kotlin.test.Test
import kotlin.test.assertFailsWith
class ApiTest {
@Test
fun applyingNonArrayPatchShouldThrowAnException() {
assertFailsWith<InvalidJsonPatchException> {
val objectMapper = GsonObjectMapper()
val invalid: JsonElement = objectMapper.readTree("[{\"not\": \"a patch\"}]")
val to: JsonElement = objectMapper.readTree("{\"a\":1}")
JsonPatch.apply(invalid.jsonArray, to)
}
}
@Test
fun applyingAnInvalidArrayShouldThrowAnException() {
assertFailsWith<InvalidJsonPatchException> {
val objectMapper = GsonObjectMapper()
val invalid: JsonElement = objectMapper.readTree("[1, 2, 3, 4, 5]")
val to: JsonElement = objectMapper.readTree("{\"a\":1}")
JsonPatch.apply(invalid.jsonArray, to)
}
}
@Test
fun applyingAPatchWithAnInvalidOperationShouldThrowAnException() {
assertFailsWith<InvalidJsonPatchException> {
val objectMapper = GsonObjectMapper()
val invalid: JsonElement = objectMapper.readTree("[{\"op\": \"what\"}]")
val to: JsonElement = objectMapper.readTree("{\"a\":1}")
JsonPatch.apply(invalid.jsonArray, to)
}
}
@Test
fun validatingNonArrayPatchShouldThrowAnException() {
assertFailsWith<InvalidJsonPatchException> {
val objectMapper = GsonObjectMapper()
val invalid: JsonElement = objectMapper.readTree("{\"not\": \"a patch\"}")
JsonPatch.validate(invalid)
}
}
@Test
fun validatingAnInvalidArrayShouldThrowAnException() {
assertFailsWith<InvalidJsonPatchException> {
val objectMapper = GsonObjectMapper()
val invalid: JsonElement = objectMapper.readTree("[1, 2, 3, 4, 5]")
JsonPatch.validate(invalid)
}
}
@Test
fun validatingAPatchWithAnInvalidOperationShouldThrowAnException() {
assertFailsWith<InvalidJsonPatchException> {
val objectMapper = GsonObjectMapper()
val invalid: JsonElement = objectMapper.readTree("[{\"op\": \"what\"}]")
JsonPatch.validate(invalid)
}
}
} | kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/ApiTest.kt | 3052329746 |
package com.reidsync.kxjsonpatch
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlin.random.Random
/*
* Copyright 2016 flipkart.com kjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ /**
* User: gopi.vishwakarma
* Date: 05/08/14
*/
object TestDataGenerator {
private val random = Random(Int.MAX_VALUE)
private val name: List<String> = arrayListOf<String>("summers", "winters", "autumn", "spring", "rainy")
private val age: List<Int> = arrayListOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
private val gender: List<String> = arrayListOf<String>("male", "female")
private val country: List<String> = arrayListOf<String>(
"india",
"aus",
"nz",
"sl",
"rsa",
"wi",
"eng",
"bang",
"pak"
)
private val friends: List<String> = arrayListOf<String>(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"
)
fun generate(count: Int): JsonElement {
var jsonNode: JsonArray = JsonArray(emptyList())
for (i in 0 until count) {
var objectNode: JsonObject = JsonObject(emptyMap())
objectNode.addProperty(
"name",
name[random.nextInt(name.size)]
)
objectNode.addProperty(
"age",
age[random.nextInt(age.size)]
)
objectNode.addProperty(
"gender",
gender[random.nextInt(gender.size)]
)
val countryNode: JsonArray = getArrayNode(
country.subList(
random.nextInt(
country.size / 2
), country.size / 2 + random.nextInt(country.size / 2)
)
)
objectNode = objectNode.add("country", countryNode)
val friendNode: JsonArray = getArrayNode(
friends.subList(
random.nextInt(
friends.size / 2
), friends.size / 2 + random.nextInt(friends.size / 2)
)
)
objectNode = objectNode.add("friends", friendNode)
jsonNode = jsonNode.add(objectNode)
}
return jsonNode
}
private fun getArrayNode(args: List<String>): JsonArray {
val countryNode: JsonArray = JsonArray(emptyList())
for (arg in args) {
countryNode.add(JsonPrimitive(arg))
}
return countryNode
}
} | kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/TestDataGenerator.kt | 2083704720 |
package com.reidsync.kxjsonpatch
import com.reidsync.kxjsonpatch.utils.GsonObjectMapper
import kotlinx.serialization.json.*
/*
* Copyright 2016 flipkart.com kjsonpatch.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class PatchTestCase private constructor(
val isOperation: Boolean,
node: JsonObject
) {
private val node: JsonObject
fun getNode(): JsonObject {
return node
}
init {
this.node = node
}
companion object {
private val MAPPER = GsonObjectMapper()
//fun load(fileName: String): Collection<PatchTestCase> {
fun load(testData: String): Collection<PatchTestCase> {
val tree: JsonElement = MAPPER.readTree(testData)
val result: MutableList<PatchTestCase> = ArrayList<PatchTestCase>()
for (node in tree.jsonObject.get("errors")!!.jsonArray) {
if (isEnabled(node)) {
result.add(PatchTestCase(false, node.jsonObject))
}
}
for (node in tree.jsonObject.get("ops")!!.jsonArray) {
if (isEnabled(node)) {
result.add(PatchTestCase(true, node.jsonObject))
}
}
return result
}
private fun isEnabled(node: JsonElement): Boolean {
val disabled: JsonElement? = node.jsonObject.get("disabled")
return (disabled == null || !disabled.jsonPrimitive.boolean)
}
}
} | kotlin-json-patch/kotlin-json-patch/src/commonTest/kotlin/com/reidsync/kxjsonpatch/PatchTestCase.kt | 3118349467 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.ext
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
@Composable
fun Int.dp(): Dp = with(LocalDensity.current) { [email protected]() }
| EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/ext/UnitExt.kt | 1008775160 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.ext
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.statusBars
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalDensity
@Composable
fun WindowInsets.Companion.statusBarHeight(): Int = statusBars.getTop(LocalDensity.current)
@Composable
fun WindowInsets.Companion.navigationBarHeight(): Int =
navigationBars.getBottom(LocalDensity.current) | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/ext/InsetsExt.kt | 777372208 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
/**
* For People list
*
* Created on Feb 05, 2023.
*
*/
@Composable
fun ProfileContent(
userName: String,
subName: String? = null,
isOnline: Boolean,
alignment: Alignment.Horizontal,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier,
horizontalAlignment = alignment
) {
CompositionLocalProvider(
LocalContentColor provides LocalContentColor.current.copy(alpha = if (isOnline) 1f else 0.4f)
) {
Text(
text = userName,
style = MaterialTheme.typography.bodyLarge
)
}
CompositionLocalProvider(LocalContentColor provides LocalContentColor.current.copy(alpha = 0.4F)) {
Text(
text = subName ?: if (isOnline) "Active now" else "Offline",
style = MaterialTheme.typography.bodyMedium
)
}
}
} | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/ProfileContent.kt | 601916977 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ExitToApp
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mobiledevpro.ui.theme.AppTheme
/**
* Clickable item for settings list
*
* Created on Apr 02, 2023.
*
*/
@Composable
fun SettingsButton(
label: String,
icon: ImageVector,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(
horizontal = 16.dp,
vertical = 10.dp
)
.clickable {
onClick()
}
) {
Text(text = label, style = MaterialTheme.typography.bodyLarge)
IconButton(
onClick = onClick
) {
Icon(imageVector = icon, contentDescription = "")
}
}
}
@Composable
@Preview
fun SettingButtonPreview() {
AppTheme(darkTheme = true) {
SettingsButton(
"Logout",
icon = Icons.Rounded.ExitToApp,
onClick = {}
)
}
} | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/SettingsButton.kt | 765401776 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import com.mobiledevpro.ui.theme.topAppBarColor
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppTopBar(title: String, icon: ImageVector, iconClickAction: () -> Unit = {}) {
TopAppBar(
navigationIcon = {
Icon(
imageVector = icon,
contentDescription = title,
modifier = Modifier
.padding(horizontal = 16.dp)
.clickable {
iconClickAction.invoke()
}
)
},
title = { Text(title) },
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.topAppBarColor
)
)
} | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/AppTopBar.kt | 2136780531 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mobiledevpro.ui.theme.AppTheme
/**
* Radio Button
*
* Created on Apr 02, 2023.
*
*/
@Composable
fun LabeledDarkModeSwitch(
label: String,
checked: Boolean,
onCheckedChanged: (Boolean) -> Unit
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(
horizontal = 16.dp,
vertical = 10.dp
)
) {
Text(text = label, style = MaterialTheme.typography.bodyLarge)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Text("☀️")
Switch(
checked = checked,
onCheckedChange = onCheckedChanged
)
Text("🌘")
}
}
}
@Composable
@Preview
fun LabeledSwitchPreview() {
AppTheme(darkTheme = true) {
LabeledDarkModeSwitch(
"Dark mode",
checked = false,
onCheckedChanged = {}
)
}
} | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/LabeledDarkModeSwitch.kt | 160382626 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.LocalAbsoluteTonalElevation
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
/**
* Common background for all screens
*
* Created on Jan 10, 2023.
*
*/
@Composable
fun ScreenBackground(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
val color = MaterialTheme.colorScheme.background
Surface(
color = if (color == Color.Unspecified) Color.Transparent else color,
modifier = modifier.fillMaxSize(),
) {
CompositionLocalProvider(
LocalAbsoluteTonalElevation provides 0.dp
) {
content()
}
}
}
| EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/ScreenBackground.kt | 451255658 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import android.net.Uri
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
import coil.transform.CircleCropTransformation
import com.mobiledevpro.ui.theme.lightGreen
import com.mobiledevpro.ui.theme.red
/**
* For Profile screen
*
* Created on Feb 05, 2023.
*
*/
@Composable
fun ProfilePicture(photoUri: Uri, onlineStatus: Boolean, size : ProfilePictureSize, modifier: Modifier = Modifier) {
val pictureSizeDp = when(size) {
ProfilePictureSize.SMALL -> 36.dp
ProfilePictureSize.MEDIUM -> 72.dp
ProfilePictureSize.LARGE -> 144.dp
}
Card(
shape = CircleShape,
border = BorderStroke(
width = 2.dp,
color = if (onlineStatus) MaterialTheme.colorScheme.lightGreen else MaterialTheme.colorScheme.red
),
modifier = modifier,
elevation = CardDefaults.cardElevation(4.dp)
) {
Image(
painter = rememberAsyncImagePainter(
model = ImageRequest.Builder(LocalContext.current)
.data(photoUri)
.size(Size.ORIGINAL) // Set the target size to load the image at.
.transformations(CircleCropTransformation())
.build()
),
contentDescription = "Profile image",
modifier = Modifier.size(pictureSizeDp),
contentScale = ContentScale.Crop
)
}
}
enum class ProfilePictureSize {
SMALL,
MEDIUM,
LARGE
} | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/ProfilePicture.kt | 3697063550 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
/**
* Common navigation bar for bottom menu
*
* Created on Jan 12, 2023.
*
*/
@Composable
fun AppBottomBar(
modifier: Modifier = Modifier,
content: @Composable RowScope.() -> Unit
) {
NavigationBar(
modifier = modifier,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
tonalElevation = 4.dp,
content = content
)
}
@Composable
fun RowScope.AppBottomBarItem(
selected: Boolean,
onClick: () -> Unit,
icon: @Composable () -> Unit,
modifier: Modifier = Modifier,
selectedIcon: @Composable () -> Unit = icon,
enabled: Boolean = true,
label: @Composable (() -> Unit)? = null,
alwaysShowLabel: Boolean = true
) {
NavigationBarItem(
selected = selected,
onClick = onClick,
icon = if (selected) selectedIcon else icon,
modifier = modifier,
enabled = enabled,
label = label,
alwaysShowLabel = alwaysShowLabel,
colors = NavigationBarItemDefaults.colors(
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
selectedTextColor = MaterialTheme.colorScheme.onPrimaryContainer,
unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant,
indicatorColor = MaterialTheme.colorScheme.primaryContainer
)
)
} | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/AppBottomBar.kt | 2601149609 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.component
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
/**
* Default card for list items
*
* Created on May 06, 2023.
*
*/
@Composable
fun CardItem(modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {
Card(
modifier = modifier
.padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 8.dp)
.fillMaxWidth()
.wrapContentHeight(align = Alignment.Top),
elevation = CardDefaults.cardElevation(2.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
),
content = content
)
}
| EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/component/CardItem.kt | 8676294 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.state
interface UIState | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/state/UIState.kt | 2460351078 |
package com.mobiledevpro.ui.vm
import androidx.lifecycle.ViewModel
import com.mobiledevpro.ui.state.UIState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
abstract class BaseViewModel<State : UIState> : ViewModel() {
protected val _uiState: MutableStateFlow<State> = MutableStateFlow(initUIState())
val uiState: StateFlow<State> = _uiState.asStateFlow()
abstract fun initUIState(): State
} | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/vm/BaseViewModel.kt | 2225740005 |
package com.mobiledevpro.ui.theme
import androidx.compose.material3.ColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF006495)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFCBE6FF)
val md_theme_light_onPrimaryContainer = Color(0xFF001E30)
val md_theme_light_secondary = Color(0xFF006781)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFBAEAFF)
val md_theme_light_onSecondaryContainer = Color(0xFF001F29)
val md_theme_light_tertiary = Color(0xFF006496)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFCCE5FF)
val md_theme_light_onTertiaryContainer = Color(0xFF001E31)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFF8FDFF)
val md_theme_light_onBackground = Color(0xFF001F25)
val md_theme_light_surface = Color(0xFFF8FDFF)
val md_theme_light_onSurface = Color(0xFF001F25)
val md_theme_light_surfaceVariant = Color(0xFFDEE3EA)
val md_theme_light_onSurfaceVariant = Color(0xFF41474D)
val md_theme_light_outline = Color(0xFF72787E)
val md_theme_light_inverseOnSurface = Color(0xFFD6F6FF)
val md_theme_light_inverseSurface = Color(0xFF00363F)
val md_theme_light_inversePrimary = Color(0xFF8FCDFF)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF006495)
val md_theme_light_outlineVariant = Color(0xFFC1C7CE)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFF8FCDFF)
val md_theme_dark_onPrimary = Color(0xFF003450)
val md_theme_dark_primaryContainer = Color(0xFF004B71)
val md_theme_dark_onPrimaryContainer = Color(0xFFCBE6FF)
val md_theme_dark_secondary = Color(0xFF5FD4FD)
val md_theme_dark_onSecondary = Color(0xFF003544)
val md_theme_dark_secondaryContainer = Color(0xFF004D62)
val md_theme_dark_onSecondaryContainer = Color(0xFFBAEAFF)
val md_theme_dark_tertiary = Color(0xFF91CDFF)
val md_theme_dark_onTertiary = Color(0xFF003350)
val md_theme_dark_tertiaryContainer = Color(0xFF004B72)
val md_theme_dark_onTertiaryContainer = Color(0xFFCCE5FF)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF001F25)
val md_theme_dark_onBackground = Color(0xFFA6EEFF)
val md_theme_dark_surface = Color(0xFF001F25)
val md_theme_dark_onSurface = Color(0xFFA6EEFF)
val md_theme_dark_surfaceVariant = Color(0xFF41474D)
val md_theme_dark_onSurfaceVariant = Color(0xFFC1C7CE)
val md_theme_dark_outline = Color(0xFF8B9198)
val md_theme_dark_inverseOnSurface = Color(0xFF001F25)
val md_theme_dark_inverseSurface = Color(0xFFA6EEFF)
val md_theme_dark_inversePrimary = Color(0xFF006495)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFF8FCDFF)
val md_theme_dark_outlineVariant = Color(0xFF41474D)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF06283D)
@get:Composable
val ColorScheme.topAppBarColor: Color
get() = seed
@get:Composable
val ColorScheme.lightGreen: Color
get() = Color(0x9932CD32)
@get:Composable
val ColorScheme.red: Color
get() = Color(0x99F44336) | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/theme/Color.kt | 2559703433 |
package com.mobiledevpro.ui.theme
import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
private val LightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim
)
private val DarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun AppTheme(
darkTheme: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = Color.Transparent.toArgb()
window.navigationBarColor = colorScheme.surfaceColorAtElevation(4.dp).toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(color = MaterialTheme.colorScheme.background)
) {
content()
}
}
}
//TODO: it's temporary implementation. Dark mode value should be saved into preferences.
val _darkModeState = MutableStateFlow(true)
val darkModeState: StateFlow<Boolean> = _darkModeState.asStateFlow() | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/theme/Theme.kt | 2573699263 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.ui.theme
| EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/theme/Icon.kt | 3268455922 |
package com.mobiledevpro.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
)
*/
) | EUFriendsChat/core/ui/src/main/kotlin/com/mobiledevpro/ui/theme/Type.kt | 2755444177 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.di
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisallowComposableCalls
import androidx.compose.runtime.remember
import org.koin.compose.module.rememberKoinModules
import org.koin.compose.scope.rememberKoinScope
import org.koin.core.annotation.KoinExperimentalAPI
import org.koin.core.module.Module
import org.koin.core.qualifier.TypeQualifier
import org.koin.core.scope.Scope
import org.koin.ext.getFullName
import org.koin.java.KoinJavaComponent
inline fun <reified T> koinScope(): Scope {
val scopeId = T::class.getFullName() + "@" + T::class.hashCode()
val qualifier = TypeQualifier(T::class)
return KoinJavaComponent.getKoin().getOrCreateScope(scopeId, qualifier)
}
@OptIn(KoinExperimentalAPI::class)
@Composable
inline fun <reified T> rememberViewModel(
crossinline modules: @DisallowComposableCalls () -> List<Module>
): T {
rememberKoinModules(
modules = modules
)
val scope = rememberKoinScope(scope = koinScope<T>())
return remember { scope.get() }
} | EUFriendsChat/core/di/src/main/kotlin/com/mobiledevpro/di/KoinExt.kt | 1685741311 |
package com.mobiledevpro.util/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
object Constant {
const val LOG_TAG_DEBUG = "app.debug"
} | EUFriendsChat/core/util/src/main/kotlin/com/mobiledevpro/util/Constant.kt | 3535718247 |
package com.mobiledevpro.util
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
object TimeUtil {
fun currentTimeStamp(): String = DateTimeFormatter.ofPattern(TIMESTAMP_PATTERN).let { format ->
LocalDateTime.now().format(format)
}
}
private const val TIMESTAMP_PATTERN = "yyyyMMdd_HHmmssSSS" | EUFriendsChat/core/util/src/main/kotlin/com/mobiledevpro/util/TimeUtil.kt | 4161825859 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.mobiledevpro.chatlist.di.featureChatListModule
import com.mobiledevpro.chatlist.view.ChatListScreen
import com.mobiledevpro.chatlist.view.ChatListViewModel
import com.mobiledevpro.di.rememberViewModel
import com.mobiledevpro.home.view.HomeScreen
import com.mobiledevpro.home.view.HomeViewModel
import com.mobiledevpro.navigation.ext.navigateTo
import com.mobiledevpro.navigation.graph.HomeNavGraph
import com.mobiledevpro.navigation.graph.OnBoardingNavGraph
import com.mobiledevpro.navigation.graph.PeopleNavGraph
import com.mobiledevpro.onboarding.view.OnBoardingFirstScreen
import com.mobiledevpro.onboarding.view.OnBoardingScreen
import com.mobiledevpro.onboarding.view.OnBoardingSecondScreen
import com.mobiledevpro.onboarding.view.OnBoardingThirdScreen
import com.mobiledevpro.people.profile.view.PeopleProfileScreen
import com.mobiledevpro.people.profile.view.PeopleProfileViewModel
import com.mobiledevpro.people.profile.view.args.PeopleProfileArgs
import com.mobiledevpro.people.view.PeopleScreen
import com.mobiledevpro.peoplelist.di.featurePeopleListModule
import com.mobiledevpro.peoplelist.view.PeopleListScreen
import com.mobiledevpro.peoplelist.view.PeopleListViewModel
import com.mobiledevpro.subscription.SubscriptionScreen
import com.mobiledevpro.user.profile.di.featureUserProfileModule
import com.mobiledevpro.user.profile.view.ProfileScreen
import com.mobiledevpro.user.profile.view.vm.ProfileViewModel
fun NavGraphBuilder.homeNavGraph(onNavigateToRoot: (Screen) -> Unit) {
composable(
route = Screen.Home.route
) {
Log.d("navigation", "------homeNavGraph:START------------")
//NavController for nested graph
//It will not work for root graph
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
val bottomBar: @Composable () -> Unit = {
Log.d("navigation", "homeNavGraph:bottomBar")
HomeBottomNavigation(
screens = listOf(
Screen.ChatList,
Screen.People,
Screen.Profile
), onNavigateTo = navController::navigateTo,
currentDestination = navBackStackEntry?.destination
)
}
val nestedNavGraph: @Composable () -> Unit = {
Log.d("navigation", "homeNavGraph:nestedNavGraph")
HomeNavGraph(
navController = navController,
onNavigateToRoot = onNavigateToRoot
)
}
val viewModel: HomeViewModel = viewModel()
HomeScreen(
bottomBar = bottomBar,
nestedNavGraph = nestedNavGraph
)
Log.d("navigation", "------homeNavGraph:END------------")
}
}
fun NavGraphBuilder.onBoardingNavGraph(onNavigateToRoot: (Screen) -> Unit) {
composable(
route = Screen.OnBoarding.route
) {
val navController = rememberNavController()
val nestedNavGraph: @Composable () -> Unit = {
OnBoardingNavGraph(
navController = navController
)
}
OnBoardingScreen(
nestedNavGraph,
onNext = {
when (navController.currentDestination?.route) {
Screen.OnBoardingFirst.route -> navController.navigateTo(Screen.OnBoardingSecond)
Screen.OnBoardingSecond.route -> navController.navigateTo(Screen.OnBoardingThird)
Screen.OnBoardingThird.route -> Screen.Home.withClearBackStack()
.also(onNavigateToRoot)
else -> {}
}
}
)
}
}
fun NavGraphBuilder.peopleNavGraph() {
composable(
route = Screen.People.route
) {
val navController = rememberNavController()
val nestedNavGraph: @Composable () -> Unit = {
PeopleNavGraph(
navController = navController
)
}
PeopleScreen(nestedNavGraph)
}
}
fun NavGraphBuilder.onBoardingFirstScreen() {
composable(
route = Screen.OnBoardingFirst.route
) {
OnBoardingFirstScreen()
}
}
fun NavGraphBuilder.onBoardingSecondScreen() {
composable(
route = Screen.OnBoardingSecond.route
) {
OnBoardingSecondScreen()
}
}
fun NavGraphBuilder.onBoardingThirdScreen() {
composable(
route = Screen.OnBoardingThird.route
) {
OnBoardingThirdScreen()
}
}
fun NavGraphBuilder.subscriptionScreen(onNavigateBack: () -> Unit) {
composable(
route = Screen.Subscription.route
) {
SubscriptionScreen(onNavigateBack)
}
}
fun NavGraphBuilder.chatListScreen() {
composable(
route = Screen.ChatList.route
) {
val viewModel = rememberViewModel<ChatListViewModel>(
modules = { listOf(featureChatListModule) }
)
ChatListScreen(
state = viewModel.uiState,
onClick = { chat ->
//TODO: open chat screen
}
)
}
}
fun NavGraphBuilder.peopleListScreen(onNavigateTo: (Screen) -> Unit) {
composable(
route = Screen.PeopleList.route
) {
val viewModel = rememberViewModel<PeopleListViewModel>(
modules = { listOf(featurePeopleListModule) }
)
PeopleListScreen(
viewModel.uiState,
onNavigateToProfile = { profileId: Int ->
Screen.PeopleProfile.routeWith(profileId.toString())
.also(onNavigateTo)
}
)
}
}
fun NavGraphBuilder.peopleProfileScreen(
onNavigateBack: () -> Unit,
onNavigateTo: (Screen) -> Unit
) {
composable(
route = Screen.PeopleProfile.route,
arguments = listOf(
navArgument(PeopleProfileArgs.PEOPLE_PROFILE_ID_ARG) { type = NavType.IntType }
)
) {
val viewModel: PeopleProfileViewModel = viewModel()
val peopleProfile = remember { viewModel.getProfile() }
peopleProfile ?: return@composable
PeopleProfileScreen(
peopleProfile,
onBackPressed = onNavigateBack,
onOpenChatWith = {}
)
}
}
fun NavGraphBuilder.profileScreen(onNavigateTo: (Screen) -> Unit) {
composable(
route = Screen.Profile.route
) {
val viewModel = rememberViewModel<ProfileViewModel>(
modules = {
listOf(featureUserProfileModule)
}
)
ProfileScreen(
state = viewModel.uiState,
onNavigateToSubscription = {
onNavigateTo(Screen.Subscription)
}
)
}
}
| EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/ScreenNavigation.kt | 2341290660 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation
import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import com.mobiledevpro.ui.component.AppBottomBar
import com.mobiledevpro.ui.component.AppBottomBarItem
@Composable
fun HomeBottomNavigation(
screens: List<Screen>,
onNavigateTo: (Screen) -> Unit,
currentDestination: NavDestination?
) {
Log.d("navigation", "HomeBottomNavigation")
AnimatedVisibility(
visible = true,
enter = slideInHorizontally(initialOffsetX = { it }),
exit = slideOutHorizontally(targetOffsetX = { it }),
) {
AppBottomBar {
screens.forEach { screen ->
Log.d("navigation", "HomeBottomNavigation: hierarchy = $currentDestination")
val selected: Boolean =
currentDestination?.hierarchy?.any { it.route == screen.route } ?: false
AppBottomBarItem(
selected = selected,
onClick = { onNavigateTo(screen) },
icon = {
Icon(
imageVector = screen.icon ?: Icons.Default.Warning,
contentDescription = null
)
},
label = { Text(text = screen.title ?: "") }
)
}
}
}
} | EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/HomeBottomNavigation.kt | 3581184799 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation.ext
import android.util.Log
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import com.mobiledevpro.navigation.Screen
fun NavController.navigateTo(
screen: Screen
) {
val currentRoute: String? = this.currentBackStackEntry?.destination?.route
val route = screen.routePath?.let { routePath ->
screen.route.replaceAfter("/", routePath)
} ?: screen.route
Log.d("navigation", "navigateTo: ${screen.route}")
navigate(route) {
Log.d("navigation", "findStartDestination: ${graph.findStartDestination()}")
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
popUpTo(graph.findStartDestination().id) {
saveState = true
}
// Avoid multiple copies of the same destination when
// reselecting the same item
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = screen.restoreState
//Clearing back stack up to certain screen if required
if (screen.clearBackStack && !currentRoute.isNullOrEmpty())
popUpTo(currentRoute) {
inclusive = true
}
}
} | EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/ext/NavControllerExt.kt | 247806775 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation.graph
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import com.mobiledevpro.navigation.Screen
import com.mobiledevpro.navigation.onBoardingFirstScreen
import com.mobiledevpro.navigation.onBoardingSecondScreen
import com.mobiledevpro.navigation.onBoardingThirdScreen
/**
* Nested navigation graph for OnBoarding screen
*
* Created on Jan 24, 2023.
*
*/
@Composable
fun OnBoardingNavGraph(
modifier: Modifier = Modifier,
navController: NavHostController
) {
NavHost(
navController = navController,
startDestination = Screen.OnBoardingFirst.route,
modifier = modifier,
) {
onBoardingFirstScreen()
onBoardingSecondScreen()
onBoardingThirdScreen()
}
} | EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/graph/OnBoardingNavGraph.kt | 1971248060 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation.graph
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import com.mobiledevpro.navigation.Screen
import com.mobiledevpro.navigation.ext.navigateTo
import com.mobiledevpro.navigation.peopleListScreen
import com.mobiledevpro.navigation.peopleProfileScreen
/**
* Nested navigation graph for People screen
*
* Created on Feb 04, 2023.
*
*/
@Composable
fun PeopleNavGraph(
modifier: Modifier = Modifier,
navController: NavHostController
) {
NavHost(
navController = navController,
startDestination = Screen.PeopleList.route,
modifier = modifier,
) {
peopleListScreen(onNavigateTo = navController::navigateTo)
peopleProfileScreen(
onNavigateTo = navController::navigateTo,
onNavigateBack = navController::navigateUp
)
}
} | EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/graph/PeopleNavGraph.kt | 2613511892 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation.graph
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import com.mobiledevpro.navigation.Screen
import com.mobiledevpro.navigation.chatListScreen
import com.mobiledevpro.navigation.peopleNavGraph
import com.mobiledevpro.navigation.profileScreen
/**
* Nested navigation graph for Home screen
*
* Created on Jan 24, 2023.
*
*/
@Composable
fun HomeNavGraph(
modifier: Modifier = Modifier,
navController: NavHostController,
onNavigateToRoot: (Screen) -> Unit
) {
NavHost(
navController = navController,
startDestination = Screen.ChatList.route,
modifier = modifier,
) {
chatListScreen()
peopleNavGraph()
profileScreen(onNavigateTo = onNavigateToRoot)
}
} | EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/graph/HomeNavGraph.kt | 4279708520 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation.graph
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import com.mobiledevpro.navigation.Screen
import com.mobiledevpro.navigation.ext.navigateTo
import com.mobiledevpro.navigation.homeNavGraph
import com.mobiledevpro.navigation.onBoardingNavGraph
import com.mobiledevpro.navigation.subscriptionScreen
/**
* Top-level navigation host in the app
*
* Created on Jan 07, 2023.
*
*/
@Composable
fun RootNavGraph(
navController: NavHostController,
modifier: Modifier = Modifier,
startDestination: Screen
) {
NavHost(
navController = navController,
route = "root_host",
startDestination = startDestination.route,
modifier = modifier,
) {
val navigateBack: () -> Unit = {
navController.navigateUp()
}
//Nested Navigation Graphs
onBoardingNavGraph(onNavigateToRoot = navController::navigateTo)
homeNavGraph(onNavigateToRoot = navController::navigateTo)
//Root screens
subscriptionScreen(onNavigateBack = navigateBack)
}
} | EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/graph/RootNavGraph.kt | 525229983 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.navigation
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.Person
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.ui.graphics.vector.ImageVector
import com.mobiledevpro.people.profile.view.args.PeopleProfileArgs
const val navigationRouteOnBoarding = "on_boarding"
const val navigationRouteOnBoardingFirst = "on_boarding_first"
const val navigationRouteOnBoardingSecond = "on_boarding_second"
const val navigationRouteOnBoardingThird = "on_boarding_third"
const val navigationRouteHome = "home"
const val navigationRouteChatList = "chat_list"
const val navigationRouteProfile = "profile"
const val navigationRoutePeople = "people"
const val navigationRoutePeopleList = "people_list"
const val navigationRoutePeopleProfile =
"people_profile/{${PeopleProfileArgs.PEOPLE_PROFILE_ID_ARG}}"
const val navigationRouteSubscription = "subscription"
sealed class Screen(
val route: String,
var routePath: String? = null,
var clearBackStack: Boolean = false,
val restoreState: Boolean = true,
val title: String? = null,
val icon: ImageVector? = null
) {
fun withClearBackStack() = apply { clearBackStack = true }
fun routeWith(path: String) = apply {
routePath = path
}
object OnBoarding : Screen(navigationRouteOnBoarding)
object OnBoardingFirst : Screen(navigationRouteOnBoardingFirst)
object OnBoardingSecond : Screen(navigationRouteOnBoardingSecond)
object OnBoardingThird : Screen(navigationRouteOnBoardingThird)
object Home : Screen(navigationRouteHome)
// 3 tabs of Bottom navigation
object ChatList :
Screen(route = navigationRouteChatList, title = "Chats", icon = Icons.Rounded.Home)
object People : Screen(
route = navigationRoutePeople,
restoreState = false,
title = "People",
icon = Icons.Rounded.Person,
)
object Profile :
Screen(route = navigationRouteProfile, title = "Profile", icon = Icons.Rounded.Settings)
object Subscription : Screen(navigationRouteSubscription)
object PeopleList : Screen(navigationRoutePeopleList)
object PeopleProfile : Screen(navigationRoutePeopleProfile)
} | EUFriendsChat/core/navigation/src/main/kotlin/com/mobiledevpro/navigation/Route.kt | 1510359461 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.coroutines
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
// Based on: https://proandroiddev.com/resilient-use-cases-with-kotlin-result-coroutines-and-annotations-511df10e2e16
/**
* Like [runCatching], but with proper coroutines cancellation handling. Also only catches [Exception] instead of [Throwable].
*
* Cancellation exceptions need to be rethrown. See https://github.com/Kotlin/kotlinx.coroutines/issues/1814.
*/
/*
inline fun <R> resultOf(block: () -> R): Result<R> {
return try {
Result.success(block())
} catch (t: TimeoutCancellationException) {
Result.failure(t)
} catch (c: CancellationException) {
throw c
} catch (e: Exception) {
Result.failure(e)
}
}
*/
/**
* Like [runCatching], but with proper coroutines cancellation handling. Also only catches [Exception] instead of [Throwable].
*
* Cancellation exceptions need to be rethrown. See https://github.com/Kotlin/kotlinx.coroutines/issues/1814.
*/
inline fun <T, R> T.resultOf(block: T.() -> R): Result<R> {
return try {
Result.success(block())
} catch (t: TimeoutCancellationException) {
Result.failure(t)
} catch (c: CancellationException) {
throw c
} catch (e: Exception) {
Result.failure(e)
}
}
/**
* Like [mapCatching], but uses [resultOf] instead of [runCatching].
*/
inline fun <R, T> Result<T>.mapResult(transform: (value: T) -> R): Result<R> {
val successResult = getOrNull()
return when {
successResult != null -> resultOf { transform(successResult) }
else -> Result.failure(exceptionOrNull() ?: error("Unreachable state"))
}
}
@OptIn(ExperimentalContracts::class)
inline fun <R, T> Result<T>.andThen(transform: (value: T) -> Result<R>): Result<R> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
val successResult = getOrNull()
return when {
successResult != null -> transform(successResult)
else -> Result.failure(exceptionOrNull() ?: error("Unreachable state"))
}
}
@OptIn(ExperimentalContracts::class)
inline fun <R, T> Result<T>.andThenFlow(transform: (value: T) -> Flow<Result<R>>): Flow<Result<R>> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
val successResult: T? = getOrNull()
return when {
successResult != null -> transform(successResult)
else -> flowOf(Result.failure(exceptionOrNull() ?: error("Unreachable state")))
}
}
class None
| EUFriendsChat/core/coroutines/src/main/kotlin/com/mobiledevpro/coroutines/ResultExt.kt | 1824242485 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.coroutines
import android.util.Log
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Base UseCase with Coroutines
*
* Created on Sep 12, 2022.
*
*/
abstract class BaseCoroutinesUseCase<Results, in Params>(
executionDispatcher: CoroutineDispatcher
) : BaseUseCase(executionDispatcher) {
abstract suspend fun buildUseCase(params: Params? = null): Results
suspend fun execute(params: Params? = null): Result<Results> =
withContext(dispatcher) {
try {
if (dispatcher == Dispatchers.Main)
throw RuntimeException("Use case '${this::class.simpleName}' cannot be executed in $dispatcher")
resultOf {
[email protected](params)
}
} catch (t: Throwable) {
logException(t.message ?: t.cause?.message ?: t.toString())
Result.failure(t)
} catch (e: Exception) {
logException(e.localizedMessage ?: e.cause?.message ?: e.toString())
Result.failure(Throwable(e.localizedMessage))
}
}
override fun logException(errMessage: String) {
Log.e(this::class.simpleName, "${this::class.simpleName} : $errMessage")
}
} | EUFriendsChat/core/coroutines/src/main/kotlin/com/mobiledevpro/coroutines/BaseCoroutinesUseCase.kt | 102836724 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.coroutines
import kotlinx.coroutines.CoroutineDispatcher
/**
* Base UseCase
*
* Created on Sep 12, 2022.
*
*/
abstract class BaseUseCase(
executionDispatcher: CoroutineDispatcher
) {
protected val dispatcher = executionDispatcher
abstract fun logException(errMessage: String)
} | EUFriendsChat/core/coroutines/src/main/kotlin/com/mobiledevpro/coroutines/BaseUseCase.kt | 1713098378 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.coroutines
import android.util.Log
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
/**
* Base UseCase for Coroutines Flow result
*
* Created on Sep 12, 2022.
*
*/
abstract class BaseCoroutinesFLowUseCase<Results, in Params>(
executionDispatcher: CoroutineDispatcher
) : BaseUseCase(executionDispatcher) {
abstract fun buildUseCaseFlow(params: Params? = null): Flow<Results>
fun execute(params: Params? = null): Flow<Result<Results>> =
try {
if (dispatcher == Dispatchers.Main)
throw RuntimeException("Use case '${this::class.simpleName}' cannot be executed in $dispatcher")
this.buildUseCaseFlow(params)
.flowOn(dispatcher)
.map {
resultOf { it }
}
} catch (e: Exception) {
logException(e.localizedMessage ?: e.cause?.message ?: e.toString())
flowOf(Result.failure(Throwable(e.localizedMessage)))
} catch (t: Throwable) {
logException(t.message ?: t.cause?.message ?: t.toString())
flowOf(Result.failure(t))
}
override fun logException(errMessage: String) {
Log.e(this::class.simpleName, "${this::class.simpleName} : $errMessage")
}
} | EUFriendsChat/core/coroutines/src/main/kotlin/com/mobiledevpro/coroutines/BaseCoroutinesFLowUseCase.kt | 897869945 |
package com.mobiledevpro.domain.model
import android.net.Uri
/**
* Chat
*
* Created on May 06, 2023.
*
*/
data class Chat(
val user: UserProfile,
val peopleList: List<PeopleProfile>,
val unreadMsgCount : Int = 0
)
val fakeUser = UserProfile(
name = "Joe Black",
nickname = "@nickname",
status = true,
photo = Uri.parse("https://media.istockphoto.com/id/1090878494/photo/close-up-portrait-of-young-smiling-handsome-man-in-blue-polo-shirt-isolated-on-gray-background.jpg?b=1&s=170667a&w=0&k=20&c=c3TaqVe9-0EcHl7mjO-9YChSvGBDhvzUai6obs1Ibz4=")
)
val fakeChatList = arrayListOf(
Chat(
user = fakeUser,
peopleList = fakePeopleProfileList.take(5).sortedByDescending { !it.status },
unreadMsgCount = 100
),
Chat(
user = fakeUser,
peopleList = fakePeopleProfileList.takeLast(3).sortedByDescending { !it.status },
unreadMsgCount = 0
),
Chat(
user = fakeUser,
peopleList = listOf(fakePeopleProfileList[6]),
unreadMsgCount = 3
)
)
fun Chat.name() : String =
this.peopleList.toChatName()
| EUFriendsChat/core/domain/src/main/kotlin/com/mobiledevpro/domain/model/Chat.kt | 2198967537 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.domain.model
import android.net.Uri
/**
* Profile
*
* Created on Feb 04, 2023.
*
*/
data class PeopleProfile(
val id: Int,
val name: String,
val status: Boolean,
val photo: Uri? = null
) {
fun listKey(): String = "${id}_${name.replace("\\s+".toRegex(), "")}"
}
val fakePeopleProfileList = arrayListOf(
PeopleProfile(
id = 0,
name = "Michaela Runnings",
status = true,
Uri.parse("https://images.unsplash.com/photo-1485290334039-a3c69043e517?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80")
),
PeopleProfile(
id = 1,
name = "John Pestridge",
status = false,
Uri.parse("https://images.unsplash.com/photo-1542178243-bc20204b769f?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 2,
name = "Manilla Andrews",
status = true,
Uri.parse("https://images.unsplash.com/photo-1543123820-ac4a5f77da38?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NDh8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 3,
name = "Dan Spicer",
status = false,
Uri.parse("https://images.unsplash.com/photo-1595152772835-219674b2a8a6?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NDd8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 4,
name = "Keanu Dester",
status = false,
Uri.parse("https://images.unsplash.com/photo-1597528380214-aa94bde3fc32?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NTZ8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 5,
name = "Anichu Patel",
status = false,
Uri.parse("https://images.unsplash.com/photo-1598641795816-a84ac9eac40c?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NjJ8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 6,
name = "Kienla Onso",
status = true,
Uri.parse("https://images.unsplash.com/photo-1566895733044-d2bdda8b6234?ixid=MXwxMjA3fDB8MHxzZWFyY2h8ODh8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 7,
name = "Andra Matthews",
status = false,
Uri.parse("https://images.unsplash.com/photo-1530577197743-7adf14294584?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NTV8fHBvcnRyYWl0fGVufDB8MnwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 8,
name = "Georgia S.", status = false,
Uri.parse("https://images.unsplash.com/photo-1547212371-eb5e6a4b590c?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTA3fHxwb3J0cmFpdHxlbnwwfDJ8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 8,
name = "Matt Dengo",
status = false,
Uri.parse("https://images.unsplash.com/photo-1578176603894-57973e38890f?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTE0fHxwb3J0cmFpdHxlbnwwfDJ8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 9,
name = "Marsha T.",
status = true,
Uri.parse("https://images.unsplash.com/photo-1605087880595-8cc6db61f3c6?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTI0fHxwb3J0cmFpdHxlbnwwfDJ8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
),
PeopleProfile(
id = 10,
name = "Invshu Patel",
status = true,
Uri.parse("https://images.unsplash.com/photo-1561820009-8bef03ebf8e5?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTM3fHxwb3J0cmFpdHxlbnwwfDJ8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60")
)
)
fun List<PeopleProfile>.toChatName(): String =
mapTo(ArrayList<String>()) { profile -> profile.name }.let { names ->
val stringBuilder = StringBuilder()
names.onEachIndexed { index, s ->
if (index > 0)
stringBuilder.append(", ")
stringBuilder.append(s)
}
stringBuilder.toString()
} | EUFriendsChat/core/domain/src/main/kotlin/com/mobiledevpro/domain/model/PeopleProfile.kt | 1040475093 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.domain.model
import android.net.Uri
/**
* App User Profile
*
* Created on Feb 04, 2023.
*
*/
data class UserProfile(
val name : String,
val nickname: String,
val status: Boolean = false,
val photo : Uri = Uri.EMPTY
)
| EUFriendsChat/core/domain/src/main/kotlin/com/mobiledevpro/domain/model/UserProfile.kt | 700756158 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.app.ui
import androidx.compose.runtime.Composable
import androidx.navigation.compose.rememberNavController
import com.mobiledevpro.navigation.Screen
import com.mobiledevpro.navigation.graph.RootNavGraph
@Composable
fun MainApp() {
val navController = rememberNavController()
RootNavGraph(
navController = navController,
startDestination = Screen.Home
)
} | EUFriendsChat/app/src/main/kotlin/com/mobiledevpro/app/ui/MainApp.kt | 3891964070 |
package com.mobiledevpro.app
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.getValue
import androidx.core.view.WindowCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.mobiledevpro.app.ui.MainApp
import com.mobiledevpro.ui.theme.AppTheme
import com.mobiledevpro.ui.theme.darkModeState
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//False - allows to drawing the content "edge-to-edge"
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
val darkModeState by darkModeState.collectAsStateWithLifecycle()
AppTheme(darkTheme = darkModeState) {
MainApp()
}
}
}
} | EUFriendsChat/app/src/main/kotlin/com/mobiledevpro/app/MainActivity.kt | 1864461419 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.app
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
class App : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
// Log Koin into Android logger
androidLogger()
// Reference Android context
androidContext(this@App)
// Load common modules (feature modules will be loaded on demand)
// modules(myAppModules)
}
}
} | EUFriendsChat/app/src/main/kotlin/com/mobiledevpro/app/Application.kt | 3425180430 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalog
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.getByType
import kotlin.jvm.optionals.getOrNull
internal val Project.libs: VersionCatalog
get() = extensions.getByType<VersionCatalogsExtension>().named("libs")
internal val VersionCatalog.plugins: List<String>
get() = pluginAliases
internal fun VersionCatalog.versionStr(alias: String): String =
this.findVersion(alias).getOrNull()?.toString() ?: ""
internal fun VersionCatalog.versionInt(alias: String): Int =
versionStr(alias).toInt()
internal fun VersionCatalog.library(alias: String) =
findLibrary(alias).get()
internal fun VersionCatalog.bundle(alias: String) =
findBundle(alias).get()
| EUFriendsChat/build-logic/src/main/kotlin/VersionCatalogExt.kt | 2130350856 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.home.view
import androidx.lifecycle.ViewModel
/**
* Home screen
*
* Created on Jan 24, 2023.
*
*/
class HomeViewModel : ViewModel() {
} | EUFriendsChat/feature/home/src/main/kotlin/com/mobiledevpro/home/view/HomeViewModel.kt | 1982136130 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.home.view
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.mobiledevpro.ui.component.ScreenBackground
@Composable
fun HomeScreen(
nestedNavGraph: @Composable () -> Unit,
bottomBar: @Composable () -> Unit
) {
Scaffold(
bottomBar = bottomBar,
contentWindowInsets = WindowInsets(left = 0, top = 0, right = 0, bottom = 0)
) { paddingValues ->
ScreenBackground(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
) {
nestedNavGraph.invoke()
}
}
} | EUFriendsChat/feature/home/src/main/kotlin/com/mobiledevpro/home/view/HomeScreen.kt | 2164860022 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.chatlist.di
import com.mobiledevpro.chatlist.domain.usecase.GetChatListUseCase
import com.mobiledevpro.chatlist.view.ChatListViewModel
import org.koin.androidx.viewmodel.dsl.viewModelOf
import org.koin.core.module.dsl.scopedOf
import org.koin.dsl.module
/**
* User Profile screen module
*
* Created on Jul 22, 2023.
*
*/
val featureChatListModule = module {
scope<ChatListViewModel> {
viewModelOf(::ChatListViewModel)
scopedOf(::GetChatListUseCase)
}
} | EUFriendsChat/feature/chat_list/src/main/kotlin/com/mobiledevpro/chatlist/di/Module.kt | 2018826627 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.chatlist.view
import com.mobiledevpro.domain.model.Chat
import com.mobiledevpro.ui.state.UIState
/**
* UI state for [com.mobiledevpro.chatlist.view.ChatListScreen]
*
* Created on Feb 04, 2023.
*
*/
sealed interface ChatListUIState : UIState {
data object Empty : ChatListUIState
data object Loading : ChatListUIState
class Success(val profileList : List<Chat>) : ChatListUIState
class Fail(val throwable: Throwable) : ChatListUIState
} | EUFriendsChat/feature/chat_list/src/main/kotlin/com/mobiledevpro/chatlist/view/ChatListUIState.kt | 3225737715 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.chatlist.view
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.mobiledevpro.chatlist.domain.usecase.GetChatListUseCase
import com.mobiledevpro.ui.vm.BaseViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class ChatListViewModel(
private val getChatListUseCase: GetChatListUseCase
) : BaseViewModel<ChatListUIState>() {
override fun initUIState(): ChatListUIState = ChatListUIState.Empty
init {
Log.d("UI", "ChatListViewModel init")
observeChatList()
}
private fun observeChatList() {
getChatListUseCase.execute()
.onEach { result ->
result.onSuccess { list ->
ChatListUIState.Success(list)
.also { _uiState.value = it }
}.onFailure {
//TODO: show an error
}
}.launchIn(viewModelScope)
}
} | EUFriendsChat/feature/chat_list/src/main/kotlin/com/mobiledevpro/chatlist/view/ChatListViewModel.kt | 1107410362 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.chatlist.view.component
import android.net.Uri
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Badge
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mobiledevpro.domain.model.Chat
import com.mobiledevpro.domain.model.PeopleProfile
import com.mobiledevpro.domain.model.fakePeopleProfileList
import com.mobiledevpro.domain.model.fakeUser
import com.mobiledevpro.domain.model.name
import com.mobiledevpro.ui.component.CardItem
import com.mobiledevpro.ui.component.ProfilePicture
import com.mobiledevpro.ui.component.ProfilePictureSize
import com.mobiledevpro.ui.theme.AppTheme
/**
* Fo chat list screen
*
* Created on May 06, 2023.
*
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ChatCard(
modifier: Modifier = Modifier,
chat: Chat,
onClick: () -> Unit
) {
CardItem(
modifier = modifier
.clickable { onClick.invoke() }
) {
Box {
Row(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 24.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
ChatPicture(
profileList = chat.peopleList
)
Text(
text = chat.name(),
style = MaterialTheme.typography.bodyMedium,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(horizontal = 8.dp)
)
}
if (chat.unreadMsgCount > 0)
Badge(
containerColor = MaterialTheme.colorScheme.tertiary,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(8.dp)
) {
Text(
text = if (chat.unreadMsgCount > 99) "99+" else chat.unreadMsgCount.toString(),
style = MaterialTheme.typography.labelSmall
)
}
}
}
}
@Composable
fun ChatPicture(profileList: List<PeopleProfile>, modifier: Modifier = Modifier) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(modifier = modifier) {
profileList.take(VISIBLE_PROFILES_COUNT).forEachIndexed { index, profile ->
ProfilePicture(
profile.photo ?: Uri.EMPTY,
profile.status,
size = ProfilePictureSize.SMALL,
modifier = Modifier.padding(start = 16.dp * index)
)
}
}
if (profileList.size > VISIBLE_PROFILES_COUNT)
Text(
text = "+${profileList.size - 3}",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(4.dp)
)
}
}
@Composable
@Preview
fun ChatCardPreview() {
val peopleList = fakePeopleProfileList.take(2).sortedByDescending { !it.status }
val chat = Chat(fakeUser, peopleList)
AppTheme {
ChatCard(
chat = chat,
onClick = {})
}
}
const val VISIBLE_PROFILES_COUNT = 3 | EUFriendsChat/feature/chat_list/src/main/kotlin/com/mobiledevpro/chatlist/view/component/ChatCard.kt | 1376578862 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.chatlist.view
import android.widget.Toast
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.mobiledevpro.chatlist.view.component.ChatCard
import com.mobiledevpro.domain.model.Chat
import com.mobiledevpro.domain.model.fakeChatList
import com.mobiledevpro.ui.component.ScreenBackground
import com.mobiledevpro.ui.ext.dp
import com.mobiledevpro.ui.ext.statusBarHeight
import com.mobiledevpro.ui.theme.AppTheme
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@Composable
fun ChatListScreen(
state: StateFlow<ChatListUIState>,
onClick: (Chat) -> Unit
) {
val uiState by state.collectAsStateWithLifecycle()
val context = LocalContext.current
ScreenBackground(
modifier = Modifier
.fillMaxSize()
) {
when (uiState) {
is ChatListUIState.Loading -> Loading()
is ChatListUIState.Empty -> NoChatFound()
is ChatListUIState.Success ->
ChatList(
chatList = (uiState as ChatListUIState.Success).profileList,
onClick = onClick
)
is ChatListUIState.Fail -> {
NoChatFound()
LaunchedEffect(Unit) {
Toast.makeText(
context,
(uiState as ChatListUIState.Fail).throwable.localizedMessage,
Toast.LENGTH_LONG
).show()
}
}
}
}
}
@Composable
private fun ChatList(chatList: List<Chat>, onClick: (Chat) -> Unit) {
//Cause content is drawn edge-to-edge, let's set the top-padding for the first element in the list
val statusBarHeight: Dp = WindowInsets.statusBarHeight().dp()
LazyColumn {
itemsIndexed(chatList) { index, chat ->
ChatCard(
modifier = Modifier.then(
if (index == 0)
Modifier.padding(top = statusBarHeight)
else
Modifier
),
chat = chat,
onClick = { onClick(chat) }
)
}
}
}
@Composable
private fun NoChatFound() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "No chat found",
modifier = Modifier
.padding(16.dp)
.align(Alignment.Center),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Composable
private fun Loading() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "Loading...", modifier = Modifier
.padding(16.dp)
.align(Alignment.Center),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Composable
@Preview
fun ChatListScreenPreview() {
AppTheme {
ChatListScreen(
state = MutableStateFlow(ChatListUIState.Success(fakeChatList)),
onClick = {}
)
}
} | EUFriendsChat/feature/chat_list/src/main/kotlin/com/mobiledevpro/chatlist/view/ChatListScreen.kt | 1198494993 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.chatlist.domain.usecase
import com.mobiledevpro.coroutines.BaseCoroutinesFLowUseCase
import com.mobiledevpro.coroutines.None
import com.mobiledevpro.domain.model.Chat
import com.mobiledevpro.domain.model.fakeChatList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
class GetChatListUseCase(
) : BaseCoroutinesFLowUseCase<List<Chat>, None>(Dispatchers.IO) {
override fun buildUseCaseFlow(params: None?): Flow<List<Chat>> =
flowOf(fakeChatList)
} | EUFriendsChat/feature/chat_list/src/main/kotlin/com/mobiledevpro/chatlist/domain/usecase/GetChatListUseCase.kt | 3426400335 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.subscription
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
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.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mobiledevpro.ui.component.ScreenBackground
import com.mobiledevpro.ui.theme.AppTheme
@Composable
fun SubscriptionScreen(onNavigateBack: () -> Unit) {
val context = LocalContext.current
val showToast: (message: String) -> Unit = { message ->
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
Scaffold(
contentWindowInsets = WindowInsets.systemBars
) { paddingValues ->
ScreenBackground(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "Be like a Pro",
style = MaterialTheme.typography.titleLarge,
modifier = Modifier
.align(Alignment.TopCenter)
.padding(16.dp)
)
Column(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.Center),
verticalArrangement = Arrangement.Center
) {
Text(
text = "Subscribe on",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(16.dp)
.align(Alignment.CenterHorizontally)
.fillMaxWidth(),
style = MaterialTheme.typography.bodyLarge
)
SubsButton(
text = "1 Month - 0.9\$",
modifier = Modifier.align(Alignment.CenterHorizontally)
) {
showToast("Subscribing to 1 month...")
onNavigateBack()
}
SubsButton(
text = "6 Months - 3.99\$",
modifier = Modifier.align(Alignment.CenterHorizontally)
) {
showToast("Subscribing to 6 months...")
onNavigateBack()
}
SubsButton(
text = "1 Year - 6.99\$",
modifier = Modifier.align(Alignment.CenterHorizontally)
) {
showToast("Subscribing to 1 year...")
onNavigateBack()
}
}
}
/*
Column(
modifier = Modifier
.padding(16.dp)
.verticalScroll(rememberScrollState())
.height(IntrinsicSize.Max)
) {
Header()
//If you remove Items, Footer will be centered at the screen as you could see on attached screenshots
Item(text = "Item 1")
Item(text = "Item 2")
Item(text = "Item 3")
Box(
modifier = Modifier
.fillMaxSize()
//.background(color = Color.Blue)
) {
Footer(modifier = Modifier.align(Alignment.Center))
}
}
*/
}
}
}
/*
@Composable
fun Header() {
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.background(color = Color.Yellow)
)
}
@Composable
fun Item(text: String) {
Box(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth()
.height(50.dp)
.background(color = Color.White)
) {
Text(
text = text,
modifier = Modifier.align(Alignment.Center),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Composable
fun Footer(modifier: Modifier) {
Box(
modifier = modifier
.padding(vertical = 8.dp)
.fillMaxWidth()
.height(100.dp)
.background(color = Color.Gray)
) {
Text(
text = "Optional block",
modifier = Modifier.align(Alignment.Center),
style = MaterialTheme.typography.bodyLarge
)
}
}
*/
@Composable
fun SubsButton(
text: String,
modifier: Modifier,
onClick: () -> Unit
) {
Button(
onClick = onClick,
modifier = modifier
.padding(8.dp)
.defaultMinSize(minWidth = 192.dp, minHeight = 48.dp)
) {
Text(text = text)
}
}
@Preview
@Composable
fun SubscriptionScreenPreview() {
AppTheme {
SubscriptionScreen {}
}
} | EUFriendsChat/feature/subscription/src/main/kotlin/com/mobiledevpro/subscription/SubscriptionScreen.kt | 3713633752 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.peoplelist
import app.cash.turbine.test
import com.mobiledevpro.peoplelist.domain.usecase.GetPeopleListUseCase
import com.mobiledevpro.peoplelist.view.PeopleListViewModel
import com.mobiledevpro.peoplelist.view.PeopleProfileUIState
import com.mobiledevpro.ui.state.UIState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class PeopleListViewModelTest {
private lateinit var vm: PeopleListViewModel
@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setUp() {
Dispatchers.setMain(StandardTestDispatcher())
val useCase = GetPeopleListUseCase()
vm = PeopleListViewModel(getPeopleListUseCase = useCase)
assertTrue(
"Initial state is incorrect: ${vm.uiState.value}",
(vm.uiState.value as UIState) == PeopleProfileUIState.Loading
)
}
@Test
fun stateTest() = runTest {
vm.uiState.test {
// assertEquals("State is not Loading", PeopleProfileUIState.Loading, awaitItem())
assertTrue(
"People list is empty",
(awaitItem() as PeopleProfileUIState.Success).profileList.isNotEmpty()
)
}
}
@After
fun finish() = Dispatchers.resetMain()
} | EUFriendsChat/feature/people_list/src/test/kotlin/com/mobiledevpro/peoplelist/PeopleListViewModelTest.kt | 4207471807 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.peoplelist.di
import com.mobiledevpro.peoplelist.domain.usecase.GetPeopleListUseCase
import com.mobiledevpro.peoplelist.view.PeopleListViewModel
import org.koin.androidx.viewmodel.dsl.viewModelOf
import org.koin.core.module.dsl.scopedOf
import org.koin.dsl.module
/**
* User Profile screen module
*
* Created on Jul 22, 2023.
*
*/
val featurePeopleListModule = module {
scope<PeopleListViewModel> {
viewModelOf(::PeopleListViewModel)
scopedOf(::GetPeopleListUseCase)
}
} | EUFriendsChat/feature/people_list/src/main/kotlin/com/mobiledevpro/peoplelist/di/Module.kt | 2232321465 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.peoplelist.view
import androidx.lifecycle.viewModelScope
import com.mobiledevpro.peoplelist.domain.usecase.GetPeopleListUseCase
import com.mobiledevpro.ui.vm.BaseViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class PeopleListViewModel(
private val getPeopleListUseCase: GetPeopleListUseCase
) : BaseViewModel<PeopleProfileUIState>() {
override fun initUIState(): PeopleProfileUIState = PeopleProfileUIState.Loading
init {
observePeopleList()
}
private fun observePeopleList() {
getPeopleListUseCase.execute()
.onEach { result ->
result.onSuccess { list ->
PeopleProfileUIState.Success(list)
.also { _uiState.value = it }
}.onFailure {
//TODO: show error
}
}.launchIn(viewModelScope)
}
} | EUFriendsChat/feature/people_list/src/main/kotlin/com/mobiledevpro/peoplelist/view/PeopleListViewModel.kt | 1666506290 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.peoplelist.view
import android.widget.Toast
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.mobiledevpro.domain.model.PeopleProfile
import com.mobiledevpro.peoplelist.view.component.ProfileCard
import com.mobiledevpro.ui.component.ScreenBackground
import com.mobiledevpro.ui.ext.dp
import com.mobiledevpro.ui.ext.statusBarHeight
import com.mobiledevpro.ui.theme.AppTheme
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@Composable
fun PeopleListScreen(
stateFlow: StateFlow<PeopleProfileUIState>,
onNavigateToProfile: (profileId: Int) -> Unit
) {
val uiState by stateFlow.collectAsStateWithLifecycle()
val context = LocalContext.current
ScreenBackground(
modifier = Modifier
.fillMaxSize()
) {
when (uiState) {
is PeopleProfileUIState.Loading -> Loading()
is PeopleProfileUIState.Empty -> NoPeopleFound()
is PeopleProfileUIState.Success ->
PeopleList(
list = (uiState as PeopleProfileUIState.Success).profileList,
onProfileClick = onNavigateToProfile
)
is PeopleProfileUIState.Fail -> {
NoPeopleFound()
LaunchedEffect(Unit) {
Toast.makeText(
context,
(uiState as PeopleProfileUIState.Fail).throwable.localizedMessage,
Toast.LENGTH_LONG
).show()
}
}
}
}
}
@Composable
private fun NoPeopleFound() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "No people found",
modifier = Modifier
.padding(16.dp)
.align(Alignment.Center),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Composable
private fun Loading() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "Loading...", modifier = Modifier
.padding(16.dp)
.align(Alignment.Center),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Composable
private fun PeopleList(list: List<PeopleProfile>, onProfileClick: (profileId: Int) -> Unit) {
//Cause content is drawn edge-to-edge, let's set the top-padding for the first element in the list
val statusBarHeight: Dp = WindowInsets.statusBarHeight().dp()
LazyColumn {
itemsIndexed(
items = list,
key = { _, item -> item.listKey() }
) { index, profile ->
ProfileCard(
modifier = Modifier.then(
if (index == 0)
Modifier.padding(top = statusBarHeight)
else
Modifier
),
item = profile,
onClick = { onProfileClick(profile.id) })
}
}
}
@Preview
@Composable
fun PeopleListPreview() {
AppTheme {
PeopleListScreen(
stateFlow = MutableStateFlow(PeopleProfileUIState.Empty),
onNavigateToProfile = { }
)
}
} | EUFriendsChat/feature/people_list/src/main/kotlin/com/mobiledevpro/peoplelist/view/PeopleListScreen.kt | 724689975 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.peoplelist.view.component
import android.net.Uri
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.mobiledevpro.domain.model.PeopleProfile
import com.mobiledevpro.ui.component.CardItem
import com.mobiledevpro.ui.component.ProfileContent
import com.mobiledevpro.ui.component.ProfilePicture
import com.mobiledevpro.ui.component.ProfilePictureSize
/**
* For People list
*
* Created on Feb 05, 2023.
*
*/
@Composable
internal fun ProfileCard(modifier: Modifier = Modifier, item: PeopleProfile, onClick: () -> Unit) {
CardItem(
modifier = modifier
.clickable { onClick.invoke() }
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
ProfilePicture(
item.photo ?: Uri.EMPTY,
item.status,
size = ProfilePictureSize.MEDIUM,
modifier = Modifier.padding(16.dp)
)
ProfileContent(
userName = item.name,
subName = null,
isOnline = item.status,
alignment = Alignment.Start,
modifier = Modifier.padding(8.dp)
)
}
}
} | EUFriendsChat/feature/people_list/src/main/kotlin/com/mobiledevpro/peoplelist/view/component/ProfileCard.kt | 3398393070 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.peoplelist.view
import com.mobiledevpro.domain.model.PeopleProfile
import com.mobiledevpro.ui.state.UIState
/**
* UI state for [com.mobiledevpro.peoplelist.view.PeopleListScreen]
*
* Created on Feb 04, 2023.
*
*/
sealed interface PeopleProfileUIState : UIState {
object Empty : PeopleProfileUIState
object Loading : PeopleProfileUIState
class Success(val profileList : List<PeopleProfile>) : PeopleProfileUIState
class Fail(val throwable: Throwable) : PeopleProfileUIState
} | EUFriendsChat/feature/people_list/src/main/kotlin/com/mobiledevpro/peoplelist/view/PeopleProfileUIState.kt | 403334336 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.peoplelist.domain.usecase
import com.mobiledevpro.coroutines.BaseCoroutinesFLowUseCase
import com.mobiledevpro.coroutines.None
import com.mobiledevpro.domain.model.PeopleProfile
import com.mobiledevpro.domain.model.fakePeopleProfileList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
class GetPeopleListUseCase(
) : BaseCoroutinesFLowUseCase<List<PeopleProfile>, None>(Dispatchers.IO) {
override fun buildUseCaseFlow(params: None?): Flow<List<PeopleProfile>> =
flowOf(fakePeopleProfileList)
} | EUFriendsChat/feature/people_list/src/main/kotlin/com/mobiledevpro/peoplelist/domain/usecase/GetPeopleListUseCase.kt | 2525807101 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.people.view
import android.util.Log
import androidx.compose.runtime.Composable
/**
* Host for People list and People profile
*
* Created on Feb 04, 2023.
*
*/
@Composable
fun PeopleScreen(
nestedNavGraph: @Composable () -> Unit
) {
Log.d("navigation", "PeopleScreen: ")
nestedNavGraph.invoke()
} | EUFriendsChat/feature/people/src/main/kotlin/com/mobiledevpro/people/view/PeopleScreen.kt | 534733385 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.onboarding.view
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
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.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mobiledevpro.ui.theme.AppTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OnBoardingFirstScreen() {
Box(
modifier = Modifier
.fillMaxSize()
.background(color = Color(0x80FFCC99))
) {
Text(
text = "1st OnBoarding",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(16.dp)
.align(Alignment.Center)
.fillMaxWidth(),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Preview
@Composable
fun OnBoardingFirstPreview() {
AppTheme {
OnBoardingFirstScreen()
}
} | EUFriendsChat/feature/onboarding/src/main/kotlin/com/mobiledevpro/onboarding/view/OnBoardingFirstScreen.kt | 3189920732 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.onboarding.view
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
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.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mobiledevpro.ui.theme.AppTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OnBoardingSecondScreen() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.background(color = Color(0x80FFFF99))
) {
Text(
text = "2nd OnBoarding",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(16.dp)
.align(Alignment.Center)
.fillMaxWidth(),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Preview
@Composable
fun OnBoardingSecondPreview() {
AppTheme {
OnBoardingSecondScreen()
}
} | EUFriendsChat/feature/onboarding/src/main/kotlin/com/mobiledevpro/onboarding/view/OnBoardingSecondScreen.kt | 226490309 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.onboarding.view
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
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.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mobiledevpro.ui.theme.AppTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OnBoardingThirdScreen() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.background(color = Color(0x80FF9999))
) {
Text(
text = "3rd OnBoarding",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(16.dp)
.align(Alignment.Center)
.fillMaxWidth(),
style = MaterialTheme.typography.bodyLarge
)
}
}
@Preview
@Composable
fun OnBoardingThirdPreview() {
AppTheme {
OnBoardingThirdScreen()
}
} | EUFriendsChat/feature/onboarding/src/main/kotlin/com/mobiledevpro/onboarding/view/OnBoardingThirdScreen.kt | 1221242416 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.onboarding.view
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
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.unit.dp
import com.mobiledevpro.ui.component.ScreenBackground
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OnBoardingScreen(
nestedNavGraph: @Composable () -> Unit,
onNext: () -> Unit
) {
Scaffold { paddingValues ->
ScreenBackground(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
nestedNavGraph.invoke()
Button(
onClick = onNext,
modifier = Modifier
.align(Alignment.BottomCenter)
.defaultMinSize(minWidth = 144.dp, minHeight = 48.dp)
) {
Text(text = "Next")
}
}
}
}
} | EUFriendsChat/feature/onboarding/src/main/kotlin/com/mobiledevpro/onboarding/view/OnBoardingScreen.kt | 3400282917 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.people.profile.view
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableIntStateOf
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.layout.boundsInParent
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.mobiledevpro.domain.model.PeopleProfile
import com.mobiledevpro.domain.model.fakePeopleProfileList
import com.mobiledevpro.people.profile.R
import com.mobiledevpro.ui.component.ProfileContent
import com.mobiledevpro.ui.component.ProfilePicture
import com.mobiledevpro.ui.component.ProfilePictureSize
import com.mobiledevpro.ui.component.ScreenBackground
import com.mobiledevpro.ui.theme.AppTheme
import com.mobiledevpro.ui.R as RApp
/**
* Profile screen for selected person from People list
*
* Created on Feb 03, 2023.
*
*/
@Composable
fun PeopleProfileScreen(
profile: PeopleProfile,
onBackPressed: () -> Unit,
onOpenChatWith: (profile: PeopleProfile) -> Unit
) {
val backgroundBoxTopOffset = remember { mutableIntStateOf(0) }
ScreenBackground(
modifier = Modifier
.fillMaxSize()
.statusBarsPadding()
) {
//Background with rounded top-corners
Box(
modifier = Modifier
.offset { IntOffset(0, backgroundBoxTopOffset.value) }
.clip(RoundedCornerShape(topStart = 48.dp, topEnd = 48.dp))
.background(color = MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp))
)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Top
) {
IconButton(
onClick = { onBackPressed() },
modifier = Modifier.padding(16.dp)
) {
Icon(
painter = painterResource(id = RApp.drawable.ic_arrow_back_white_24dp),
contentDescription = ""
)
}
ProfilePicture(
photoUri = profile.photo ?: Uri.EMPTY,
onlineStatus = profile.status,
size = ProfilePictureSize.LARGE,
modifier = Modifier
.padding(paddingValues = PaddingValues(16.dp, 16.dp, 16.dp, 16.dp))
.align(Alignment.CenterHorizontally)
.onGloballyPositioned {
val rect = it.boundsInParent()
backgroundBoxTopOffset.value =
rect.topCenter.y.toInt() + (rect.bottomCenter.y - rect.topCenter.y).toInt() / 2
}
)
ProfileContent(
userName = profile.name,
isOnline = profile.status,
alignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(8.dp)
.align(Alignment.CenterHorizontally)
)
ProfileSocialIcons(modifier = Modifier.align(Alignment.CenterHorizontally))
Row(
modifier = Modifier
.fillMaxHeight()
.align(Alignment.CenterHorizontally),
verticalAlignment = Alignment.Bottom
) {
Button(
onClick = {
profile.also(onOpenChatWith)
},
modifier = Modifier
.padding(bottom = 48.dp, top = 16.dp, start = 16.dp, end = 16.dp)
.defaultMinSize(minHeight = 48.dp, minWidth = 144.dp),
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.tertiary),
) {
Text(text = "Say Hi \uD83D\uDC4B")
}
}
}
}
}
@Composable
fun ProfileSocialIcons(modifier: Modifier) {
Row(
modifier = modifier
) {
IconButton(
onClick = {
}
) {
Icon(
painter = painterResource(id = R.drawable.ic_instagram_white_48dp),
contentDescription = "",
modifier = Modifier.padding(4.dp),
)
}
IconButton(
onClick = {
}
) {
Icon(
painter = painterResource(id = R.drawable.ic_linkedin_white_48dp),
contentDescription = "",
modifier = Modifier.padding(4.dp)
)
}
IconButton(
onClick = {
}
) {
Icon(
painter = painterResource(id = R.drawable.ic_youtube_white_48dp),
contentDescription = "",
modifier = Modifier.padding(4.dp)
)
}
IconButton(
onClick = {
}
) {
Icon(
painter = painterResource(id = R.drawable.ic_twitter_white_48dp),
contentDescription = "",
modifier = Modifier.padding(4.dp)
)
}
}
}
@Preview
@Composable
fun PeopleProfilePreview() {
AppTheme(darkTheme = true) {
fakePeopleProfileList.find { it.id == 2 }?.let {
PeopleProfileScreen(
it,
onBackPressed = {},
onOpenChatWith = {}
)
}
}
} | EUFriendsChat/feature/people_profile/src/main/kotlin/com/mobiledevpro/people/profile/view/PeopleProfileScreen.kt | 2803522911 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.people.profile.view
import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.mobiledevpro.domain.model.PeopleProfile
import com.mobiledevpro.domain.model.fakePeopleProfileList
import com.mobiledevpro.people.profile.view.args.PeopleProfileArgs
/**
* Profile screen for selected person from People list
*
* Created on Feb 04, 2023.
*
*/
class PeopleProfileViewModel(
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val profileId : Int = PeopleProfileArgs(savedStateHandle).peopleProfileId
init {
Log.d("navigation", "PeopleProfileViewModel: args = $profileId")
}
fun getProfile() : PeopleProfile? = fakePeopleProfileList.find { it.id == profileId }
} | EUFriendsChat/feature/people_profile/src/main/kotlin/com/mobiledevpro/people/profile/view/PeopleProfileViewModel.kt | 2376490263 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.people.profile.view.args
import androidx.lifecycle.SavedStateHandle
/**
*
* Created on Feb 04, 2023.
*
*/
class PeopleProfileArgs(val peopleProfileId: Int) {
constructor(savedStateHandle: SavedStateHandle) :
this(checkNotNull(savedStateHandle[PEOPLE_PROFILE_ID_ARG]) as Int)
companion object {
const val PEOPLE_PROFILE_ID_ARG = "peopleProfileId"
}
} | EUFriendsChat/feature/people_profile/src/main/kotlin/com/mobiledevpro/people/profile/view/args/PeopleProfileArgs.kt | 797035271 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.user.profile.di
import com.mobiledevpro.user.profile.domain.usecase.GetUserProfileUseCase
import com.mobiledevpro.user.profile.view.vm.ProfileViewModel
import org.koin.androidx.viewmodel.dsl.viewModelOf
import org.koin.core.module.dsl.scopedOf
import org.koin.dsl.module
/**
* User Profile screen module
*
* Created on Jul 22, 2023.
*
*/
val featureUserProfileModule = module {
scope<ProfileViewModel> {
viewModelOf(::ProfileViewModel)
scopedOf(::GetUserProfileUseCase)
}
} | EUFriendsChat/feature/user_profile/src/main/kotlin/com/mobiledevpro/user/profile/di/Module.kt | 4012706576 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.user.profile.view.state
import com.mobiledevpro.domain.model.UserProfile
import com.mobiledevpro.ui.state.UIState
/**
* UI state for [com.mobiledevpro.user.profile.view.ProfileScreen]
*
* Created on May 09, 2023.
*
*/
sealed interface UserProfileUIState : UIState {
object Empty : UserProfileUIState
class Success(val userProfile: UserProfile) : UserProfileUIState
class Fail(val throwable: Throwable) : UserProfileUIState
} | EUFriendsChat/feature/user_profile/src/main/kotlin/com/mobiledevpro/user/profile/view/state/UserProfileUIState.kt | 3389684614 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.user.profile.view.vm
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.mobiledevpro.ui.vm.BaseViewModel
import com.mobiledevpro.user.profile.domain.usecase.GetUserProfileUseCase
import com.mobiledevpro.user.profile.view.state.UserProfileUIState
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class ProfileViewModel(
private val getUserProfileUseCase: GetUserProfileUseCase
) : BaseViewModel<UserProfileUIState>() {
override fun initUIState(): UserProfileUIState = UserProfileUIState.Empty
init {
Log.d("UI", "ProfileViewModel init")
observeUserProfile()
}
private fun observeUserProfile() {
getUserProfileUseCase.execute()
.onEach { result ->
result.onSuccess { profile ->
UserProfileUIState.Success(profile)
.also { _uiState.value = it }
}.onFailure {
//TODO: show the error
}
}.launchIn(viewModelScope)
}
} | EUFriendsChat/feature/user_profile/src/main/kotlin/com/mobiledevpro/user/profile/view/vm/ProfileViewModel.kt | 1872994490 |
/*
* Copyright 2022 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.user.profile.view
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ExitToApp
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.layout.boundsInParent
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.rememberLottieComposition
import com.mobiledevpro.domain.model.UserProfile
import com.mobiledevpro.domain.model.fakeUser
import com.mobiledevpro.ui.component.LabeledDarkModeSwitch
import com.mobiledevpro.ui.component.ProfileContent
import com.mobiledevpro.ui.component.ProfilePicture
import com.mobiledevpro.ui.component.ProfilePictureSize
import com.mobiledevpro.ui.component.ScreenBackground
import com.mobiledevpro.ui.component.SettingsButton
import com.mobiledevpro.ui.theme.AppTheme
import com.mobiledevpro.ui.theme._darkModeState
import com.mobiledevpro.ui.theme.darkModeState
import com.mobiledevpro.user.profile.view.state.UserProfileUIState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import com.mobiledevpro.ui.R as RUi
@Composable
fun ProfileScreen(
state: StateFlow<UserProfileUIState>,
onNavigateToSubscription: () -> Unit
) {
Log.d("navigation", "ProfileScreen:")
val uiState by state.collectAsStateWithLifecycle()
val context = LocalContext.current
val backgroundBoxTopOffset = remember { mutableStateOf(0) }
val darkModeOn = remember { mutableStateOf(darkModeState.value) }
val user : UserProfile = when(uiState) {
is UserProfileUIState.Success -> (uiState as UserProfileUIState.Success).userProfile
is UserProfileUIState.Fail -> {
LaunchedEffect(Unit) {
Toast.makeText(
context,
(uiState as UserProfileUIState.Fail).throwable.localizedMessage,
Toast.LENGTH_LONG
).show()
}
UserProfile("", "", false, Uri.EMPTY)
}
else -> UserProfile("", "", false, Uri.EMPTY)
}
ScreenBackground(
modifier = Modifier
.fillMaxSize()
.statusBarsPadding()
) {
//Background with rounded top-corners
Box(
modifier = Modifier
.offset { IntOffset(0, backgroundBoxTopOffset.value) }
.clip(RoundedCornerShape(topStart = 48.dp, topEnd = 48.dp))
.background(color = MaterialTheme.colorScheme.surfaceColorAtElevation(4.dp))
)
Box(modifier = Modifier.fillMaxSize()) {
BeLikeAProButton(modifier = Modifier
.align(Alignment.TopEnd)
.padding(8.dp)
.size(56.dp)
.clickable { onNavigateToSubscription() })
Column(
modifier = Modifier
.fillMaxSize()
.padding(start = 16.dp, end = 16.dp, bottom = 32.dp),
verticalArrangement = Arrangement.Top
) {
ProfilePicture(
photoUri = user.photo,
onlineStatus = true,
size = ProfilePictureSize.LARGE,
modifier = Modifier
.padding(paddingValues = PaddingValues(16.dp, 16.dp, 16.dp, 16.dp))
.align(Alignment.CenterHorizontally)
.onGloballyPositioned {
val rect = it.boundsInParent()
backgroundBoxTopOffset.value =
rect.topCenter.y.toInt() + (rect.bottomCenter.y - rect.topCenter.y).toInt() / 2
}
)
ProfileContent(
userName = user.name,
subName = user.nickname,
isOnline = user.status,
alignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(8.dp)
.align(Alignment.CenterHorizontally)
)
Column(
modifier = Modifier
.fillMaxHeight()
.align(Alignment.CenterHorizontally),
verticalArrangement = Arrangement.Bottom
) {
LabeledDarkModeSwitch(
label = "Dark mode",
checked = darkModeOn.value,
onCheckedChanged = { isDark ->
Log.d("main", "ProfileScreen: dark $isDark")
darkModeOn.value = isDark
_darkModeState.update {
isDark
}
})
Divider()
SettingsButton(
label = "Log Out",
icon = Icons.Rounded.ExitToApp,
onClick = {
}
)
}
}
}
}
}
@Composable
fun BeLikeAProButton(modifier: Modifier) {
//Here is how to use Lottie animation with Compose https://github.com/airbnb/lottie/blob/master/android-compose.md
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(RUi.raw.ic_crowd))
LottieAnimation(composition = composition, modifier = modifier)
}
@Preview
@Composable
fun ProfileScreenPreview() {
AppTheme(darkTheme = true) {
ProfileScreen(
state = MutableStateFlow(UserProfileUIState.Success(fakeUser)),
onNavigateToSubscription = {}
)
}
} | EUFriendsChat/feature/user_profile/src/main/kotlin/com/mobiledevpro/user/profile/view/ProfileScreen.kt | 2078068005 |
/*
* Copyright 2023 | Dmitri Chernysh | https://mobile-dev.pro
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mobiledevpro.user.profile.domain.usecase
import com.mobiledevpro.coroutines.BaseCoroutinesFLowUseCase
import com.mobiledevpro.coroutines.None
import com.mobiledevpro.domain.model.UserProfile
import com.mobiledevpro.domain.model.fakeUser
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
class GetUserProfileUseCase(
) : BaseCoroutinesFLowUseCase<UserProfile, None>(Dispatchers.IO) {
override fun buildUseCaseFlow(params: None?): Flow<UserProfile> =
flowOf(fakeUser)
} | EUFriendsChat/feature/user_profile/src/main/kotlin/com/mobiledevpro/user/profile/domain/usecase/GetUserProfileUseCase.kt | 2299684318 |
package com.quick691.testthumbnail
import android.os.Build
import android.os.Bundle
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
import expo.modules.ReactActivityDelegateWrapper
class MainActivity : ReactActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// Set the theme to AppTheme BEFORE onCreate to support
// coloring the background, status bar, and navigation bar.
// This is required for expo-splash-screen.
setTheme(R.style.AppTheme);
super.onCreate(null)
}
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "main"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate {
return ReactActivityDelegateWrapper(
this,
BuildConfig.IS_NEW_ARCHITECTURE_ENABLED,
object : DefaultReactActivityDelegate(
this,
mainComponentName,
fabricEnabled
){})
}
/**
* Align the back button behavior with Android S
* where moving root activities to background instead of finishing activities.
* @see <a href="https://developer.android.com/reference/android/app/Activity#onBackPressed()">onBackPressed</a>
*/
override fun invokeDefaultOnBackPressed() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
if (!moveTaskToBack(false)) {
// For non-root activities, use the default implementation to finish them.
super.invokeDefaultOnBackPressed()
}
return
}
// Use the default back button implementation on Android S
// because it's doing more than [Activity.moveTaskToBack] in fact.
super.invokeDefaultOnBackPressed()
}
}
| test-expo-thumbnail/android/app/src/main/java/com/quick691/testthumbnail/MainActivity.kt | 1133151431 |
package com.quick691.testthumbnail
import android.app.Application
import android.content.res.Configuration
import androidx.annotation.NonNull
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.ReactHost
import com.facebook.react.config.ReactFeatureFlags
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
import expo.modules.ApplicationLifecycleDispatcher
import expo.modules.ReactNativeHostWrapper
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper(
this,
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> {
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return PackageList(this).packages
}
override fun getJSMainModuleName(): String = ".expo/.virtual-metro-entry"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
)
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (!BuildConfig.REACT_NATIVE_UNSTABLE_USE_RUNTIME_SCHEDULER_ALWAYS) {
ReactFeatureFlags.unstable_useRuntimeSchedulerAlways = false
}
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
if (BuildConfig.DEBUG) {
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
ApplicationLifecycleDispatcher.onApplicationCreate(this)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig)
}
}
| test-expo-thumbnail/android/app/src/main/java/com/quick691/testthumbnail/MainApplication.kt | 3412581260 |
package com.example.littlelemon
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.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
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.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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.littlelemon.data.MenuItem
import com.example.littlelemon.ui.theme.LittleLemonColor
@Composable
fun HeroSection(dishes: List<MenuItem> = listOf()) {
var filter by remember { mutableStateOf("") };
var dishesFiltered = dishes;
var categories = dishes.groupBy { it.category };
var categoryFilter by remember { mutableStateOf("") }
Column {
Column(modifier = Modifier
.background(LittleLemonColor.green)
.padding(start = 12.dp, end = 12.dp, top = 16.dp, bottom = 16.dp)) {
Text(
text = "Little Lemon",
fontSize = 40.sp,
fontWeight = FontWeight.Bold,
color = LittleLemonColor.yellow
)
Row(
modifier = Modifier
.padding(top = 20.dp)
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Chicago",
fontSize = 24.sp,
color = LittleLemonColor.cloud
)
Text(
text = "We are a family-owned Mediterranean restaurant, focused on traditional recipes served with a modern twist",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.padding(end = 20.dp), color = LittleLemonColor.cloud
)
}
Column(modifier = Modifier.weight(1f)){
Image(
painter = painterResource(id = R.drawable.hero_image),
contentDescription = "Upper Panel Image",
modifier = Modifier.clip(RoundedCornerShape(10.dp)).fillMaxWidth().size(200.dp),
contentScale = ContentScale.FillWidth
)
}
}
TextField(value = filter,
onValueChange = { filter = it },
placeholder = { Text("Enter search phrase") },
leadingIcon = { Icon(imageVector = Icons.Default.Search, contentDescription = "") },
modifier = Modifier
.fillMaxWidth()
.clip(shape = RoundedCornerShape(4.dp))
.padding(10.dp))
}
Column(Modifier.padding(horizontal = 10.dp, vertical = 16.dp)) {
Text(text = "ORDER FOR DELIVERY", fontWeight = FontWeight.Bold)
Row {
LazyRow {
itemsIndexed(categories.keys.toList()) { _,
category ->
Button(onClick = { categoryFilter = category;
filter = ""},
modifier = Modifier.padding(horizontal = 10.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color.LightGray,
contentColor = LittleLemonColor.charcoal)) {
Text(category)
}
}
}
}
}
if (!filter.isNullOrEmpty()) {
dishesFiltered = dishes.filter { it.description.contains(filter, true) || it.title.contains(filter,true)}
categoryFilter = "";
}
if (!categoryFilter.isNullOrEmpty()) {
dishesFiltered = dishes.filter { it.category.contentEquals(categoryFilter) }
filter = "";
}
if(categoryFilter.isNullOrEmpty() && filter.isNullOrEmpty())
dishesFiltered = dishes;
MenuItemsComposable(dishesFiltered)
}
}
@Preview(showBackground = true)
@Composable
fun HeroSectionPreview() {
HeroSection()
}
| Littlelemon-Android-Capstone-/HeroSection.kt | 934351690 |
package com.example.littlelemon.data
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [MenuItem::class], version = 1)
abstract class MenuDatabase : RoomDatabase() {
abstract fun menuDao(): MenuDao
} | Littlelemon-Android-Capstone-/MenuDatabase.kt | 904669356 |
package com.example.littlelemon.network
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName(value = "Menu")
class MenuNetworkdata(
val menu: List<MenuItemNetwork>
)
@Serializable
class MenuItemNetwork (
val id: Int,
val title: String,
val description : String,
val price: Double,
val image: String,
val category: String
) | Littlelemon-Android-Capstone-/Network.kt | 1244498263 |
package com.example.littlelemon
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.lifecycleScope
import androidx.navigation.compose.rememberNavController
import androidx.room.Room
import com.example.littlelemon.data.MenuDatabase
import com.example.littlelemon.data.MenuItem
import com.example.littlelemon.network.MenuItemNetwork
import com.example.littlelemon.network.MenuNetworkdata
import com.example.littlelemon.ui.theme.LittleLemonTheme
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.android.Android
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivity : ComponentActivity() {
private val database by lazy {
Room.databaseBuilder(
applicationContext,
MenuDatabase::class.java,
"menu.db"
).build()
}
private val sharedPreferences by lazy {
getSharedPreferences("LittleLemon", MODE_PRIVATE)
}
private val client = HttpClient(Android) {
install(ContentNegotiation) {
json(contentType = ContentType("text", "plain"))
}
}
private suspend fun getMenu(): List<MenuItemNetwork> {
val response: MenuNetworkdata =
client.get("https://raw.githubusercontent.com/Meta-Mobile-Developer-PC/Working-With-Data-API/main/menu.json")
.body()
return response?.menu?: listOf();
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
val menuItems = getMenu()
withContext(Dispatchers.IO) {
for (menuItem in menuItems){
val menuItemDb = MenuItem(menuItem.id,
menuItem.title,
menuItem.description,
menuItem.price,
menuItem.image,
menuItem.category)
database.menuDao().saveMenuItem(menuItemDb)
}
}
}
setContent {
val navController = rememberNavController()
LittleLemonTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
NavigationComposable(navController = navController,
sharedPreferences,
database)
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
LittleLemonTheme {
Greeting("Android")
}
} | Littlelemon-Android-Capstone-/MainActivity.kt | 45288679 |
package com.example.littlelemon
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.littlelemon", appContext.packageName)
}
} | Littlelemon-Android-Capstone-/ExampleInstrumentedTest.kt | 669504326 |
package com.example.littlelemon
import android.content.SharedPreferences
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.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
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.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.edit
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.example.littlelemon.ui.theme.LittleLemonColor
import com.example.littlelemon.ui.theme.LittleLemonTheme
@Composable
fun OnboardingComposable(navController: NavHostController,
sharedPreferences: SharedPreferences?) {
var firstName by remember { mutableStateOf("") }
var lastName by remember { mutableStateOf("") }
var email by remember { mutableStateOf("") }
LittleLemonTheme{
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.logo),
contentDescription = "Little Lemon Logo",
modifier = Modifier
.fillMaxWidth()
.padding(top = 20.dp, bottom = 20.dp)
)
Row (modifier = Modifier
.background(LittleLemonColor.green)
.fillMaxWidth()
.align(Alignment.CenterHorizontally)
.padding(top = 20.dp, bottom = 20.dp),
horizontalArrangement = Arrangement.Center
){
Text(text = "Let's get to know you",
fontSize = 24.sp,
color = Color.White)
}
Column (modifier = Modifier
.padding(start = 10.dp, end = 10.dp, top = 16.dp, bottom = 16.dp)
.fillMaxSize()
, verticalArrangement = Arrangement.SpaceBetween
){
Row (){
Column() {
Text(text = "Personal information",
modifier = Modifier.padding(top = 16.dp, bottom = 16.dp))
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = firstName,
onValueChange = {firstName = it },
label = { Text("First name")}
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 10.dp),
value = lastName,
onValueChange = {lastName = it },
label = { Text("Last name") }
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = email,
onValueChange = {email = it },
label = { Text("Email address") }
)
}
}
Button(
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(containerColor = LittleLemonColor.yellow,
contentColor = Color.Black),
onClick = {
if(!email.isBlank()
&& !firstName.isBlank()
&& !lastName.isBlank()){
sharedPreferences?.edit(commit = true) {
putString("email", email);
putString("firstName", firstName);
putString("lastName", lastName);
}
navController?.navigate(Home.route);
}
}
) {
Text("Register")
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun OnboardingPreview() {
OnboardingComposable(navController = rememberNavController(), null)
} | Littlelemon-Android-Capstone-/OnboardingComposable.kt | 3429783448 |
package com.example.littlelemon.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class MenuItem(
@PrimaryKey val id: Int,
val title: String,
val description : String,
val price: Double,
val image: String,
val category: String
) | Littlelemon-Android-Capstone-/MenuItem.kt | 1462958326 |
package com.example.littlelemon
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)
}
} | Littlelemon-Android-Capstone-/ExampleUnitTest.kt | 2190062257 |
package com.example.littlelemon.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)
object LittleLemonColor {
val green = Color(0xFF495E57)
val yellow = Color(0xFFF4CE14)
val pink = Color(0xFFFBDABB)
val cloud = Color(0xFFEDEFEE)
val charcoal = Color(0xFF333333)
}
| Littlelemon-Android-Capstone-/Color.kt | 584383795 |
package com.example.littlelemon.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 LittleLemonTheme(
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
)
} | Littlelemon-Android-Capstone-/Theme.kt | 641642330 |
package com.example.littlelemon
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
@Composable
fun TopAppBarComposable(navController: NavHostController, showProfileIcon: Boolean) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center) {
Image(
painter = painterResource(id = R.drawable.logo),
contentDescription = "Little Lemon Logo"
)
if(showProfileIcon){
IconButton(onClick = { navController.navigate(Profile.route) }) {
Image(
painter = painterResource(id = R.drawable.profile),
contentDescription = "Profile",
modifier = Modifier.size(24.dp)
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun TopAppBarPreview() {
TopAppBarComposable(navController = rememberNavController(), true)
}
| Littlelemon-Android-Capstone-/TopAppBarComposable.kt | 477220788 |
package com.example.littlelemon
interface Destinations {
val route : String
}
object Home : Destinations {
override val route = "Home"
}
object Onboarding : Destinations {
override val route = "Onboarding"
}
object Profile : Destinations {
override val route = "Profile"
}
| Littlelemon-Android-Capstone-/Destinations.kt | 452043073 |
package com.example.littlelemon
import android.content.SharedPreferences
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.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.OutlinedTextField
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.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.edit
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.example.littlelemon.ui.theme.LittleLemonColor
import com.example.littlelemon.ui.theme.LittleLemonTheme
@Composable
fun ProfileComposable (navController: NavHostController,
sharedPreferences: SharedPreferences?){
LittleLemonTheme{
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.logo),
contentDescription = "Little Lemon Logo",
modifier = Modifier
.fillMaxWidth()
.padding(top = 20.dp, bottom = 20.dp)
)
Column (modifier = Modifier
.padding(start = 10.dp, end = 10.dp, top = 16.dp, bottom = 16.dp)
.fillMaxSize()
, verticalArrangement = Arrangement.SpaceBetween
){
Row (){
Column() {
Text(text = "Personal information",
modifier = Modifier.padding(top = 16.dp, bottom = 16.dp))
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = sharedPreferences?.getString("firstName","").toString(),
onValueChange = {},
readOnly = true,
label = { Text("First name")}
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 10.dp),
value = sharedPreferences?.getString("lastName","").toString(),
onValueChange = {},
readOnly = true,
label = { Text("Last name") }
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = sharedPreferences?.getString("email","").toString(),
onValueChange = {},
readOnly = true,
label = { Text("Email address") }
)
}
}
Button(
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(containerColor = LittleLemonColor.yellow,
contentColor = Color.Black),
onClick = {
sharedPreferences?.edit(commit = true) {
putString("email", "");
putString("firstName", "");
putString("lastName", "");
}
navController?.navigate(Onboarding.route);
}
) {
Text("Log out")
}
}
}
}
}
@Composable
@Preview
fun ProfileScreenPreview(){
ProfileComposable(navController = rememberNavController(), null);
} | Littlelemon-Android-Capstone-/ProfileComposable.kt | 2241881764 |
package com.example.littlelemon
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardColors
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import com.example.littlelemon.data.MenuItem
import com.example.littlelemon.ui.theme.LittleLemonColor
@OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)
@Composable
fun MenuItemComposable(dish: MenuItem) {
Card(onClick = {}, colors = CardDefaults.cardColors(
containerColor = Color.White)
) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(10.dp)){
Column(modifier = Modifier.fillMaxWidth(0.8f)) {
Text(
text = dish.title,
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier
.padding(top = 5.dp, bottom = 5.dp),
color = Color.Black
)
Text(
text = dish.description,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier
.padding(top = 5.dp, bottom = 5.dp)
.fillMaxWidth(0.75f)
)
Text(
text = "$${dish.price}",
style = MaterialTheme.typography.bodySmall,
fontWeight = FontWeight.Bold
)
}
GlideImage(
model = dish.image,
contentDescription = "Dish image",
modifier = Modifier.clip(RoundedCornerShape(10.dp)).fillMaxWidth(),
contentScale = ContentScale.FillWidth
)
}
}
Divider(
modifier = Modifier.padding(start = 8.dp, end = 8.dp),
thickness = 1.dp,
color = Color.LightGray
)
} | Littlelemon-Android-Capstone-/MenuItemComposable.kt | 3882107987 |
package com.example.littlelemon
import android.content.SharedPreferences
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.littlelemon.data.MenuDatabase
@Composable
fun NavigationComposable(navController: NavHostController,
sharedPreferences: SharedPreferences,
database: MenuDatabase
) {
NavHost(navController = navController,
startDestination = if (sharedPreferences.getString("email","").isNullOrEmpty())
Onboarding.route
else
Home.route)
{
composable(Home.route) {
HomeComposable(navController, database)
}
composable(Onboarding.route)
{
OnboardingComposable(navController, sharedPreferences)
}
composable(Profile.route)
{
ProfileComposable(navController, sharedPreferences)
}
}
} | Littlelemon-Android-Capstone-/NavigationComposable.kt | 3206819419 |
package com.example.littlelemon
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
import com.example.littlelemon.data.MenuItem
@Composable
fun MenuItemsComposable(dishes: List<MenuItem> = listOf()) {
Column {
LazyColumn{
itemsIndexed(dishes){ _,
dish -> MenuItemComposable(dish)
}
}
}
} | Littlelemon-Android-Capstone-/MenuItemsComposable.kt | 2592241294 |
package com.example.littlelemon.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
)
*/
) | Littlelemon-Android-Capstone-/Type.kt | 1944173237 |
package com.example.littlelemon.data
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface MenuDao {
@Query("SELECT * FROM MenuItem")
fun getAllMenuItems(): LiveData<List<MenuItem>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveMenuItem(menuItem: MenuItem)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveMenuItems(menuItems: List<MenuItem>)
@Delete
fun deleteMenuItem(menuItem: MenuItem)
}
| Littlelemon-Android-Capstone-/MenuDao.kt | 2064257944 |
package com.example.littlelemon;
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable;
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.tooling.preview.Preview;
import androidx.navigation.NavHostController
import com.example.littlelemon.data.MenuDatabase
@Composable
fun HomeComposable (navController: NavHostController, database: MenuDatabase){
val menuItems by database.menuDao().getAllMenuItems().observeAsState(emptyList())
Column {
TopAppBarComposable(navController = navController,true)
HeroSection(menuItems)
}
}
@Composable
@Preview
fun HomeScreenPreview(){
//Home(navController = rememberNavController(), database = MenuDatabase());
} | Littlelemon-Android-Capstone-/HomeComposable.kt | 1043808514 |
package com.example.pract2
import android.support.test.InstrumentationRegistry
import android.support.test.runner.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.pract2", appContext.packageName)
}
} | pract2/app/src/androidTest/java/com/example/pract2/ExampleInstrumentedTest.kt | 2202394092 |
package com.example.pract2
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)
}
} | pract2/app/src/test/java/com/example/pract2/ExampleUnitTest.kt | 2978412176 |
package com.example.pract2
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Patterns
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
lateinit var button: Button
lateinit var EditLogin : EditText
lateinit var EditEmail : EditText
lateinit var EditPassword : EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button=findViewById(R.id.Button)
textView=findViewById(R.id.text)
EditLogin=findViewById(R.id.Login)
EditEmail=findViewById(R.id.Email)
EditPassword=findViewById(R.id.Password)
button.setOnClickListener {
if(EditLogin.text.toString() !=""&& EditEmail.text.toString()!=""&& EditPassword.text.toString()!=""){
if (!ProfEmail(EditEmail.text))
{
Toast.makeText(this, "Был найден некорректный ввод эл. почты! Повторите попытку", Toast.LENGTH_SHORT).show()
}
else
{
Toast.makeText(this, "Пользователь был добавлен!", Toast.LENGTH_SHORT).show()
val user = User(1,EditLogin.text.toString(), EditEmail.text.toString(), EditPassword.text.toString())
val p0 = Data(this,null)
p0.addUser(user)
}
}
else{
Toast.makeText(this,"Пустые поля",Toast.LENGTH_LONG).show()
}
}
}
private fun ProfEmail(email: CharSequence): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
} | pract2/app/src/main/java/com/example/pract2/MainActivity.kt | 706920372 |
package com.example.pract2
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CursorFactory
import android.database.sqlite.SQLiteOpenHelper
class Data(context: Context, cursorFactory: CursorFactory?):
SQLiteOpenHelper(context, "ListUsersData", cursorFactory, 1)
{
override fun onCreate(p0: SQLiteDatabase) {
val query = "CREATE TABLE users (id INT PRIMARY KEY, login TEXT, email TEXT, pass TEXT)"
p0!!.execSQL(query)
}
override fun onUpgrade(p0: SQLiteDatabase, p1: Int, p2: Int) {
p0.execSQL("DROP TABLE IF EXISTS users")
onCreate(p0)
}
fun addUser(user: User) {
val contentValues = ContentValues()
contentValues.put("id", user.Id)
contentValues.put("login", user.login)
contentValues.put("email", user.email)
contentValues.put("pass", user.password)
val p0 = writableDatabase
p0.insert("users", null, contentValues)
p0.close()
}
} | pract2/app/src/main/java/com/example/pract2/Data.kt | 4159270283 |
package com.example.pract2
class User(val Id: Int,val login:String,val email:String,val password:String){
} | pract2/app/src/main/java/com/example/pract2/User.kt | 814229832 |
import androidx.compose.ui.window.ComposeUIViewController
fun MainViewController() = ComposeUIViewController { App() }
| ComposeMultiplatformExample/composeApp/src/iosMain/kotlin/MainViewController.kt | 3500059733 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.