path
stringlengths
4
242
contentHash
stringlengths
1
10
content
stringlengths
0
3.9M
SpringInAction5/reactor/src/test/kotlin/FluxTransformingTest.kt
3053128290
import org.junit.jupiter.api.Test import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.core.scheduler.Schedulers import reactor.test.StepVerifier import java.time.Duration import java.util.* class FluxTransformingTest { @Test fun skipAFew() { val skipFlux = Flux.just("one", "two", "skip a few", "ninety nine", "one hundred") .skip(3) StepVerifier.create(skipFlux) .expectNext("ninety nine", "one hundred") .verifyComplete() } @Test fun skipAFewSeconds() { val skipFlux = Flux.just("one", "two", "skip a few", "ninety nine", "one hundred") .delayElements(Duration.ofSeconds(1)) .skip(Duration.ofSeconds(4)) StepVerifier.create(skipFlux) .expectNext("ninety nine", "one hundred") .verifyComplete() } @Test fun take() { val nationalParkFlux = Flux.just("Yellowstone", "Yosemite", "Grand Canyon", "Zion", "grand Teton") .take(3) StepVerifier.create(nationalParkFlux) .expectNext("Yellowstone", "Yosemite", "Grand Canyon") .verifyComplete() } @Test fun takeAFewSeconds() { val nationalParkFlux = Flux.just("Yellowstone", "Yosemite", "Grand Canyon", "Zion", "grand Teton") .delayElements(Duration.ofSeconds(1)) .take(Duration.ofMillis(3500)) StepVerifier.create(nationalParkFlux) .expectNext("Yellowstone", "Yosemite", "Grand Canyon") .verifyComplete() } @Test fun filter() { val nationalParkFlux = Flux.just("Yellowstone", "Yosemite", "Grand Canyon", "Zion", "grand Teton") .filter {np -> !np.contains(" ")} StepVerifier.create(nationalParkFlux) .expectNext("Yellowstone", "Yosemite", "Zion") .verifyComplete() } @Test fun distinct() { val animalFlux = Flux.just("dog", "cat", "bird", "dog", "bird", "anteater") .distinct() StepVerifier.create(animalFlux) .expectNext("dog", "cat", "bird", "anteater") .verifyComplete() } companion object { data class Player(val firstName: String, val secondName: String) } @Test fun map() { val playerFlux: Flux<Player> = Flux.just("Michael Jordan", "Scottie Pippen", "Steve Kerr") .map { s -> val split = s.split("\\s".toRegex()) Player(split[0], split[1]) } StepVerifier.create(playerFlux) .expectNext(Player("Michael", "Jordan")) .expectNext(Player("Scottie", "Pippen")) .expectNext(Player("Steve", "Kerr")) .verifyComplete() } @Test fun flatMap() { val playerFlux = Flux.just("Michael Jordan", "Scottie Pippen", "Steve Kerr") .flatMap { n -> Mono.just(n) .map { p -> val split = p.split("\\s".toRegex()) Player(split[0], split[1]) } .subscribeOn(Schedulers.parallel()) /* Schedulers λ™μ‹œμ„± λͺ¨λΈ .immediate(): ν˜„μž¬ μŠ€λ ˆλ“œμ—μ„œ ꡬ독 μ‹€ν–‰ .single(): λ‹¨μΌμ˜ μž¬μ‚¬μš© κ°€λŠ₯ν•œ μŠ€λ ˆλ“œμ—μ„œ ꡬ독 μ‹€ν–‰ -> 이후 λͺ¨λ‘ λ™μΌν•œ μŠ€λ ˆλ“œ μž¬μ‚¬μš© .newSingle(): 맀 ν˜ΈμΆœλ§ˆλ‹€ μ „μš© μŠ€λ ˆλ“œμ—μ„œ ꡬ독 μ‹€ν–‰ .elastic(): λ¬΄ν•œν•˜κ³  μ‹ μΆ•μ„± μžˆλŠ” ν’€μ—μ„œ κ°€μ Έμ˜¨ μž‘μ—… μŠ€λ ˆλ“œμ—μ„œ ꡬ독 μ‹€ν–‰ .parallel(): κ³ μ •λœ 크기의 ν’€(CPU μ½”μ–΄μ˜ 개수)μ—μ„œ κ°€μ Έμ˜¨ μž‘μ—… μŠ€λ ˆλ“œμ—μ„œ ꡬ독 μ‹€ν–‰ */ } val playerList: List<Player> = listOf(Player("Michael", "Jordan"), Player("Scottie", "Pippen"), Player("Steve", "Kerr")) //μˆœμ„œ 보μž₯ X StepVerifier.create(playerFlux) .expectNextMatches { p: Player -> playerList.contains(p) } .expectNextMatches { p: Player -> playerList.contains(p) } .expectNextMatches { p: Player -> playerList.contains(p) } .verifyComplete() } }
Labb_1_androidutveckling/app/src/androidTest/java/com/example/labb_1/ExampleInstrumentedTest.kt
2150698388
package com.example.labb_1 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.labb_1", appContext.packageName) } }
Labb_1_androidutveckling/app/src/test/java/com/example/labb_1/ExampleUnitTest.kt
200892682
package com.example.labb_1 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) } }
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/MainActivity.kt
1853045555
package com.example.labb_1 import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private val validUsernames = arrayOf("ester", "linus", "bruno") @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val usernameEditText = findViewById<EditText>(R.id.username) val loginButton = findViewById<Button>(R.id.loginButton) loginButton.setOnClickListener { val enteredUsername = usernameEditText.text.toString() if (validUsernames.contains(enteredUsername)) { val intent = Intent(this, HomeActivity::class.java) intent.putExtra("username", enteredUsername) startActivity(intent) finish() } else { Toast.makeText( this, "Invalid username. Please try again.", Toast.LENGTH_SHORT ).show() } } } }
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/HomeActivity.kt
416492513
package com.example.labb_1 import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class HomeActivity : AppCompatActivity() { @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.home) val loggedInUserTextView = findViewById<TextView>(R.id.loggedInUser) val username = intent.getStringExtra("username") loggedInUserTextView.text = "Welcome, $username" val logoutButton = findViewById<Button>(R.id.logoutBtn) logoutButton.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } val nextButton = findViewById<Button>(R.id.homeNextBtn) val prevButton = findViewById<Button>(R.id.homePrevBtn) nextButton.setOnClickListener { val intent = Intent(this, SolarsystemActivity::class.java) startActivity(intent) finish() } prevButton.setOnClickListener { val intent = Intent(this, MoonActivity::class.java) startActivity(intent) finish() } } }
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/SolarsystemActivity.kt
70612078
package com.example.labb_1 import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class SolarsystemActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_solarsystem) val nextButton = findViewById<Button>(R.id.homeNextBtn) val prevButton = findViewById<Button>(R.id.homePrevBtn) val logoutButton = findViewById<Button>(R.id.logoutBtn) logoutButton.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } nextButton.setOnClickListener { val intent = Intent(this, MoonActivity::class.java) startActivity(intent) finish() } prevButton.setOnClickListener { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) finish() } } }
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/MoonActivity.kt
3904167388
package com.example.labb_1 import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MoonActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_moon) val nextButton = findViewById<Button>(R.id.homeNextBtn) val prevButton = findViewById<Button>(R.id.homePrevBtn) val logoutButton = findViewById<Button>(R.id.logoutBtn) logoutButton.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } nextButton.setOnClickListener { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) finish() } prevButton.setOnClickListener { val intent = Intent(this, SolarsystemActivity::class.java) startActivity(intent) finish() } } }
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/data/Result.kt
2993406887
package com.example.labb_1.data /** * A generic class that holds a value with its loading status. * @param <T> */ sealed class Result<out T : Any> { data class Success<out T : Any>(val data: T) : Result<T>() data class Error(val exception: Exception) : Result<Nothing>() override fun toString(): String { return when (this) { is Success<*> -> "Success[data=$data]" is Error -> "Error[exception=$exception]" } } }
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/data/LoginDataSource.kt
1195832366
package com.example.labb_1.data import com.example.labb_1.data.model.LoggedInUser import java.io.IOException /** * Class that handles authentication w/ login credentials and retrieves user information. */ class LoginDataSource { fun login(username: String, password: String): Result<LoggedInUser> { try { // TODO: handle loggedInUser authentication val fakeUser = LoggedInUser(java.util.UUID.randomUUID().toString(), "Jane Doe") return Result.Success(fakeUser) } catch (e: Throwable) { return Result.Error(IOException("Error logging in", e)) } } fun logout() { // TODO: revoke authentication } }
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/data/model/LoggedInUser.kt
1326001886
package com.example.labb_1.data.model /** * Data class that captures user information for logged in users retrieved from LoginRepository */ data class LoggedInUser( val userId: String, val displayName: String )
Labb_1_androidutveckling/app/src/main/java/com/example/labb_1/data/LoginRepository.kt
3055462909
package com.example.labb_1.data import com.example.labb_1.data.model.LoggedInUser /** * Class that requests authentication and user information from the remote data source and * maintains an in-memory cache of login status and user credentials information. */ class LoginRepository(val dataSource: LoginDataSource) { // in-memory cache of the loggedInUser object var user: LoggedInUser? = null private set val isLoggedIn: Boolean get() = user != null init { // If user credentials will be cached in local storage, it is recommended it be encrypted // @see https://developer.android.com/training/articles/keystore user = null } fun logout() { user = null dataSource.logout() } fun login(username: String, password: String): Result<LoggedInUser> { // handle login val result = dataSource.login(username, password) if (result is Result.Success) { setLoggedInUser(result.data) } return result } private fun setLoggedInUser(loggedInUser: LoggedInUser) { this.user = loggedInUser // If user credentials will be cached in local storage, it is recommended it be encrypted // @see https://developer.android.com/training/articles/keystore } }
NewsMultiplatformDemo/shared/src/iosMain/kotlin/com/xarhssta/newsmultiplatformdemo/di/KoinInitializer.kt
3361834219
package com.xarhssta.newsmultiplatformdemo.di import com.xarhssta.newsmultiplatformdemo.application.article.ArticlesViewModel import org.koin.core.component.KoinComponent import org.koin.core.component.inject import org.koin.core.context.startKoin fun initKoin() { val modules = sharedKoinModule + databaseModule startKoin { modules(modules) } } class ArticlesInjector: KoinComponent { val articlesViewModel: ArticlesViewModel by inject() }
NewsMultiplatformDemo/shared/src/iosMain/kotlin/com/xarhssta/newsmultiplatformdemo/di/DatabaseModule.kt
952949673
package com.xarhssta.newsmultiplatformdemo.di import app.cash.sqldelight.db.SqlDriver import com.xarhssta.newsmultiplatformdemo.db.DatabaseDriverFactory import com.xarhssta.newsmultiplatformdemo.db.NewsMultiplatformDatabase import org.koin.dsl.module val databaseModule = module { single<SqlDriver> { DatabaseDriverFactory().createDriver() } single<NewsMultiplatformDatabase> { NewsMultiplatformDatabase(get()) } }
NewsMultiplatformDemo/shared/src/iosMain/kotlin/com/xarhssta/newsmultiplatformdemo/BaseViewModel.kt
1176768636
package com.xarhssta.newsmultiplatformdemo import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.cancel actual open class BaseViewModel { actual val scope: CoroutineScope = CoroutineScope(Dispatchers.IO) fun clear() { scope.cancel() } }
NewsMultiplatformDemo/shared/src/iosMain/kotlin/com/xarhssta/newsmultiplatformdemo/db/DatabaseDriverFactory.kt
273901970
package com.xarhssta.newsmultiplatformdemo.db import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.native.NativeSqliteDriver actual class DatabaseDriverFactory { actual fun createDriver(): SqlDriver = NativeSqliteDriver( schema = NewsMultiplatformDatabase.Schema, name = "NewsMultiplatform.Database.db" ) }
NewsMultiplatformDemo/shared/src/iosMain/kotlin/com/xarhssta/newsmultiplatformdemo/Platform.ios.kt
4040541794
package com.xarhssta.newsmultiplatformdemo import platform.Foundation.NSLog import platform.UIKit.UIDevice import platform.UIKit.UIScreen actual class Platform() { actual val osName: String get() = UIDevice.currentDevice.systemName actual val osVersion: String get() = UIDevice.currentDevice.systemVersion actual val deviceModel: String get() = UIDevice.currentDevice.model actual val density: Int get() = UIScreen.mainScreen.scale.toInt() actual fun logPlatformSystemInfo() { NSLog( "($osName, $osVersion, $deviceModel, $density" ) } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/di/SharedKoinModule.kt
547528559
package com.xarhssta.newsmultiplatformdemo.di val sharedKoinModule = listOf( articlesModule, networkModule )
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/di/NetworkModule.kt
2558342027
package com.xarhssta.newsmultiplatformdemo.di import io.ktor.client.HttpClient import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json import org.koin.dsl.module val networkModule = module { single<HttpClient> { HttpClient { install(ContentNegotiation) { json(Json { prettyPrint = true isLenient = true ignoreUnknownKeys = true }) } } } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/di/ArticlesModule.kt
3913527522
package com.xarhssta.newsmultiplatformdemo.di import com.xarhssta.newsmultiplatformdemo.data.article.ArticlesDataSource import com.xarhssta.newsmultiplatformdemo.data.article.ArticlesRepository import com.xarhssta.newsmultiplatformdemo.data.article.ArticlesService import com.xarhssta.newsmultiplatformdemo.application.article.ArticlesViewModel import com.xarhssta.newsmultiplatformdemo.domain.article.FetchArticlesUseCase import org.koin.dsl.module val articlesModule = module { single<ArticlesService> { ArticlesService(get()) } single<ArticlesDataSource> { ArticlesDataSource(get()) } single<ArticlesRepository> { ArticlesRepository(get(), get()) } single<FetchArticlesUseCase> { FetchArticlesUseCase(get()) } single<ArticlesViewModel> { ArticlesViewModel(get()) } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/Platform.kt
748274559
package com.xarhssta.newsmultiplatformdemo expect class Platform { val osName: String val osVersion: String val deviceModel: String val density: Int fun logPlatformSystemInfo() }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/BaseViewModel.kt
2445528051
package com.xarhssta.newsmultiplatformdemo import kotlinx.coroutines.CoroutineScope expect open class BaseViewModel() { val scope: CoroutineScope }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/db/DatabaseDriverFactory.kt
20753954
package com.xarhssta.newsmultiplatformdemo.db import app.cash.sqldelight.db.SqlDriver expect class DatabaseDriverFactory { fun createDriver(): SqlDriver }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/application/article/ArticlesState.kt
1894031557
package com.xarhssta.newsmultiplatformdemo.application.article import com.xarhssta.newsmultiplatformdemo.domain.article.Article data class ArticlesState ( val articles: List<Article> = listOf(), val loading: Boolean = false, val error: String? = null )
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/application/article/ArticlesViewModel.kt
2509154367
package com.xarhssta.newsmultiplatformdemo.application.article import com.xarhssta.newsmultiplatformdemo.BaseViewModel import com.xarhssta.newsmultiplatformdemo.domain.article.FetchArticlesUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class ArticlesViewModel(private val fetchArticlesUseCase: FetchArticlesUseCase): BaseViewModel() { private val _articlesState: MutableStateFlow<ArticlesState> = MutableStateFlow(ArticlesState(loading = true)) val articlesState: StateFlow<ArticlesState> = _articlesState init { getArticles() } fun getArticles(forceFetch: Boolean = false) { scope.launch { _articlesState.emit(ArticlesState(loading = true)) val fetchedArticles = fetchArticlesUseCase.fetchArticles(forceFetch) _articlesState.emit(ArticlesState(articles = fetchedArticles)) } } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/data/article/ArticlesDataSource.kt
1216301114
package com.xarhssta.newsmultiplatformdemo.data.article import com.xarhssta.newsmultiplatformdemo.db.NewsMultiplatformDatabase class ArticlesDataSource(private val database: NewsMultiplatformDatabase) { fun getAllArticles(): List<ArticleRaw> = database .newsMultiplatformDatabaseQueries .selectAll(::mapToArticleRaw) .executeAsList() fun insertArticles(articles: List<ArticleRaw>) { database.newsMultiplatformDatabaseQueries.transaction { articles.forEach { insertArticle(it) } } } fun removeAllArticles() = database.newsMultiplatformDatabaseQueries.removeAllArticles() private fun mapToArticleRaw( title: String, description: String?, date: String, imageUrl: String? ): ArticleRaw = ArticleRaw( title = title, description = description, date = date, imageUrl = imageUrl ) private fun insertArticle(articleRaw: ArticleRaw) { database.newsMultiplatformDatabaseQueries.insertArticle( title = articleRaw.title, description = articleRaw.description, date = articleRaw.date, imageUrl = articleRaw.imageUrl ) } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/data/article/ArticlesResponse.kt
2491376527
package com.xarhssta.newsmultiplatformdemo.data.article import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ArticlesResponse( @SerialName("status") val status: String, @SerialName("totalResults") val totalResults: Int, @SerialName("articles") val articles: List<ArticleRaw> )
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/data/article/ArticleRaw.kt
1298014786
package com.xarhssta.newsmultiplatformdemo.data.article import com.xarhssta.newsmultiplatformdemo.domain.article.Article import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlinx.datetime.TimeZone import kotlinx.datetime.daysUntil import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.todayIn import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlin.math.abs @Serializable data class ArticleRaw( @SerialName("title") val title: String, @SerialName("description") val description: String?, @SerialName("publishedAt") val date: String, @SerialName("urlToImage") val imageUrl: String? ) { companion object { fun ArticleRaw.toArticle(): Article = Article( title = title, description = description ?: "", date = getDaysString(date), imageUrl = imageUrl ?: "" ) } } private fun getDaysString(date: String): String { val days = Clock.System .todayIn(TimeZone.currentSystemDefault()) .daysUntil( Instant .parse(date) .toLocalDateTime(TimeZone.currentSystemDefault()) .date ) return when { abs(days) > 1 -> "${abs(days)} days ago" abs(days) == 1 -> "Yesterday" else -> "Today" } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/data/article/ArticlesRepository.kt
606163839
package com.xarhssta.newsmultiplatformdemo.data.article import com.xarhssta.newsmultiplatformdemo.domain.article.Article class ArticlesRepository( private val service: ArticlesService, private val dataSource: ArticlesDataSource ) { suspend fun getArticles(forceFetch: Boolean): List<Article> { if(forceFetch) { dataSource.removeAllArticles() return fetchArticles() } val articlesDb = dataSource.getAllArticles() if (articlesDb.isEmpty()) { return fetchArticles() } return articlesDb.map { it.toArticle() } } private suspend fun fetchArticles(): List<Article> { val fetchedArticles = service.fetchArticles() dataSource.insertArticles(fetchedArticles) return fetchedArticles.map { it.toArticle() } } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/data/article/ArticlesService.kt
1000360148
package com.xarhssta.newsmultiplatformdemo.data.article import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.get class ArticlesService(private val httpClient: HttpClient) { private val country = "us" private val category = "sports" private val apiKey = "cdf04355b5364d78ae63007f5552a669" suspend fun fetchArticles(): List<ArticleRaw> { val response: ArticlesResponse = httpClient.get("https://newsapi.org/v2/top-headlines?country=$country&category=$category&apiKey=$apiKey").body() return response.articles } }
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/domain/article/Article.kt
1494632720
package com.xarhssta.newsmultiplatformdemo.domain.article data class Article( val title: String, val description: String, val date: String, val imageUrl: String )
NewsMultiplatformDemo/shared/src/commonMain/kotlin/com/xarhssta/newsmultiplatformdemo/domain/article/FetchArticlesUseCase.kt
1172775152
package com.xarhssta.newsmultiplatformdemo.domain.article import com.xarhssta.newsmultiplatformdemo.data.article.ArticlesRepository class FetchArticlesUseCase( private val repository: ArticlesRepository ) { suspend fun fetchArticles(forceFetch: Boolean): List<Article> { return repository.getArticles(forceFetch) } }
NewsMultiplatformDemo/shared/src/androidMain/kotlin/com/xarhssta/newsmultiplatformdemo/BaseViewModel.kt
1667072672
package com.xarhssta.newsmultiplatformdemo import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope actual open class BaseViewModel: ViewModel() { actual val scope = viewModelScope }
NewsMultiplatformDemo/shared/src/androidMain/kotlin/com/xarhssta/newsmultiplatformdemo/Platform.android.kt
4253673709
package com.xarhssta.newsmultiplatformdemo import android.content.res.Resources import android.os.Build import android.util.Log import kotlin.math.round actual class Platform() { actual val osName: String get() = "Android" actual val osVersion: String get() ="${Build.VERSION.SDK_INT}" actual val deviceModel: String get() = "${Build.MANUFACTURER} ${Build.MODEL}" actual val density: Int get() = round(Resources.getSystem().displayMetrics.density).toInt() actual fun logPlatformSystemInfo() { Log.d( "NewsMultiplatformDemo", "($osName, $osVersion, $deviceModel, $density" ) } }
NewsMultiplatformDemo/shared/src/androidMain/kotlin/com/xarhssta/newsmultiplatformdemo/db/DatabaseDriverFactory.kt
3127769879
package com.xarhssta.newsmultiplatformdemo.db import android.content.Context import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.android.AndroidSqliteDriver actual class DatabaseDriverFactory(private val context: Context) { actual fun createDriver(): SqlDriver = AndroidSqliteDriver( schema = NewsMultiplatformDatabase.Schema, context = context, name = "NewsMultiplatform.Database.db" ) }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/MainActivity.kt
3012424832
package com.xarhssta.newsmultiplatformdemo.android import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.* import androidx.compose.ui.Modifier class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApplicationTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { AppScaffold() } } } } }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/di/ViewModelsModule.kt
4191531840
package com.xarhssta.newsmultiplatformdemo.android.di import com.xarhssta.newsmultiplatformdemo.application.article.ArticlesViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelsModule = module { viewModel { ArticlesViewModel(get()) } }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/di/DatabaseModule.kt
1468850513
package com.xarhssta.newsmultiplatformdemo.android.di import app.cash.sqldelight.db.SqlDriver import com.xarhssta.newsmultiplatformdemo.db.DatabaseDriverFactory import com.xarhssta.newsmultiplatformdemo.db.NewsMultiplatformDatabase import org.koin.android.ext.koin.androidContext import org.koin.dsl.module val databaseModule = module { single<SqlDriver> { DatabaseDriverFactory(androidContext()).createDriver() } single<NewsMultiplatformDatabase> { NewsMultiplatformDatabase(get()) } }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/MyApplicationTheme.kt
4096862818
package com.xarhssta.newsmultiplatformdemo.android import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Shapes import androidx.compose.material3.Typography import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color 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.dp import androidx.compose.ui.unit.sp @Composable fun MyApplicationTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { darkColorScheme( primary = Color(0xFFBB86FC), secondary = Color(0xFF03DAC5), tertiary = Color(0xFF3700B3) ) } else { lightColorScheme( primary = Color(0xFF6200EE), secondary = Color(0xFF03DAC5), tertiary = Color(0xFF3700B3) ) } val typography = Typography( bodyMedium = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) ) val shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) ) MaterialTheme( colorScheme = colors, typography = typography, shapes = shapes, content = content ) }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/NewsMultiplatformApp.kt
2879656716
package com.xarhssta.newsmultiplatformdemo.android import android.app.Application import com.xarhssta.newsmultiplatformdemo.android.di.databaseModule import com.xarhssta.newsmultiplatformdemo.android.di.viewModelsModule import com.xarhssta.newsmultiplatformdemo.di.sharedKoinModule import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class NewsMultiplatformApp: Application() { override fun onCreate() { super.onCreate() initKoin() } private fun initKoin() { val modules = sharedKoinModule + viewModelsModule + databaseModule startKoin { androidContext(this@NewsMultiplatformApp) modules(modules) } } }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/AppScaffold.kt
1387178144
package com.xarhssta.newsmultiplatformdemo.android 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 androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.xarhssta.newsmultiplatformdemo.android.screens.ArticlesScreen import com.xarhssta.newsmultiplatformdemo.android.screens.DetailsScreen import com.xarhssta.newsmultiplatformdemo.android.screens.Screen @Composable fun AppScaffold() { val navController = rememberNavController() Scaffold { AppNavHost( navController = navController, modifier = Modifier .fillMaxSize() .padding(it) ) } } @Composable fun AppNavHost( navController: NavHostController, modifier: Modifier = Modifier ) { NavHost( navController = navController, startDestination = Screen.ARTICLES.route, modifier = modifier ) { composable(Screen.ARTICLES.route) { ArticlesScreen( onAboutButtonClick = { navController.navigate(Screen.DEVICE_DETAILS.route) }) } composable(Screen.DEVICE_DETAILS.route) { DetailsScreen(onBackClick = { navController.popBackStack() }) } } }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/screens/ArticlesScreen.kt
408087150
package com.xarhssta.newsmultiplatformdemo.android.screens import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Info import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.SwipeRefreshState import com.xarhssta.newsmultiplatformdemo.domain.article.Article import com.xarhssta.newsmultiplatformdemo.application.article.ArticlesViewModel import org.koin.androidx.compose.getViewModel @Composable fun ArticlesScreen( articlesViewModel: ArticlesViewModel = getViewModel(), onAboutButtonClick: () -> Unit = { } ) { val articlesState = articlesViewModel.articlesState.collectAsState() Column { AppBar(onAboutButtonClick) if (articlesState.value.loading) { Loader() } if (articlesState.value.error != null) { ErrorMessage(articlesState.value.error) } if (articlesState.value.articles.isNotEmpty()) { ArticlesListView(articlesViewModel) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun AppBar(onAboutButtonClick: () -> Unit) { TopAppBar( title = { Text(text = "Articles") }, actions = { IconButton(onClick = onAboutButtonClick) { Icon( imageVector = Icons.Outlined.Info, contentDescription = "Device Details Button" ) } } ) } @Composable fun Loader() { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { CircularProgressIndicator( modifier = Modifier.width(64.dp), color = MaterialTheme.colorScheme.surfaceVariant, trackColor = MaterialTheme.colorScheme.secondary ) } } @Composable fun ErrorMessage(message: String?) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text( text = message?.lowercase() ?: "unknown error", style = TextStyle(fontSize = 28.sp, textAlign = TextAlign.Center) ) } } @Composable fun ArticlesListView(viewModel: ArticlesViewModel) { SwipeRefresh( state = SwipeRefreshState(viewModel.articlesState.value.loading), onRefresh = { viewModel.getArticles(true) } ) { LazyColumn(modifier = Modifier.fillMaxSize()) { items(viewModel.articlesState.value.articles) { ArticleItemView(it) } } } } @Composable fun ArticleItemView(article: Article) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { AsyncImage( model = article.imageUrl, contentDescription = null ) Spacer(modifier = Modifier.height(4.dp)) Text( text = article.title, style = TextStyle(fontWeight = FontWeight.Bold), fontSize = 22.sp ) Spacer(modifier = Modifier.height(8.dp)) Text(text = article.description) Spacer(modifier = Modifier.height(4.dp)) Text( text = article.date, style = TextStyle(color = Color.Gray), modifier = Modifier.align(Alignment.End) ) Spacer(modifier = Modifier.height(4.dp)) } }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/screens/DetailsScreen.kt
1792840196
package com.xarhssta.newsmultiplatformdemo.android.screens import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.xarhssta.newsmultiplatformdemo.Platform @Composable fun DetailsScreen( onBackClick: () -> Unit = { } ) { Column { Toolbar(onBackClick) ContentView() } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun Toolbar(onBackClick: () -> Unit) { TopAppBar( title = { Text(text = "Device Details") }, navigationIcon = { IconButton(onClick = onBackClick) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back Button") } } ) } @Composable private fun ContentView() { val items = makeItems() LazyColumn(modifier = Modifier.fillMaxSize()) { items(items) { RowView(title = it.first, subtitle = it.second) } } } @Composable private fun RowView(title: String, subtitle: String) { Column(Modifier.padding(8.dp)) { Text( text = title, style = MaterialTheme.typography.bodySmall, color = Color.Gray ) Text( text = subtitle, style = MaterialTheme.typography.bodyLarge ) } Divider() } private fun makeItems(): List<Pair<String, String>> { val platform = Platform() platform.logPlatformSystemInfo() return listOf( Pair("Operating System", "${platform.osName} ${platform.osVersion}"), Pair("Device Model", platform.deviceModel), Pair("Screen Density", platform.density.toString()) ) } @Preview @Composable private fun DetailsScreenPreview() { Surface { DetailsScreen() } }
NewsMultiplatformDemo/androidApp/src/main/java/com/xarhssta/newsmultiplatformdemo/android/screens/Screen.kt
3615954860
package com.xarhssta.newsmultiplatformdemo.android.screens enum class Screen(val route: String) { ARTICLES("articles"), DEVICE_DETAILS("device-details") }
OpenMind/openmind/src/androidTest/java/com/example/openmind/ExampleInstrumentedTest.kt
1457837837
package com.example.openmind import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * 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.openmind", appContext.packageName) } }
OpenMind/openmind/src/test/java/com/example/openmind/ExampleUnitTest.kt
221868806
package com.example.openmind import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/MainViewModel.kt
4209429837
package com.example.openmind.ui import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.openmind.di.repository.ProfileRepositoryProvider import com.example.openmind.utils.SessionManager import kotlinx.coroutines.launch import java.io.IOException import java.lang.RuntimeException import java.net.SocketTimeoutException class MainViewModel : GlobalViewModel() { private val repository = ProfileRepositoryProvider.provideRepository() private var currentProfileId: String = "111e4567-e89b-12d3-a456-426614174000" init { setJwtTokenForCurrentProfile() } private fun setJwtTokenForCurrentProfile() { SessionManager.clearSharedPreferences() viewModelScope.launch { try { val token = repository.generateJwtToken(currentProfileId) SessionManager.saveJwtToken(token) } catch (e: IOException) { handleError(e) } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post/viewmodel/PostViewState.kt
1044206354
package com.example.openmind.ui.post.viewmodel import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.text.input.TextFieldValue import com.example.openmind.domain.model.comment.CommentModel import com.example.openmind.domain.model.post.PostDto import com.example.openmind.enums.SortType internal class PostViewState { val postIsLoading = mutableStateOf(true) val commentToReply = mutableStateOf<CommentModel?>(null) val defaultCommentLines = 3 val commentsBatchSize = 5 val commentMessage = mutableStateOf( TextFieldValue("") ) val commentFieldFocusRequester = FocusRequester() var activeSortType: MutableState<SortType> = mutableStateOf(SortType.HOT) val sortingList: List<SortType> = listOf( SortType.HOT, SortType.NEW, SortType.OLD ) var currentPostId: String = "" var post: MutableState<PostDto> = mutableStateOf(PostDto("", "")) val comments = mutableStateListOf<CommentModel>() }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post/viewmodel/PostViewModel.kt
3121080221
package com.example.openmind.ui.post.viewmodel import android.util.Log import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableIntStateOf import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import androidx.lifecycle.viewModelScope import com.example.openmind.data.repository.CommentsRepository import com.example.openmind.data.repository.PostRepository import com.example.openmind.di.repository.CommentsRepositoryProvider import com.example.openmind.di.repository.PostRepositoryProvider import com.example.openmind.domain.model.comment.CommentModel import com.example.openmind.domain.model.comment.CreateCommentModel import com.example.openmind.domain.model.rating.RatingInfo import com.example.openmind.ui.GlobalViewModel import com.example.openmind.ui.post.components.comments.withStylishTags import com.example.openmind.enums.SortType import com.example.openmind.utils.Sortable import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch class PostViewModel : GlobalViewModel(), Sortable { private val viewState: PostViewState = PostViewState() private val postRepository: PostRepository = PostRepositoryProvider.provideRepository() private val commentRepository: CommentsRepository = CommentsRepositoryProvider.provideRepository() override fun setActiveSortType(sortType: SortType) { viewState.activeSortType.value = sortType } override fun activeSortType(): SortType = viewState.activeSortType.value override fun getSortingList(): List<SortType> = viewState.sortingList fun getFocusRequester() = viewState.commentFieldFocusRequester fun getPost() = viewState.post.value fun getPostRating() = RatingInfo( ratingId = getPost().ratingId, rating = mutableIntStateOf(getPost().rating), isRated = mutableIntStateOf(getPost().isRated) ) fun getReplyComment() = viewState.commentToReply fun getShortCommentLinesCount() = viewState.defaultCommentLines fun getCommentBatchSize() = viewState.commentsBatchSize fun postIsLoading(): Boolean = viewState.postIsLoading.value fun commentMessage() = viewState.commentMessage fun getComments() = viewState.comments fun setCurrentPostID(postId: String) { viewState.currentPostId = postId } fun setReplyComment(comment: CommentModel) { Log.i("PostViewModel", "SetReplyCommentTO $comment") viewState.commentToReply.value = comment val initialString = withStylishTags("@" + viewState.commentToReply.value!!.commentAuthor.let { "$it, " }) val selection = TextRange(initialString.length) viewState.commentMessage.value = TextFieldValue( annotatedString = initialString, selection = selection ) viewState.commentFieldFocusRequester.requestFocus() } fun onCommentChange(): (TextFieldValue) -> Unit = { it -> if (viewState.commentMessage.value.text.contains("@")) viewState.commentMessage.value = TextFieldValue( annotatedString = withStylishTags(it.text), selection = it.selection ) else { viewState.commentMessage.value = it viewState.commentToReply.value = null } } private fun saveComment(comment: CreateCommentModel) { viewModelScope.launch { commentRepository.postComment(comment) fetchCommentsInternal() } } fun onCommentSend(focusManager: FocusManager, replyTo: MutableState<CommentModel?>) { val commentToPost = CreateCommentModel(commentMessage = viewState.commentMessage.value.text) commentToPost.postId = viewState.currentPostId if (replyTo.value != null) { commentToPost.parentCommentId = replyTo.value!!.commentId } saveComment(commentToPost) replyTo.value = null focusManager.clearFocus() viewState.commentMessage.value = TextFieldValue("") } fun fetchPostDetails() { viewModelScope.launch { viewState.postIsLoading.value = true val loadPostJob = async { fetchPostInternal() } val loadCommentsJob = async { fetchCommentsInternal() } awaitAll(loadPostJob, loadCommentsJob) viewState.postIsLoading.value = false } } private suspend fun fetchPostInternal() { kotlin.runCatching { postRepository.fetchPostById(viewState.currentPostId) }.onSuccess { viewState.post.value = it }.onFailure { handleError(it) } } private suspend fun fetchCommentsInternal() { kotlin.runCatching { commentRepository.fetchCommentsByPostId(viewState.currentPostId) }.onSuccess { viewState.comments.clear() viewState.comments.addAll(it) }.onFailure { handleError(it) } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post/PostContentView.kt
485216346
package com.example.openmind.ui.post import CommentField import NoRippleInteractionSource import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.CircularProgressIndicator 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.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.R import com.example.openmind.ui.components.general.RatingView import com.example.openmind.ui.components.general.borderBottom import com.example.openmind.ui.post.components.comments.CommentView import com.example.openmind.ui.post.viewmodel.PostViewModel import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.DarkBlue40 import com.example.openmind.ui.theme.Delimiter import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeBoldW700 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.ManropeSemiBoldW600 import com.example.openmind.ui.theme.SteelBlue60 import com.example.openmind.ui.theme.spacing @RequiresApi(Build.VERSION_CODES.O) @Composable fun PostContentView( viewModel: PostViewModel, modifier: Modifier = Modifier ) { Column( modifier = modifier .padding( start = MaterialTheme.spacing.large, end = MaterialTheme.spacing.large, bottom = 5.dp ) .fillMaxSize() ) { if (viewModel.postIsLoading() /*and viewModel.isCommentsLoading()*/) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator(modifier = Modifier.size(40.dp)) } } else { LazyColumn( Modifier.weight(1f) ) { item { Column { Column( modifier = Modifier.borderBottom(1.dp, Delimiter) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { Row(verticalAlignment = Alignment.CenterVertically) { //UserIcon Image( painter = painterResource(R.drawable.user_pic), contentDescription = "user_icon", modifier = Modifier .size(30.dp) .padding(start = 0.dp, end = 7.dp, top = 6.dp) ) //Category name Text( text = viewModel.getPost().category, fontSize = 14.sp, lineHeight = 20.sp, maxLines = 1, fontFamily = FontFamily.ManropeSemiBoldW600, ) //Created Time Text( text = viewModel.getPost().formatElapsedTime(), fontSize = 14.sp, lineHeight = 20.sp, maxLines = 1, fontFamily = FontFamily.ManropeRegularW400, modifier = Modifier.padding(start = 20.dp), color = SteelBlue60 ) } //more button (three dots) IconButton( onClick = { }, modifier = Modifier .size(24.dp) .padding(end = 10.dp), interactionSource = NoRippleInteractionSource.INSTANCE ) { Icon( Icons.Default.MoreVert, contentDescription = stringResource(id = R.string.content_description_more), modifier = Modifier .size(24.dp) .rotate(90f) ) } } //Post Title Text( text = viewModel.getPost().title, fontSize = 16.sp, lineHeight = 24.sp, fontFamily = FontFamily.ManropeBoldW700, color = DarkBlue40, ) //Post Description Text( text = viewModel.getPost().description, fontSize = 12.sp, lineHeight = 16.sp, fontFamily = FontFamily.ManropeRegularW400, modifier = Modifier.padding(top = 6.dp) ) // FeedBack and Share Row( modifier = Modifier .padding(top = 14.dp, bottom = 12.dp) .fillMaxWidth(), ) { //Rating RatingView( viewModel.getPostRating(), Modifier, onRatingChange = viewModel.onRatingChange() ) //Comments Column( modifier = Modifier .padding(horizontal = 4.dp) .weight(1f) ) { Row( modifier = Modifier .clip(CircleShape) .border(1.dp, BorderLight, CircleShape) .padding(end = 20.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( painter = painterResource(id = R.drawable.message), contentDescription = stringResource(id = R.string.content_description_decrease), modifier = Modifier .padding( start = 10.dp, top = 5.dp, bottom = 5.dp, end = 6.dp ) .size(20.dp), tint = MaibPrimary ) Text( text = stringResource( R.string.comments_count, viewModel.getPost().commentCount ), style = MaterialTheme.typography.titleMedium, maxLines = 1, textAlign = TextAlign.Center ) } } // SharePost(viewModel.getPost().postId) } } } } item { Spacer(modifier = Modifier.height(16.dp)) } items(items = viewModel.getComments()) { item -> CommentView( viewModel = viewModel, item = item, onReplyClick = { comment -> viewModel.setReplyComment(comment) }) } } } LaunchedEffect(Unit) { viewModel.fetchPostDetails() } CommentField(viewModel = viewModel, replyTo = viewModel.getReplyComment()) } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post/components/comments/CommentField.kt
1362544746
import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Send import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.openmind.R import com.example.openmind.domain.model.comment.CommentModel import com.example.openmind.ui.post.viewmodel.PostViewModel import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.DarkGray20 import com.example.openmind.ui.theme.IconColor import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeSemiBoldW600 @OptIn(ExperimentalMaterial3Api::class) @Composable fun CommentField( viewModel: PostViewModel, modifier: Modifier = Modifier, replyTo: MutableState<CommentModel?> = remember { mutableStateOf(null) }, ) { val focusManager = LocalFocusManager.current val commentPlaceholderText = stringResource(id = R.string.comment_placeholder) Row( modifier = modifier .background(color = Color.White) .border(2.dp, BorderLight, RoundedCornerShape(6.dp)) .padding(bottom = 5.dp, start = 10.dp, end = 10.dp), verticalAlignment = Alignment.CenterVertically ) { BasicTextField( value = viewModel.commentMessage().value, onValueChange = viewModel.onCommentChange(), modifier = Modifier .defaultMinSize(minHeight = 40.dp) .padding(start = 14.dp, top = 5.dp, bottom = 5.dp) .focusRequester(viewModel.getFocusRequester()) .weight(1f), textStyle = TextStyle( fontSize = 16.sp, fontWeight = FontWeight.W600, fontFamily = FontFamily.ManropeSemiBoldW600, lineHeight = 24.sp, color = DarkGray20, textAlign = TextAlign.Justify ), singleLine = true, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Done, capitalization = KeyboardCapitalization.Sentences ), keyboardActions = KeyboardActions( onDone = { viewModel.onCommentSend(focusManager, replyTo) } ), decorationBox = @Composable { innerTextField -> TextFieldDefaults.TextFieldDecorationBox( value = viewModel.commentMessage().value.text, innerTextField = innerTextField, enabled = true, singleLine = true, visualTransformation = VisualTransformation.None, interactionSource = remember { MutableInteractionSource() }, colors = TextFieldDefaults.textFieldColors( unfocusedIndicatorColor = Color.Transparent, containerColor = Color.Transparent, ), shape = RoundedCornerShape(6.dp), placeholder = { Text( text = commentPlaceholderText, color = IconColor, fontFamily = FontFamily.ManropeSemiBoldW600, fontSize = 16.sp, lineHeight = 24.sp, modifier = Modifier.fillMaxWidth() ) }, contentPadding = PaddingValues(5.dp), ) }, ) Icon( Icons.Default.Send, contentDescription = "send", modifier = Modifier .clickable { viewModel.onCommentSend(focusManager, replyTo) } .size(30.dp), tint = MaibPrimary ) } } @Preview @Composable fun CommentFieldPreview() { CommentField(viewModel = viewModel()) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post/components/comments/SubCommentView.kt
615598130
package com.example.openmind.ui.post.components.comments import android.util.Log import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.MoreVert 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.runtime.mutableIntStateOf 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.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.R import com.example.openmind.domain.model.comment.CommentModel import com.example.openmind.domain.model.rating.RatingInfo import com.example.openmind.ui.components.general.RatingView import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.DarkGray20 import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeBoldW700 import com.example.openmind.ui.theme.ManropeExtraBoldW800 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.spacing @Composable fun SubCommentView( item: CommentModel, onReplyClick: (CommentModel) -> Unit, onRatingChange: (String, Int) -> Unit ) { val defaultMaxLine = remember { mutableIntStateOf(3) } val readMoreLabel = stringResource(id = R.string.read_more_label).lowercase() val showLessLabel = stringResource(id = R.string.show_less) val extendButtonLabel = remember { mutableStateOf(readMoreLabel) } val linesCount = remember { mutableIntStateOf(1) } val rating = remember { RatingInfo( ratingId = item.ratingId, rating = mutableStateOf(item.rating), isRated = mutableStateOf(item.isRated) ) } val tagSpanStyle = SpanStyle( fontWeight = FontWeight.W800, fontFamily = FontFamily.ManropeExtraBoldW800, fontStyle = FontStyle.Italic, fontSize = 12.sp, color = Color.Black ) Row { Row( modifier = Modifier .padding(end = 10.dp) ) { Icon( Icons.Default.AccountCircle, "user", tint = MaibPrimary, modifier = Modifier.size(30.dp) ) } Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Row { Text( text = item.commentAuthor, fontFamily = FontFamily.ManropeBoldW700, fontSize = 14.sp, lineHeight = 14.sp, color = DarkGray20, fontWeight = FontWeight.W700 ) Text( text = item.formatElapsedTime(), fontFamily = FontFamily.ManropeRegularW400, fontSize = 14.sp, lineHeight = 20.sp, fontWeight = FontWeight.W400, color = BorderLight, modifier = Modifier.padding(start = 20.dp) ) } IconButton(onClick = { /*TODO*/ }, modifier = Modifier.size(20.dp)) { Icon( Icons.Default.MoreVert, "more", modifier = Modifier.rotate(90f) ) } } Column { Text( text = if (item.commentMessage.contains("@")) { withStylishTags( item.commentMessage, tagSpanStyle ) } else { AnnotatedString(item.commentMessage) }, fontFamily = FontFamily.ManropeRegularW400, fontSize = 12.sp, fontWeight = FontWeight.W400, lineHeight = 16.sp, color = DarkGray20, overflow = TextOverflow.Ellipsis, maxLines = defaultMaxLine.intValue, onTextLayout = { textLayoutResult -> linesCount.intValue = textLayoutResult.lineCount } ) if (linesCount.intValue > 3) { Text( text = extendButtonLabel.value, fontWeight = FontWeight.W400, fontFamily = FontFamily.ManropeRegularW400, fontSize = 14.sp, lineHeight = 16.sp, color = BorderLight, maxLines = 1, modifier = Modifier.clickable { defaultMaxLine.intValue = if (defaultMaxLine.intValue == 3) Int.MAX_VALUE else 3 extendButtonLabel.value = if (extendButtonLabel.value == readMoreLabel) showLessLabel else readMoreLabel } ) } } Row { RatingView( rating = rating, isComment = true, onRatingChange = onRatingChange ) Box( contentAlignment = Alignment.Center, modifier = Modifier.padding(vertical = 3.dp, horizontal = MaterialTheme.spacing.small) ) { Text( text = "Reply", fontFamily = FontFamily.ManropeBoldW700, fontSize = 12.sp, fontWeight = FontWeight.W700, lineHeight = 16.sp, maxLines = 1, modifier = Modifier.clickable { Log.i( "SubCommentView", "Clicked reply to ${item.commentAuthor}'s comment " ) onReplyClick(item) } ) } } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post/components/comments/CommentUtils.kt
2190476242
package com.example.openmind.ui.post.components.comments import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.sp import com.example.openmind.ui.theme.ManropeExtraBoldW800 fun withStylishTags( text: String, styleSpan: SpanStyle = SpanStyle( fontWeight = FontWeight.W800, fontFamily = FontFamily.ManropeExtraBoldW800, fontStyle = FontStyle.Italic, fontSize = 16.sp, color = Color.Black ) ): AnnotatedString { val result = AnnotatedString.Builder() val delimiter = " " val words = text.split(delimiter) for ((index, word) in words.withIndex()) { if (word.indexOf("@") == 0) { result.withStyle(style = styleSpan) { append(word) } } else { result.append(word) } if (index < words.lastIndex) { result.append(delimiter) } } return result.toAnnotatedString() }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post/components/comments/CommentView.kt
4180043332
package com.example.openmind.ui.post.components.comments import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.MoreVert 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.runtime.mutableIntStateOf 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.rotate import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.R import com.example.openmind.domain.model.comment.CommentModel import com.example.openmind.domain.model.rating.RatingInfo import com.example.openmind.ui.components.general.RatingView import com.example.openmind.ui.post.viewmodel.PostViewModel import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.DarkGray20 import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeBoldW700 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.spacing @Composable fun CommentView( viewModel: PostViewModel, item: CommentModel, onReplyClick: (CommentModel) -> Unit ) { val isShowVisible = remember { mutableStateOf(true) } val currentLinesCount = remember { mutableIntStateOf(viewModel.getShortCommentLinesCount()) } val readMoreLabel = stringResource(id = R.string.read_more_label).lowercase() val showLessLabel = stringResource(id = R.string.show_less) val extendButtonLabel = remember { mutableStateOf(readMoreLabel) } val linesCount = remember { mutableIntStateOf(1) } val currentActiveCommentsCount = remember { mutableIntStateOf(0) } val rating = remember { RatingInfo( ratingId = item.ratingId, rating = mutableIntStateOf(item.rating), isRated = mutableIntStateOf(item.isRated) ) } Row(modifier = Modifier.padding(bottom = MaterialTheme.spacing.small)) { Row( modifier = Modifier .padding(end = 10.dp) ) { Icon( Icons.Default.AccountCircle, "user", tint = MaibPrimary, modifier = Modifier.size(30.dp) ) } Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Row { Text( text = item.commentAuthor, fontFamily = FontFamily.ManropeBoldW700, fontSize = 14.sp, lineHeight = 14.sp, color = DarkGray20, fontWeight = FontWeight.W700 ) Text( text = item.formatElapsedTime(), fontFamily = FontFamily.ManropeRegularW400, fontSize = 14.sp, lineHeight = 20.sp, fontWeight = FontWeight.W400, color = BorderLight, modifier = Modifier.padding(start = 20.dp) ) } IconButton(onClick = { /*TODO*/ }, modifier = Modifier.size(20.dp)) { Icon( Icons.Default.MoreVert, "more", modifier = Modifier.rotate(90f) ) } } Column { Text( text = item.commentMessage, fontFamily = FontFamily.ManropeRegularW400, fontSize = 12.sp, fontWeight = FontWeight.W400, lineHeight = 16.sp, color = DarkGray20, overflow = TextOverflow.Ellipsis, maxLines = currentLinesCount.intValue, onTextLayout = { textLayoutResult -> linesCount.intValue = textLayoutResult.lineCount } ) if (linesCount.intValue > viewModel.getShortCommentLinesCount()) { Text( text = extendButtonLabel.value, fontWeight = FontWeight.W400, fontFamily = FontFamily.ManropeRegularW400, fontSize = 14.sp, lineHeight = 16.sp, color = BorderLight, maxLines = 1, modifier = Modifier.clickable { currentLinesCount.intValue = if (currentLinesCount.intValue == viewModel.getShortCommentLinesCount()) Int.MAX_VALUE else viewModel.getShortCommentLinesCount() extendButtonLabel.value = if (extendButtonLabel.value == readMoreLabel) showLessLabel else readMoreLabel } ) } } Row { RatingView( rating = rating, isComment = true, onRatingChange = viewModel.onRatingChange() ) Box( contentAlignment = Alignment.Center, modifier = Modifier.padding(vertical = 3.dp, horizontal = MaterialTheme.spacing.small) ) { Text( text = "Reply", fontFamily = FontFamily.ManropeBoldW700, fontSize = 12.sp, fontWeight = FontWeight.W700, lineHeight = 16.sp, maxLines = 1, modifier = Modifier.clickable { onReplyClick(item) } ) } } if (item.subComments.isNotEmpty() && isShowVisible.value) { Text( text = stringResource( R.string.show_replies, item.subComments.size ), style = MaterialTheme.typography.titleSmall, color = MaibPrimary, modifier = Modifier.clickable { isShowVisible.value = !isShowVisible.value currentActiveCommentsCount.intValue = (currentActiveCommentsCount.intValue + viewModel.getCommentBatchSize()) % item.subComments.size + 1 } ) } else { item.subComments.take(currentActiveCommentsCount.intValue) .forEachIndexed { index, subItem -> when (index) { (item.subComments.size) -> { SubCommentView( subItem, onReplyClick = onReplyClick, onRatingChange = viewModel.onRatingChange() ) Text( text = stringResource( R.string.hide_replies, item.subComments.size ), style = MaterialTheme.typography.titleSmall, color = MaibPrimary, modifier = Modifier.clickable { isShowVisible.value = !isShowVisible.value currentActiveCommentsCount.intValue = 0 } ) } currentActiveCommentsCount.intValue -> { SubCommentView( subItem, onReplyClick = onReplyClick, onRatingChange = viewModel.onRatingChange() ) Text( text = stringResource( R.string.show_replies, item.subComments.size - currentActiveCommentsCount.intValue ), style = MaterialTheme.typography.titleSmall, color = MaibPrimary, modifier = Modifier.clickable { currentActiveCommentsCount.intValue = (currentActiveCommentsCount.intValue + viewModel.getCommentBatchSize()) } ) } else -> { SubCommentView( subItem, onReplyClick = onReplyClick, onRatingChange = viewModel.onRatingChange() ) } } } } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/search_result/viewModel/SearchResultViewModel.kt
4183511741
package com.example.openmind.ui.search_result.viewModel import androidx.compose.runtime.mutableStateOf import com.example.openmind.enums.PostCategories import com.example.openmind.ui.GlobalViewModel import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class SearchResultViewModel : GlobalViewModel() { private val _viewState = mutableStateOf(SearchResultViewState()) val viewState get() = _viewState.value fun getSearchResults() = viewState.searchResultList fun searchWithQuery(query: String, category: String) { GlobalScope .launch { viewState.searchResultList.clear() viewState.repository.findByTitle(query, PostCategories.valueOf(category)) .catch { cause: Throwable -> handleError(cause) } .collect { viewState.searchResultList.addAll(it) } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/search_result/viewModel/SearchResultViewState.kt
3091715801
package com.example.openmind.ui.search_result.viewModel import androidx.compose.runtime.mutableStateListOf import com.example.openmind.data.repository.PostRepository import com.example.openmind.di.repository.PostRepositoryProvider import com.example.openmind.domain.model.post.ShortPostDto class SearchResultViewState { val repository:PostRepository = PostRepositoryProvider.provideRepository() val searchResultList = mutableStateListOf<ShortPostDto>() }
OpenMind/openmind/src/main/java/com/example/openmind/ui/search_result/SearchResultsView.kt
1390345361
package com.example.openmind.ui.search_result import androidx.compose.foundation.layout.Box import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.example.openmind.ui.components.general.borderBottom import com.example.openmind.ui.navigation.navigateToPost import com.example.openmind.ui.post_list.components.PostShortView import com.example.openmind.ui.search_result.viewModel.SearchResultViewModel import com.example.openmind.ui.theme.Delimiter @Composable fun SearchResultContentView( navController: NavController, viewModel: SearchResultViewModel, modifier: Modifier = Modifier, ) { val searchResults = remember { viewModel.getSearchResults() } Box(modifier = modifier) { LazyColumn(Modifier.borderBottom(1.dp, Delimiter)) { items(items = searchResults, itemContent = { item -> PostShortView( post = item, onRatingChange = viewModel.onRatingChange(), navigateToPost = { navController.navigateToPost(item.postId) } ) }) } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/create_post/viewModel/CreatePostViewState.kt
389980828
package com.example.openmind.ui.create_post.viewModel import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.text.input.TextFieldValue import com.example.openmind.enums.PostCategories class CreatePostViewState { val title = mutableStateOf(TextFieldValue("")) val description = mutableStateOf(TextFieldValue("")) lateinit var activeCategory: PostCategories val categories = mutableStateListOf<PostCategories>() val isCategoriesLoading = mutableStateOf(true) val isCategoriesDropdownMenuVisible = mutableStateOf(false) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/create_post/viewModel/CreatePostViewModel.kt
2320889076
package com.example.openmind.ui.create_post.viewModel import androidx.compose.ui.text.input.TextFieldValue import com.example.openmind.di.repository.CategoriesRepositoryProvider import com.example.openmind.di.repository.PostRepositoryProvider import com.example.openmind.enums.PostCategories import com.example.openmind.domain.model.post.CreatePostDto import com.example.openmind.ui.GlobalViewModel import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch const val tag = "CreatePostViewModel" class CreatePostViewModel : GlobalViewModel() { private val viewState: CreatePostViewState = CreatePostViewState() val repository = PostRepositoryProvider.provideRepository() val categoryRepository = CategoriesRepositoryProvider.provideRepository() fun getDropdownVisibility() = viewState.isCategoriesDropdownMenuVisible.value fun setDropdownVisibility(isVisible: Boolean) { viewState.isCategoriesDropdownMenuVisible.value = isVisible } fun getDescription() = viewState.description.value fun getTitle() = viewState.title.value fun getCategory(): String = viewState.activeCategory.getStringValue() fun setCategory(postCategories: PostCategories) { viewState.activeCategory = postCategories } fun createPost(): CreatePostDto { val newPost = CreatePostDto( title = viewState.title.value.text, description = viewState.description.value.text, category = viewState.activeCategory.getStringValue() ) GlobalScope.launch { repository.postData(newPost) } return newPost } fun onTitleChange(): (TextFieldValue) -> Unit = { newTitle -> viewState.title.value = newTitle } fun onDescriptionChange(): (TextFieldValue) -> Unit = { newDescription -> viewState.description.value = newDescription } fun onCreatePostButton(): Unit { createPost() } fun fetchCategories() { GlobalScope.launch { viewState.isCategoriesLoading.value = true categoryRepository.fetchAll().catch { cause: Throwable -> handleError(cause) } .collect { list -> viewState.categories.clear() viewState.categories.addAll(list.map { PostCategories.valueOf(it.categoryName) }) viewState.isCategoriesLoading.value = false } } } fun getCategoriesList() = viewState.categories }
OpenMind/openmind/src/main/java/com/example/openmind/ui/create_post/components/TopAppBarCreatePost.kt
1545678043
package com.example.openmind.ui.create_post.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.example.openmind.ui.components.general.BasicTopAppBar import com.example.openmind.ui.create_post.viewModel.CreatePostViewModel import com.example.openmind.ui.screen.Screen import com.example.openmind.ui.theme.DarkBlue40 import com.example.openmind.ui.theme.NightBlue import com.example.openmindproject.ui.theme.NavigationIconStyle import com.example.openmindproject.ui.theme.OpenMindProjectTheme const val TAG: String = "PostTopAppBar" @Composable fun TopAppBarCreatePost( navController: NavController, viewModel: CreatePostViewModel, screen: Screen<*> ) { BasicTopAppBar( viewModel = viewModel, navController = navController, currentScreen = screen, titleStyle = MaterialTheme.typography.titleLarge.merge(TextStyle( textAlign = TextAlign.Center, color = NightBlue )), modifier = Modifier.padding(top = 20.dp), navIconStyle = NavigationIconStyle( iconColor = DarkBlue40 ) ) } @Preview @Composable @ExperimentalMaterial3Api fun TopAppBarPostPreview() { OpenMindProjectTheme { Scaffold(topBar = { TopAppBarCreatePost( rememberNavController(), CreatePostViewModel(), Screen.CreatePostScreen ) }, content = { paddingValues -> Column( Modifier .fillMaxSize() .background(Color.Black) .padding(paddingValues) ) { } }) } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/create_post/CreatePostContentView.kt
1558504743
package com.example.openmind.ui.create_post import androidx.compose.foundation.BorderStroke 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.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.example.openmind.R import com.example.openmind.ui.create_post.viewModel.CreatePostViewModel import com.example.openmind.ui.screen.Screen import com.example.openmind.ui.theme.ButtonBorder import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeSemiBoldW600 import com.example.openmind.ui.theme.NightBlue import com.example.openmind.ui.theme.SteelBlue60 import com.example.openmind.ui.theme.spacing import com.example.openmindproject.ui.theme.OpenMindProjectTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun CreatePostContentView( navController: NavController, viewModel: CreatePostViewModel, modifier: Modifier = Modifier ) { Column( modifier = modifier.padding( start = MaterialTheme.spacing.large, end = 20.dp, top = 20.dp, bottom = 20.dp ) ) { Column { Row { OutlinedButton( onClick = { viewModel.setDropdownVisibility(true) }, shape = RoundedCornerShape(6.dp), contentPadding = PaddingValues(16.dp), modifier = Modifier .weight(1f), colors = ButtonDefaults.outlinedButtonColors( containerColor = Color.White, contentColor = SteelBlue60, ), border = BorderStroke(1.dp, ButtonBorder) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = viewModel.getCategory(), style = TextStyle( color = SteelBlue60, fontSize = 14.sp, lineHeight = 20.sp, fontFamily = FontFamily.ManropeSemiBoldW600 ), textAlign = TextAlign.Start ) Box(Modifier.padding(end = 16.dp)) { Icon( Icons.Default.KeyboardArrowRight, contentDescription = "choose", tint = SteelBlue60, ) } } } DropdownMenu( expanded = viewModel.getDropdownVisibility(), onDismissRequest = { viewModel.setDropdownVisibility(false) }, modifier = Modifier.fillMaxWidth(0.8f) ) { viewModel.getCategoriesList().toList().forEach { category -> DropdownMenuItem( text = { Text(category.getStringValue()) }, onClick = { viewModel.setDropdownVisibility(false) viewModel.setCategory(category) } ) } } Box( modifier = Modifier .padding(start = 10.dp) .align(Alignment.CenterVertically), ) { Icon( painter = painterResource(id = R.drawable.info), contentDescription = "info", modifier = Modifier .size(20.dp), tint = MaibPrimary ) } } Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = viewModel.getTitle(), onValueChange = viewModel.onTitleChange(), colors = TextFieldDefaults.outlinedTextFieldColors( containerColor = Color.White, unfocusedBorderColor = ButtonBorder ), placeholder = { Text( "Title", style = TextStyle( color = SteelBlue60, fontSize = 14.sp, lineHeight = 20.sp, fontFamily = FontFamily.ManropeSemiBoldW600 ) ) }, textStyle = TextStyle( color = NightBlue, fontSize = 14.sp, lineHeight = 20.sp, fontFamily = FontFamily.ManropeSemiBoldW600 ), modifier = Modifier .clip(RoundedCornerShape(6.dp)) .fillMaxWidth() .padding(end = MaterialTheme.spacing.large), keyboardOptions = KeyboardOptions( imeAction = ImeAction.Next, capitalization = KeyboardCapitalization.Sentences ) ) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = viewModel.getDescription(), onValueChange = viewModel.onDescriptionChange(), colors = TextFieldDefaults.outlinedTextFieldColors( containerColor = Color.White, unfocusedBorderColor = ButtonBorder ), placeholder = { Text( "Description", style = TextStyle( color = SteelBlue60, fontSize = 14.sp, lineHeight = 20.sp, fontFamily = FontFamily.ManropeSemiBoldW600 ) ) }, textStyle = TextStyle( color = NightBlue, fontSize = 14.sp, lineHeight = 20.sp, fontFamily = FontFamily.ManropeSemiBoldW600 ), modifier = Modifier .clip(RoundedCornerShape(6.dp)) .defaultMinSize(minHeight = 100.dp) .fillMaxWidth() .padding(end = MaterialTheme.spacing.large), keyboardOptions = KeyboardOptions( imeAction = ImeAction.Done, capitalization = KeyboardCapitalization.Sentences ), keyboardActions = KeyboardActions(onDone = { viewModel.createPost() navController.navigate(Screen.SuccessRegisteredPostScreen.route) }) ) } Spacer(modifier = Modifier.height(40.dp)) Button( shape = RoundedCornerShape(8.dp), onClick = { viewModel.onCreatePostButton() navController.navigate(Screen.SuccessRegisteredPostScreen.route) }, colors = ButtonDefaults.buttonColors( containerColor = MaibPrimary ), modifier = Modifier .align(Alignment.CenterHorizontally) .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .padding(start = 10.dp, end = 20.dp), contentPadding = PaddingValues(vertical = 13.dp) ) { Text( "Create", style = MaterialTheme.typography.titleLarge.merge(color = Color.White) ) } } LaunchedEffect(Unit) { viewModel.fetchCategories() } } @Preview( showBackground = true, backgroundColor = 0xFFF7F8FA ) @Composable fun CreatePostContentPreview() { val navController: NavController = rememberNavController() val viewModel = CreatePostViewModel() OpenMindProjectTheme { CreatePostContentView( navController, viewModel = viewModel, ) } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/navigation/Navigation.kt
1964715239
package com.example.openmind.ui.navigation import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.navigation import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.openmind.enums.PostCategories import com.example.openmind.ui.screen.ComposeScreen import com.example.openmind.ui.screen.Screen @RequiresApi(Build.VERSION_CODES.O) @Composable fun Navigation(navController: NavHostController = rememberNavController()) { NavHost(navController = navController, startDestination = Screen.ProfileScreen.route) { composable(Screen.CategoriesScreen.route) { ComposeScreen(screen = Screen.CategoriesScreen, navController = navController) } composable(Screen.ProfileScreen.route) { ComposeScreen(screen = Screen.ProfileScreen, navController = navController) } navigation( route = Screen.PostListScreen.route, startDestination = "${Screen.PostListScreen.route}/{category}", ) { composable( route = "${Screen.PostListScreen.route}/{category}", arguments = listOf(navArgument("category") { type = NavType.StringType }) ) { backStackEntry -> val category = backStackEntry.arguments?.getString("category") ComposeScreen( screen = Screen.PostListScreen, navController = navController, args = mapOf("category" to (category ?: PostCategories.BUG.getStringValue())) ) } composable( route = "${Screen.CreatePostScreen.route}/{category}", arguments = listOf(navArgument("category") { type = NavType.StringType }) ) { backStackEntry -> val category = backStackEntry.arguments?.getString("category") ComposeScreen( screen = Screen.CreatePostScreen, navController = navController, args = mapOf("category" to (category ?: PostCategories.BUG.getStringValue())) ) } composable( route = "${Screen.PostScreen.route}/{postId}", arguments = listOf(navArgument("postId") { type = NavType.StringType }) ) { backStackEntry -> val postId = backStackEntry.arguments?.getString("postId") ComposeScreen( screen = Screen.PostScreen, navController = navController, args = mapOf("postId" to (postId ?: "")) ) } composable( route = "${Screen.SearchResultsScreen.route}/{category}/{searchQuery}", arguments = listOf( navArgument("category") { type = NavType.StringType }, navArgument("searchQuery") { type = NavType.StringType } ) ) { backStackEntry -> val searchQuery = backStackEntry.arguments?.getString("searchQuery") val category = backStackEntry.arguments?.getString("category") ComposeScreen( screen = Screen.SearchResultsScreen, navController = navController, args = mapOf( "category" to (category ?: (PostCategories.BUG.getStringValue())), "searchQuery" to (searchQuery ?: "") ) ) } } composable(route = Screen.SuccessRegisteredPostScreen.route) { ComposeScreen( screen = Screen.SuccessRegisteredPostScreen, navController = navController ) } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/navigation/NavControllerExtentions.kt
342139727
package com.example.openmind.ui.navigation import androidx.navigation.NavController import com.example.openmind.enums.PostCategories import com.example.openmind.ui.screen.Screen fun NavController.navigateToPost(postId: String) = this.navigate(Screen.PostScreen.route + "/$postId") fun NavController.navigateToPostList(category: PostCategories) = this.navigate(Screen.PostListScreen.route + "/${category}") fun NavController.navigateToCreatePost(category: PostCategories) = this.navigate(Screen.CreatePostScreen.route + "/${category}") fun NavController.navigateToSearchResult(query: String, category: PostCategories) = this.navigate(Screen.SearchResultsScreen.route + "/${category}/${query}")
OpenMind/openmind/src/main/java/com/example/openmind/ui/components/general/RatingView.kt
2371391849
package com.example.openmind.ui.components.general import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape 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.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.example.openmind.R import com.example.openmind.domain.model.rating.RatingInfo import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.DarkBlue40 import com.example.openmind.ui.theme.MaibError import com.example.openmind.ui.theme.MaibPrimary @Composable fun RatingView( rating: RatingInfo, modifier: Modifier = Modifier, isComment: Boolean = false, onRatingChange: (String, Int) -> Unit ) { var mutableRating by remember { rating.rating } var rated by remember {// 0 - not rated, 1 - liked, -1 - disliked rating.isRated } val likeColor = if (rated == 1) MaibPrimary else DarkBlue40 val dislikeColor = if (rated == -1) MaibError else DarkBlue40 val actionColor = if (rated == 1) MaibPrimary else if (rated == -1) MaibError else DarkBlue40 var strokeActionColor = if (rated == 1) MaibPrimary else if (rated == -1) MaibError else BorderLight var strokeColor = BorderLight if (isComment) { strokeColor = Color.Transparent strokeActionColor = Color.Transparent } Row( modifier = modifier .clip(CircleShape) .border(1.dp, strokeActionColor, CircleShape) .padding(0.dp), verticalAlignment = Alignment.CenterVertically ) { IconButton( onClick = { // /*TODO(post rating increases - patch request,button color - maib primary)*/ val newRating = when (rated) { 1 -> mutableRating - 1 -1 -> mutableRating + 2 else -> mutableRating + 1 } mutableRating = newRating rated = if (rated == 1) 0 else 1 onRatingChange(rating.ratingId, 1) }, modifier = Modifier .padding(top = 5.dp, bottom = 5.dp, start = 4.dp, end = 1.dp) .size(20.dp) ) { Icon( painter = painterResource(id = R.drawable.arrow_up), contentDescription = stringResource(R.string.content_description_increase), tint = likeColor ) } Box(Modifier.padding(end = 6.dp)) { Text( text = "$mutableRating", style = MaterialTheme.typography.titleMedium, color = actionColor, maxLines = 1, textAlign = TextAlign.Center, modifier = Modifier .defaultMinSize(minWidth = 42.dp) .borderRight(0.5.dp, strokeColor) ) } IconButton( onClick = { /*TODO(post rating decreases - patch request, button color ~ red)*/ val newRating = when (rated) { -1 -> mutableRating + 1 1 -> mutableRating - 2 else -> mutableRating - 1 } mutableRating = newRating rated = if (rated == -1) 0 else -1 onRatingChange(rating.ratingId, -1) }, modifier = Modifier .padding(top = 5.dp, bottom = 5.dp, start = 1.dp, end = 4.dp) .rotate(180f) .size(20.dp), ) { Icon( painter = painterResource(id = R.drawable.arrow_up), contentDescription = stringResource(R.string.content_description_decrease), tint = dislikeColor ) } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/components/general/CustomModifier.kt
3569367629
package com.example.openmind.ui.components.general import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp fun Modifier.borderBottom(strokeWidth: Dp, color: Color) = composed( factory = { val density = LocalDensity.current val strokeWidthPx = density.run { strokeWidth.toPx() } Modifier.drawBehind { val width = size.width val height = size.height - strokeWidthPx / 2 drawLine( color = color, start = Offset(x = 0f, y = height), end = Offset(x = width, y = height), strokeWidth = strokeWidthPx ) } } ) fun Modifier.borderRight(strokeWidth: Dp, color: Color) = composed( factory = { val density = LocalDensity.current val strokeWidthPx = density.run { strokeWidth.toPx() } Modifier.drawBehind { val width = size.width val height = size.height - strokeWidthPx / 2 drawLine( color = color, start = Offset(x = width, y = 0f), end = Offset(x = width, y = height), strokeWidth = strokeWidthPx ) } } ) fun Modifier.borderTop(strokeWidth: Dp, color: Color) = composed( factory = { val density = LocalDensity.current val strokeWidthPx = density.run { strokeWidth.toPx() } Modifier.drawBehind { val width = size.width drawLine( color = color, start = Offset(x = 0f, y = 0f), end = Offset(x = width, y = 0f), strokeWidth = strokeWidthPx ) } } )
OpenMind/openmind/src/main/java/com/example/openmind/ui/components/general/BasicTopAppBar.kt
4111002188
package com.example.openmind.ui.components.general import android.util.Log import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.expandHorizontally import androidx.compose.animation.shrinkHorizontally import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModel import androidx.navigation.NavController import com.example.openmind.R import com.example.openmind.ui.create_post.components.TAG import com.example.openmind.ui.post_list.viewModel.PostListViewModel import com.example.openmind.ui.screen.Screen import com.example.openmind.ui.theme.IconColor import com.example.openmind.ui.theme.spacing import com.example.openmindproject.ui.theme.NavigationIconStyle @Composable @OptIn( ExperimentalMaterial3Api::class ) fun BasicTopAppBar( viewModel: ViewModel, navController: NavController, currentScreen: Screen<*>, modifier: Modifier = Modifier, titleStyle: TextStyle = MaterialTheme.typography.titleLarge.merge(textAlign = TextAlign.Center), navIconStyle: NavigationIconStyle = NavigationIconStyle.defaultIconStyle() ) { val focusManager = LocalFocusManager.current Box(modifier) { CenterAlignedTopAppBar( title = { Box { Text( text = currentScreen.title, style = titleStyle ) } }, navigationIcon = { Box(modifier = Modifier.padding(start = MaterialTheme.spacing.large)) { IconButton( onClick = { Log.d(TAG, "Clicked Navigate Back") navController.navigateUp() }, modifier = Modifier.size(30.dp) ) { Icon( painterResource(id = R.drawable.navigation_up), contentDescription = "Back to post list", tint = navIconStyle.iconColor, modifier = navIconStyle.modifier ) } } }, actions = { Box(modifier = Modifier.padding(end = MaterialTheme.spacing.large)) { if (viewModel is PostListViewModel) IconButton( onClick = { Log.d(TAG, "Clicked 'Search' Button") }, modifier = Modifier .size(30.dp) ) { Icon( painter = painterResource(id = R.drawable.search_normal), contentDescription = "search", tint = IconColor, modifier = Modifier .size(24.dp) .clickable(onClick = { viewModel.updateSearchBarVisibility(isVisible = !viewModel.isSearchBarVisible()) }) ) } } }, colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = MaterialTheme.colorScheme.background ) ) if (viewModel is PostListViewModel) AnimatedVisibility( visible = viewModel.isSearchBarVisible(), enter = expandHorizontally( expandFrom = Alignment.CenterHorizontally, animationSpec = tween(durationMillis = 300) ), exit = shrinkHorizontally( shrinkTowards = Alignment.CenterHorizontally, animationSpec = tween(durationMillis = 300) ) ) { Box(modifier = Modifier.padding(horizontal = 20.dp, vertical = 10.dp)) { SearchBar(viewModel = viewModel, navController = navController, onSearch = { focusManager.clearFocus() }) } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/components/general/SharePost.kt
3565325175
package com.example.openmind.ui.components.general import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.example.openmind.R import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.spacing @Composable fun SharePost(postId: String, modifier: Modifier = Modifier) { Column( modifier = modifier .clip(CircleShape) .border(1.dp, BorderLight, CircleShape), verticalArrangement = Arrangement.Center ) { IconButton( onClick = { /*TODO("open Share popUp menu")*/ }, modifier = Modifier .padding( vertical = 5.dp, horizontal = MaterialTheme.spacing.small ) .size(20.dp) ) { Icon( painter = painterResource(id = R.drawable.export), contentDescription = "export", tint = MaibPrimary ) } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/components/general/SearchBar.kt
1993186608
package com.example.openmind.ui.components.general import com.example.openmind.enums.Keyboard import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActionScope import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.example.openmind.R import com.example.openmind.enums.PostCategories import com.example.openmind.ui.navigation.navigateToSearchResult import com.example.openmind.ui.post_list.viewModel.PostListViewModel import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.MaibPrimary import keyboardAsState @OptIn(ExperimentalMaterial3Api::class) @Composable fun SearchBar( modifier: Modifier = Modifier, navController: NavController, viewModel: PostListViewModel, onSearch: (KeyboardActionScope.() -> Unit)? = null, onFocusChangeListener: (() -> Unit)? = null ) { val searchText by viewModel.getSearchText().collectAsState() val focusRequester = remember { FocusRequester() } val keyboardState = keyboardAsState() val mutableInteractionSource = remember { MutableInteractionSource() } var previousKeyboardState by remember { mutableStateOf(keyboardState.value) } Row( modifier = modifier .fillMaxWidth() .border(BorderStroke(2.dp, MaibPrimary), RoundedCornerShape(6.dp)) .background(Color.White), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { BasicTextField( value = searchText, onValueChange = { viewModel.onSearchTextChanged(it) }, modifier = Modifier .focusRequester(focusRequester = focusRequester) .onFocusChanged { onFocusChangeListener } .defaultMinSize(minHeight = 44.dp), textStyle = TextStyle( fontSize = 16.sp ), keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, ), keyboardActions = KeyboardActions( onSearch = { onSearch navController.navigateToSearchResult(searchText, viewModel.getPostCategory()) viewModel.resetSearch() viewModel.updateSearchBarVisibility(false) } ), decorationBox = @Composable { innerTextField -> TextFieldDefaults.DecorationBox( value = searchText, innerTextField = innerTextField, placeholder = { Text(text = "Search") }, enabled = true, singleLine = true, visualTransformation = VisualTransformation.None, interactionSource = mutableInteractionSource, shape = RoundedCornerShape(6.dp), colors = TextFieldDefaults.textFieldColors( containerColor = Color.White, unfocusedIndicatorColor = Color.Transparent, ), contentPadding = PaddingValues(top = 10.dp, bottom = 10.dp, start = 20.dp) ) } ) Box( modifier = Modifier .padding(end = 16.dp), ) { Icon( painterResource(id = R.drawable.search_normal), contentDescription = null, modifier = Modifier .size(22.dp) .clickable { if (searchText.isNotBlank()) navController.navigateToSearchResult( searchText, viewModel .getActiveCategory() ?: PostCategories.BUG ) viewModel.resetSearch() viewModel.updateSearchBarVisibility(false) }, tint = BorderLight, ) } } LaunchedEffect(Unit) { focusRequester.requestFocus() } LaunchedEffect(keyboardState.value) { if (previousKeyboardState != keyboardState.value) { when (keyboardState.value) { Keyboard.Closed -> viewModel.updateSearchBarVisibility(false) Keyboard.Opened -> Unit } previousKeyboardState = keyboardState.value } } } @Preview( showBackground = true ) @Composable fun SearchBarPreview() { Column(modifier = Modifier.fillMaxSize()) { SearchBar(Modifier, navController = rememberNavController(), PostListViewModel()) } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/components/general/SortingSelector.kt
1343888014
package com.example.openmind.ui.components.general import NoRippleInteractionSource import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme 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.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.LocalMinimumInteractiveComponentEnforcement 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 import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.ui.theme.LightGray80 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.colorthemes.ColorDarkTokens import com.example.openmind.ui.theme.colorthemes.ColorLightTokens import com.example.openmind.ui.theme.colorthemes.ColorTokens import com.example.openmind.ui.theme.spacing import com.example.openmind.enums.SortType @OptIn(ExperimentalMaterial3Api::class) @Composable fun SortingSelector( setActiveSortType: (SortType) -> Unit, activeSortType: SortType, sortingList: List<SortType>, modifier: Modifier = Modifier, contentPaddings: PaddingValues = PaddingValues( vertical = MaterialTheme.spacing.small, horizontal = 10.dp ) ) { val colorTokens: ColorTokens = when { isSystemInDarkTheme() -> ColorDarkTokens else -> ColorLightTokens } val activeColors = ButtonDefaults.buttonColors( containerColor = colorTokens.RatioActiveBackground, contentColor = colorTokens.RatioActiveContent ) val inactiveColors = ButtonDefaults.buttonColors( containerColor = colorTokens.RatioInactiveBackground, contentColor = colorTokens.RatioInactiveContent ) Box( modifier = modifier .background(LightGray80, shape = RoundedCornerShape(50)) ) { Row( verticalAlignment = Alignment.Top, modifier = Modifier .defaultMinSize(minHeight = 22.dp) ) { sortingList.forEach { item -> Column { CompositionLocalProvider( LocalMinimumInteractiveComponentEnforcement provides false, ) { Button( onClick = { setActiveSortType.invoke(item) }, colors = if (activeSortType == item) activeColors else inactiveColors, modifier = Modifier .defaultMinSize(minWidth = 60.dp, minHeight = 30.dp) .padding(1.dp), interactionSource = NoRippleInteractionSource.INSTANCE, shape = RoundedCornerShape(50), contentPadding = contentPaddings ) { Text( text = item.string, fontFamily = FontFamily.ManropeRegularW400, fontSize = 14.sp, lineHeight = 20.sp, ) } } } } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/components/general/NoRippleInteractionSource.kt
55756423
import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.ui.Modifier import androidx.compose.ui.composed import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow //InteractionSource class Implementation For Buttons class NoRippleInteractionSource private constructor() : MutableInteractionSource { companion object { val INSTANCE: NoRippleInteractionSource by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { NoRippleInteractionSource() } } override val interactions: Flow<Interaction> = emptyFlow() override suspend fun emit(interaction: Interaction) {} override fun tryEmit(interaction: Interaction) = true } // Compose Modifier for clickable fun Modifier.clickableWithoutRipple( interactionSource: MutableInteractionSource, onClick: () -> Unit ) = composed( factory = { this.then( Modifier.clickable( interactionSource = interactionSource, indication = null, onClick = { onClick() } ) ) } )
OpenMind/openmind/src/main/java/com/example/openmind/ui/profile/ProfileScreenViewModel.kt
2826609439
package com.example.openmind.ui.profile import androidx.compose.runtime.MutableState import com.example.openmind.ui.GlobalViewModel class ProfileScreenViewModel : GlobalViewModel() { private val viewState = ProfileScreenViewState() fun getUserName() = "${viewState.profile.firstName} ${viewState.profile.lastName}" fun getUserNickname() = "@${viewState.profile.nickname}" fun getUserPhoneNumber() = "+373 ${viewState.profile.phoneNumber}" fun getUserEmail() = viewState.profile.email fun getNicknameState(): MutableState<String> = viewState.nicknameState fun onNicknameChange(): ((String) -> Unit) { return { inputValue -> viewState.nicknameState.value = inputValue } } fun onRenameEvent(): () -> Unit = { setUserNameTextFieldHidden() viewState.profile.nickname = viewState.nicknameState.value } fun getUserNameTextFieldViewState() = viewState.isEditNickNameFieldVisible.value fun setUserNameTextFieldVisible() { viewState.isEditNickNameFieldVisible.value = true } fun setUserNameTextFieldHidden() { viewState.isEditNickNameFieldVisible.value = false } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/profile/ProfileScreenViewState.kt
987095551
package com.example.openmind.ui.profile import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import com.example.openmind.domain.model.user.ProfileModel class ProfileScreenViewState { val profile = ProfileModel( firstName = "John", lastName = "Doe", nickname = "johndoe", phoneNumber = "675-474-54", email = "MyPersonalEmail@gmail.com" ) val isEditNickNameFieldVisible: MutableState<Boolean> = mutableStateOf(false) val nicknameState: MutableState<String> = mutableStateOf(profile.nickname) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/profile/components/PersonalDataListItem.kt
2160622796
package com.example.openmind.ui.profile.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material.icons.filled.Send import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.R import com.example.openmind.ui.components.general.borderBottom import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.LightThemeBackgroundColor import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.ManropeSemiBoldW600 import com.example.openmind.ui.theme.SteelBlue60 @OptIn(ExperimentalMaterial3Api::class) @Composable fun PersonalDataListItem( painter: Painter, firstTitle: String, subTitle: String, modifier: Modifier = Modifier, imageDescription: String? = null, isNavigationIconVisible: Boolean = false, isEditable: Boolean = false, editableValue: String? = null, onValueChange: ((String) -> Unit)? = null, editableFieldModifier: Modifier = Modifier, onSubmitEvent: (() -> Unit)? = null, shape: Shape? = null ) { Box { Row( modifier = modifier .padding(start = 16.dp) .fillMaxWidth() .borderBottom((0.5).dp, BorderLight), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row(verticalAlignment = Alignment.CenterVertically) { Icon( painter = painter, imageDescription, tint = MaibPrimary, modifier = Modifier.padding(vertical = 18.dp) ) Column(modifier = Modifier.padding(start = 12.dp)) { Text( text = firstTitle, style = TextStyle( fontFamily = FontFamily.ManropeSemiBoldW600, fontSize = 14.sp, lineHeight = 20.sp ) ) Text( text = subTitle, style = TextStyle( fontFamily = FontFamily.ManropeRegularW400, fontSize = 12.sp, lineHeight = 16.sp, color = SteelBlue60 ) ) } } if (isNavigationIconVisible) { Box { Icon( imageVector = Icons.Default.KeyboardArrowRight, contentDescription = stringResource( id = R.string.read_more_label ), tint = SteelBlue60, modifier = Modifier.align(Alignment.CenterEnd) ) } } } if (isEditable) { OutlinedTextField( value = editableValue ?: " ", onValueChange = onValueChange ?: {}, modifier = editableFieldModifier.fillMaxWidth(), shape = shape ?: RoundedCornerShape(0), trailingIcon = { IconButton( onClick = onSubmitEvent ?: {} ) { Icon( Icons.Default.Send, contentDescription = stringResource(id = R.string.create_button), tint = MaibPrimary ) } }, colors = TextFieldDefaults.outlinedTextFieldColors( containerColor = LightThemeBackgroundColor ), ) } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/profile/components/PersonalHistoryListItem.kt
1042904948
package com.example.openmind.ui.profile.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material3.Icon 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.painter.Painter import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.R import com.example.openmind.ui.components.general.borderBottom import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeSemiBoldW600 import com.example.openmind.ui.theme.SteelBlue60 @Composable fun PersonalHistoryListItem( title: String, painter: Painter, imageDescription: String, modifier: Modifier = Modifier, isNavigationIconVisible: Boolean = false ) { Row( modifier = modifier .padding(start = 16.dp) .fillMaxWidth() .borderBottom((0.5).dp, BorderLight), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row(verticalAlignment = Alignment.CenterVertically) { Icon( painter = painter, imageDescription, tint = MaibPrimary, modifier = Modifier.padding(vertical = 18.dp) ) Column(modifier = Modifier.padding(start = 12.dp)) { Text( text = title, style = TextStyle( fontFamily = FontFamily.ManropeSemiBoldW600, fontSize = 14.sp, lineHeight = 20.sp ) ) } } if (isNavigationIconVisible) { Box { Icon( imageVector = Icons.Default.KeyboardArrowRight, contentDescription = stringResource( id = R.string.read_more_label ), tint = SteelBlue60, modifier = Modifier.align(Alignment.CenterEnd) ) } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/profile/ProfileScreenView.kt
3124597699
package com.example.openmind.ui.profile import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.example.openmind.R import com.example.openmind.ui.components.general.BasicTopAppBar import com.example.openmind.ui.profile.components.PersonalDataListItem import com.example.openmind.ui.profile.components.PersonalHistoryListItem import com.example.openmind.ui.screen.Screen import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.DarkBlue40 import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeSemiBoldW600 import com.example.openmind.ui.theme.spacing @Composable fun ProfileScreenView( viewModel: ProfileScreenViewModel, navController: NavController, modifier: Modifier ) { Column( modifier = modifier .fillMaxSize() .padding(bottom = MaterialTheme.spacing.extraLarge), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Box { Box( modifier = Modifier .clip(RoundedCornerShape(50)) .padding(MaterialTheme.spacing.small) ) { Image( painterResource(id = R.drawable.user_image), contentDescription = stringResource(R.string.user_profile_image), modifier = Modifier.size(128.dp), contentScale = ContentScale.Fit ) } Box( modifier = Modifier .clip(RoundedCornerShape(50)) .border( BorderStroke(2.dp, Color.White), shape = RoundedCornerShape(50) ) .background(Color(0xFFD9F3EE)) .size(32.dp) .align(Alignment.BottomEnd) ) { Icon( painterResource(R.drawable.edit_icon), stringResource(R.string.edit_image), tint = MaibPrimary, modifier = Modifier .align(Alignment.Center) .size(16.dp) ) } } Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = MaterialTheme.spacing.medium, vertical = 20.dp) ) { Text( text = stringResource(R.string.personal_data), style = TextStyle( fontFamily = FontFamily.ManropeSemiBoldW600, fontSize = 14.sp, lineHeight = 20.sp, color = DarkBlue40 ), modifier = Modifier.padding(bottom = 8.dp) ) Column( modifier = Modifier .clip( RoundedCornerShape(8.dp) ) .border(BorderStroke(1.dp, BorderLight), shape = RoundedCornerShape(8.dp)) .background(Color.White) .fillMaxWidth(), ) { PersonalDataListItem( firstTitle = viewModel.getUserName(), subTitle = viewModel.getUserNickname(), painter = painterResource(id = R.drawable.user_pic), imageDescription = stringResource( id = R.string.user_picture ), isNavigationIconVisible = true, isEditable = viewModel.getUserNameTextFieldViewState(), editableValue = viewModel.getNicknameState().value, onValueChange = viewModel.onNicknameChange(), onSubmitEvent = viewModel.onRenameEvent(), modifier = Modifier.clickable(onClick = { viewModel.setUserNameTextFieldVisible() }), shape = RoundedCornerShape( topStart = MaterialTheme.spacing.small, topEnd = MaterialTheme.spacing.small ) ) PersonalDataListItem( painter = painterResource(id = R.drawable.mobile_icon), firstTitle = viewModel.getUserPhoneNumber(), subTitle = stringResource(R.string.phone_number), ) PersonalDataListItem( painter = painterResource(id = R.drawable.mail_icon), firstTitle = viewModel.getUserEmail(), subTitle = stringResource( R.string.e_mail ) ) } } Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = MaterialTheme.spacing.medium, vertical = 20.dp) ) { Text( text = stringResource(R.string.history), style = TextStyle( fontFamily = FontFamily.ManropeSemiBoldW600, fontSize = 14.sp, lineHeight = 20.sp, color = DarkBlue40 ), modifier = Modifier.padding(bottom = MaterialTheme.spacing.small) ) Column( modifier = Modifier .clip( RoundedCornerShape(8.dp) ) .border(BorderStroke(1.dp, BorderLight), shape = RoundedCornerShape(8.dp)) .background(Color.White) .fillMaxWidth(), ) { PersonalHistoryListItem( title = "Categories", painter = painterResource(id = R.drawable.medal_icon), imageDescription = stringResource( id = R.string.user_picture ), isNavigationIconVisible = true, modifier = Modifier.clickable(onClick = { navController.navigate(Screen.CategoriesScreen.route) }) ) PersonalHistoryListItem( title = stringResource(R.string.liked_posts), painter = painterResource(id = R.drawable.like_image), imageDescription = stringResource( id = R.string.user_picture ), ) PersonalHistoryListItem( title = stringResource(R.string.your_comments), painter = painterResource(id = R.drawable.comment_icon), imageDescription = stringResource( id = R.string.user_picture ), ) } } } } @OptIn(ExperimentalMaterial3Api::class) @Preview @Composable fun ProfileScreenPreview() { val viewModel = ProfileScreenViewModel() val navController = rememberNavController() Scaffold(topBar = { BasicTopAppBar( viewModel = viewModel, navController = navController, currentScreen = Screen.ProfileScreen ) }) { paddingValues -> ProfileScreenView( viewModel = viewModel, navController = navController, modifier = Modifier.padding(paddingValues) ) } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/theme/colorthemes/ColorDarkTokens.kt
2673769143
package com.example.openmind.ui.theme.colorthemes import androidx.compose.ui.graphics.Color import com.example.openmind.ui.theme.Pink40 import com.example.openmind.ui.theme.PurpleGrey40 object ColorDarkTokens : ColorTokens { override val Background: Color = PurpleGrey40 override val RatioInactiveBackground: Color = Pink40 override val RatioActiveBackground: Color = PurpleGrey40 override val RatioActiveContent: Color = Color.White override val RatioInactiveContent: Color = Color.White override val CategoryTitle: Color get() = TODO("Not yet implemented") override val CategoryTime: Color get() = TODO("Not yet implemented") }
OpenMind/openmind/src/main/java/com/example/openmind/ui/theme/colorthemes/ColorLightTokens.kt
3002594773
package com.example.openmind.ui.theme.colorthemes import androidx.compose.ui.graphics.Color import com.example.openmind.ui.theme.DarkBlue40 import com.example.openmind.ui.theme.DarkGray20 import com.example.openmind.ui.theme.LightGray80 import com.example.openmind.ui.theme.SteelBlue60 object ColorLightTokens : ColorTokens { override val Background = Color.White override val RatioInactiveBackground = LightGray80 override val RatioActiveBackground = Color.White override val RatioActiveContent = DarkBlue40 override val RatioInactiveContent = SteelBlue60 override val CategoryTitle = DarkGray20 override val CategoryTime = SteelBlue60 // val Error = PaletteTokens.Error40 // val ErrorContainer = PaletteTokens.Error90 // val InverseOnSurface = PaletteTokens.Neutral95 // val InversePrimary = PaletteTokens.Primary80 // val InverseSurface = PaletteTokens.Neutral20 // val OnBackground = PaletteTokens.Neutral10 // val OnError = PaletteTokens.Error100 // val OnErrorContainer = PaletteTokens.Error10 // val OnPrimary = PaletteTokens.Primary100 // val OnPrimaryContainer = PaletteTokens.Primary10 // val OnSecondary = PaletteTokens.Secondary100 // val OnSecondaryContainer = PaletteTokens.Secondary10 // val OnSurface = PaletteTokens.Neutral10 // val OnSurfaceVariant = PaletteTokens.NeutralVariant30 // val OnTertiary = PaletteTokens.Tertiary100 // val OnTertiaryContainer = PaletteTokens.Tertiary10 // val Outline = PaletteTokens.NeutralVariant50 // val OutlineVariant = PaletteTokens.NeutralVariant80 // val Primary = PaletteTokens.Primary40 // val PrimaryContainer = PaletteTokens.Primary90 // val Scrim = PaletteTokens.Neutral0 // val Secondary = PaletteTokens.Secondary40 // val SecondaryContainer = PaletteTokens.Secondary90 // val Surface = PaletteTokens.Neutral99 // val SurfaceTint = Primary // val SurfaceVariant = PaletteTokens.NeutralVariant90 // val Tertiary = PaletteTokens.Tertiary40 // val TertiaryContainer = PaletteTokens.Tertiary90 }
OpenMind/openmind/src/main/java/com/example/openmind/ui/theme/colorthemes/ColorTokens.kt
4085846798
package com.example.openmind.ui.theme.colorthemes import androidx.compose.ui.graphics.Color interface ColorTokens { val Background: Color val RatioInactiveBackground: Color val RatioActiveBackground: Color val RatioActiveContent: Color val RatioInactiveContent: Color val CategoryTitle: Color val CategoryTime: Color }
OpenMind/openmind/src/main/java/com/example/openmind/ui/theme/Color.kt
36887803
package com.example.openmind.ui.theme import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color val IconColor = Color(0xFFC3C7DB) val DarkBlue40 = Color(0xFF293946) val LightGray80 = Color(0xFFEEF1F4) val LightThemeBackgroundColor = Color(0xFFF7F8FA) val LightText = Color(0xFFFFFFFF) val SteelBlue60 = Color(0xFF696F8C) val ButtonBorder = Color(0xFFEDEFF5) val SteelGray = Color(0xFFB8B9BD) val DarkGray20 = Color(0xFF28292D) val Delimiter = Color(0xFFD8DAE5) val MaibPrimary = Color(0xFF40C1AC) val MaibError = Color(0xFFF57D7D) val BorderLight = Color(0xFFDEDFE5) val NightBlue = Color(0xFF253746) val LightGreenGradientStartColor = Color(0xFF02BAAF) val LightGreenGradientEndColor = Color(0xFF03D898) val OrangeGradientStartColor = Color(0xFFF2862E) val OrangeGradientEndColor = Color(0xFFFAB038) val LightGreenGradient = Brush.verticalGradient(listOf(LightGreenGradientStartColor, LightGreenGradientEndColor)) val OrangeGradient = Brush.horizontalGradient(listOf(OrangeGradientStartColor, OrangeGradientEndColor)) val Pink80 = Color(0xFFEFB8C8) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
OpenMind/openmind/src/main/java/com/example/openmind/ui/theme/Theme.kt
284120274
package com.example.openmindproject.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.size 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.CompositionLocalProvider 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.LocalContext import androidx.compose.ui.platform.LocalView import androidx.compose.ui.unit.dp import androidx.core.view.WindowCompat import com.example.openmind.ui.theme.DarkBlue40 import com.example.openmind.ui.theme.IconColor import com.example.openmind.ui.theme.LightThemeBackgroundColor import com.example.openmind.ui.theme.LocalSpacing import com.example.openmind.ui.theme.Pink80 import com.example.openmind.ui.theme.Spacing import com.example.openmind.ui.theme.SteelBlue60 import com.example.openmind.ui.theme.Typography private val DarkColorScheme = darkColorScheme( primary = Color.White, secondary = DarkBlue40, tertiary = Pink80, background = Color.Black, ) open class NavigationIconStyle( var iconColor: Color = IconColor, var modifier: Modifier = Modifier.size(24.dp) ) { companion object { fun defaultIconStyle() = NavigationIconStyle( iconColor = IconColor, modifier = Modifier.size(24.dp) ) } } private val LightColorScheme = lightColorScheme( primary = DarkBlue40, secondary = SteelBlue60, tertiary = DarkBlue40, background = LightThemeBackgroundColor // onPrimary: Color = ColorLightTokens.OnPrimary, //primaryContainer: Color = ColorLightTokens.PrimaryContainer, //onPrimaryContainer: Color = ColorLightTokens.OnPrimaryContainer, //inversePrimary: Color = ColorLightTokens.InversePrimary, //secondary: Color = ColorLightTokens.Secondary, //onSecondary: Color = ColorLightTokens.OnSecondary, //secondaryContainer: Color = ColorLightTokens.SecondaryContainer, //onSecondaryContainer: Color = ColorLightTokens.OnSecondaryContainer, //tertiary: Color = ColorLightTokens.Tertiary, //onTertiary: Color = ColorLightTokens.OnTertiary, //tertiaryContainer: Color = ColorLightTokens.TertiaryContainer, //onTertiaryContainer: Color = ColorLightTokens.OnTertiaryContainer, //background: Color = ColorLightTokens.Background, //onBackground: Color = ColorLightTokens.OnBackground, //surface: Color = ColorLightTokens.Surface, //onSurface: Color = ColorLightTokens.OnSurface, //surfaceVariant: Color = ColorLightTokens.SurfaceVariant, //onSurfaceVariant: Color = ColorLightTokens.OnSurfaceVariant, //surfaceTint: Color = primary, //inverseSurface: Color = ColorLightTokens.InverseSurface, //inverseOnSurface: Color = ColorLightTokens.InverseOnSurface, //error: Color = ColorLightTokens.Error, //onError: Color = ColorLightTokens.OnError, //errorContainer: Color = ColorLightTokens.ErrorContainer, //onErrorContainer: Color = ColorLightTokens.OnErrorContainer, //outline: Color = ColorLightTokens.Outline, //outlineVariant: Color = ColorLightTokens.OutlineVariant, //scrim: Color = ColorLightTokens.Scrim, ) @Composable fun OpenMindProjectTheme( darkTheme: Boolean = isSystemInDarkTheme(), 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 } } CompositionLocalProvider(LocalSpacing.provides(Spacing())) { MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/theme/Spacing.kt
907754773
package com.example.openmind.ui.theme import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp data class Spacing( val default: Dp = 0.dp, val extraSmall: Dp = 4.dp, val small: Dp = 8.dp, val medium: Dp = 16.dp, val large: Dp = 32.dp, val extraLarge: Dp = 40.dp, ) val LocalSpacing = compositionLocalOf { Spacing() } val MaterialTheme.spacing: Spacing @Composable @ReadOnlyComposable get() = LocalSpacing.current
OpenMind/openmind/src/main/java/com/example/openmind/ui/theme/Type.kt
1459154382
package com.example.openmind.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.example.openmind.R val FontFamily.Companion.ManropeRegularW400: FontFamily get() { return FontFamily(Font(R.font.manrope_regular)) } val FontFamily.Companion.ManropeSemiBoldW600: FontFamily get() { return FontFamily(Font(R.font.manrope_semibold)) } val FontFamily.Companion.ManropeExtraBoldW800: FontFamily get() { return FontFamily(Font(R.font.manrope_extrabold)) } val FontFamily.Companion.ManropeBoldW700: FontFamily get() { return FontFamily(Font(R.font.manrope_bold700)) } // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.ManropeBoldW700, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, ), // /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.ManropeExtraBoldW800, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.sp ), titleMedium = TextStyle( fontFamily = FontFamily.ManropeBoldW700, fontWeight = FontWeight.W700, fontSize = 14.sp, lineHeight = 20.sp, ), titleSmall = TextStyle( fontFamily = FontFamily.ManropeSemiBoldW600, fontWeight = FontWeight.W600, fontSize = 12.sp, lineHeight = 16.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) // */ )
OpenMind/openmind/src/main/java/com/example/openmind/ui/screen/Screen.kt
2237016930
package com.example.openmind.ui.screen import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.lifecycle.ViewModel import androidx.navigation.NavController import com.example.openmind.enums.PostCategories import com.example.openmind.ui.categories.CategoriesView import com.example.openmind.ui.categories.components.CategoriesAppBar import com.example.openmind.ui.categories.viewModel.CategoriesViewModel import com.example.openmind.ui.components.general.BasicTopAppBar import com.example.openmind.ui.create_post.CreatePostContentView import com.example.openmind.ui.create_post.components.TopAppBarCreatePost import com.example.openmind.ui.create_post.viewModel.CreatePostViewModel import com.example.openmind.ui.post.PostContentView import com.example.openmind.ui.post.viewmodel.PostViewModel import com.example.openmind.ui.post_list.PostListContentView import com.example.openmind.ui.post_list.viewModel.PostListViewModel import com.example.openmind.ui.profile.ProfileScreenView import com.example.openmind.ui.profile.ProfileScreenViewModel import com.example.openmind.ui.search_result.SearchResultContentView import com.example.openmind.ui.search_result.viewModel.SearchResultViewModel import com.example.openmind.ui.success_post_register.SuccessRegisteredPostViewModel import com.example.openmind.ui.success_post_register.SuccessRegistrationPostView sealed class Screen<T : ViewModel>( val route: String = "", var title: String = "", val topAppBar: @Composable (T, NavController) -> Unit, val content: @Composable (T, NavController, Map<String, String>, Modifier) -> Unit, //Map for args val viewModelClass: Class<T> ) { object CategoriesScreen : Screen<CategoriesViewModel>( route = "categories_screen", title = "Categories", viewModelClass = CategoriesViewModel::class.java, topAppBar = { viewModel, navController -> CategoriesAppBar( viewModel = viewModel, navController = navController, screen = CategoriesScreen ) }, content = { viewModel, navController, _, modifier -> CategoriesView( viewModel = viewModel, navController = navController, modifier = modifier ) } ) object PostListScreen : Screen<PostListViewModel>( route = "post_list_screen", title = "Posts", viewModelClass = PostListViewModel::class.java, topAppBar = { viewModel, navController -> BasicTopAppBar( viewModel = viewModel, navController = navController, currentScreen = PostListScreen, ) }, content = { viewModel, navController, args, modifier -> val category = args["category"] viewModel.setCategory( PostCategories.valueOf(category.orEmpty().uppercase()) ) Log.d( "PostListScreen", "Category set to $category" ) viewModel.setActiveCategoryInfo() PostListContentView( navController = navController, viewModel = viewModel, modifier = modifier ) } ) @RequiresApi(Build.VERSION_CODES.O) object PostScreen : Screen<PostViewModel>(route = "post_screen", title = "Post", viewModelClass = PostViewModel::class.java, topAppBar = { viewModel, navController -> BasicTopAppBar( viewModel = viewModel, navController = navController, currentScreen = PostScreen ) }, content = { viewModel, _, args, modifier -> val postId = args["postId"] Log.d( "Screen", "postId set to $postId" ) viewModel.setCurrentPostID(postId = postId.orEmpty()) PostContentView( viewModel = viewModel, modifier = modifier ) } ) object CreatePostScreen : Screen<CreatePostViewModel>( route = "create_post_screen", title = "Create Post", viewModelClass = CreatePostViewModel::class.java, topAppBar = { viewModel, navController -> TopAppBarCreatePost( navController = navController, viewModel = viewModel, CreatePostScreen ) }, content = { viewModel, navController, args, modifier -> val category = args["category"] viewModel.setCategory(category?.let { PostCategories.valueOf(it.uppercase()) } ?: PostCategories.BUG) Log.d( "CreatePostScreen", "Category set to $category" ) CreatePostContentView( navController = navController, viewModel = viewModel, modifier = modifier ) } ) object SearchResultsScreen : Screen<SearchResultViewModel>( route = "search_result_screen", title = "Results", viewModelClass = SearchResultViewModel::class.java, topAppBar = { viewModel, navController -> BasicTopAppBar( viewModel = viewModel, navController = navController, currentScreen = SearchResultsScreen ) }, content = { viewModel, navController, args, modifier -> val query = args["searchQuery"] val category = args["category"] viewModel.searchWithQuery(query.orEmpty(), category.orEmpty()) SearchResultContentView( navController = navController, viewModel = viewModel, modifier = modifier, ) } ) object SuccessRegisteredPostScreen : Screen<SuccessRegisteredPostViewModel>( route = "registered_post_screen", title = "registered_post", viewModelClass = SuccessRegisteredPostViewModel::class.java, topAppBar = { _, _ -> }, content = { _, navController, _, _ -> SuccessRegistrationPostView( navController ) } ) object ProfileScreen : Screen<ProfileScreenViewModel>( route = "profile_screen", title = "Profile", viewModelClass = ProfileScreenViewModel::class.java, topAppBar = { viewModel, navController -> BasicTopAppBar( viewModel = viewModel, navController = navController, currentScreen = PostListScreen, ) }, content = { viewModel, navController, _, modifier -> ProfileScreenView(viewModel = viewModel, navController = navController, modifier = modifier) } ) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/screen/ComposeScreen.kt
1029354816
package com.example.openmind.ui.screen import NoRippleInteractionSource import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row 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.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import clickableWithoutRipple import com.example.openmind.ui.components.general.borderBottom import com.example.openmind.ui.navigation.navigateToPost import com.example.openmind.ui.post_list.viewModel.PostListViewModel import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.ManropeRegularW400 @Composable fun <V : ViewModel> ComposeScreen( screen: Screen<V>, navController: NavController, args: Map<String, String> = emptyMap() ) { val viewModel = viewModel(screen.viewModelClass) Scaffold(modifier = Modifier.fillMaxSize(), topBar = { screen.topAppBar(viewModel, navController) }, content = { paddingValues -> screen.content( viewModel, navController, args, Modifier.padding(paddingValues) ) if (viewModel is PostListViewModel) { AnimatedVisibility(visible = viewModel.isSearchBarVisible()) { Box( modifier = Modifier .fillMaxSize() .background(Color.Black.copy(alpha = 0.5f)) .padding(paddingValues) .clickableWithoutRipple(interactionSource = NoRippleInteractionSource.INSTANCE, onClick = { viewModel.updateSearchBarVisibility(false) viewModel.resetSearch() }) ) { val searchResults by viewModel.getSearchResults().collectAsState() LazyColumn(content = { items(items = searchResults) { item -> Row( modifier = Modifier .fillMaxWidth() .background(color = Color.White) .borderBottom(1.dp, BorderLight) .defaultMinSize(minHeight = 60.dp) .clickable( onClick = { navController.navigateToPost(item.postId) viewModel.resetSearch() viewModel.updateSearchBarVisibility(false) } ), verticalAlignment = Alignment.CenterVertically ) { Text( text = item.postTitle!!, maxLines = 2, fontFamily = FontFamily.ManropeRegularW400, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding( vertical = 10.dp, horizontal = 20.dp ) ) } } }) } } } } ) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post_list/viewModel/PostListViewModel.kt
2480366603
package com.example.openmind.ui.post_list.viewModel import androidx.lifecycle.viewModelScope import com.example.openmind.data.repository.PostRepository import com.example.openmind.di.repository.PostRepositoryProvider import com.example.openmind.domain.model.category.CategoryInfo import com.example.openmind.enums.PostCategories import com.example.openmind.domain.model.post.ShortPostDto import com.example.openmind.ui.GlobalViewModel import com.example.openmind.ui.categories.components.getCategoriesInfoList import com.example.openmind.utils.Searchable import com.example.openmind.enums.SortType import com.example.openmind.utils.Sortable import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch open class PostListViewModel : GlobalViewModel(), Sortable, Searchable { private val viewState: PostListViewState = PostListViewState() val repository: PostRepository = PostRepositoryProvider.provideRepository() override fun getSortingList(): List<SortType> = viewState.getSortingList() override fun setActiveSortType(sortType: SortType) = viewState.setActiveSortType(sortType) override fun activeSortType(): SortType = viewState.getActiveSortType() fun getActiveCategory() = viewState.activeCategory fun getPostList() = viewState.loadedPosts fun postsIsLoading() = viewState.isLoading.value fun getSearchResults() = viewState.searchResults fun getSearchText() = viewState.searchText fun fetchPostList() { viewModelScope.launch { viewState.isLoading.value = true viewState.loadedPosts.clear() repository.fetchAllSuspend( category = viewState.activeCategory, sortType = viewState.activeSortType.value ) .catch { cause: Throwable -> handleError(cause) } .collect { viewState.loadedPosts.addAll(it) viewState.isLoading.value = false } } } init { viewState._searchText .debounce(500L) .distinctUntilChanged() .filter { it.isNotEmpty() } .onEach { query -> searchPost(query) } .launchIn(viewModelScope) } fun resetSearch() { viewState._searchText.value = "" } fun onSearchTextChanged(text: String) { viewState._searchText.value = text } override fun searchPost(query: String) { if (query.isBlank()) viewState._searchResults.value = emptyList() val lowercaseQuery = query.lowercase() val subStrings = lowercaseQuery.split(" ") val found = mutableListOf<ShortPostDto>() subStrings.any { splitedSubString -> found.addAll(viewState.loadedPosts.filter { post -> post.postTitle!!.lowercase().contains(splitedSubString) }) } viewState._searchResults.value = found.toList() } override fun onSearch() { TODO("Not yet implemented") } override fun updateSearchBarVisibility(isVisible: Boolean) { viewState.isSearchBarVisible.value = isVisible } override fun isSearchBarVisible(): Boolean = viewState.isSearchBarVisible.value fun setCategory(postCategories: PostCategories) { viewState.activeCategory = postCategories } fun setActiveCategoryInfo() { viewState.activeCategoryInfo = getCategoriesInfoList().first { it.categoryType == viewState.activeCategory } } fun getActiveCategoryInfo(): CategoryInfo = viewState.activeCategoryInfo fun getCategoryInitials(): String { val words = viewState.activeCategoryInfo.categoryTitle.trim().split(" ") val initials = words.map { it.first().uppercase() } return initials.joinToString("") } fun getPostCount(): String { return "${viewState.getPostsCount()} posts" } fun getPostCategory(): PostCategories = viewState.activeCategory ?: PostCategories.BUG }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post_list/viewModel/PostListViewState.kt
2496181305
package com.example.openmind.ui.post_list.viewModel import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import com.example.openmind.domain.model.category.CategoryInfo import com.example.openmind.enums.PostCategories import com.example.openmind.domain.model.post.ShortPostDto import com.example.openmind.enums.SortType import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow class PostListViewState { val isLoading = mutableStateOf(true) lateinit var activeCategoryInfo: CategoryInfo val activeSortType = mutableStateOf(SortType.HOT) private val sortingList: List<SortType> = listOf( SortType.HOT, SortType.OLD, SortType.FRESH ) private var _activeCategory: PostCategories? = null var activeCategory: PostCategories? get() = _activeCategory set(value) { _activeCategory = value } var loadedPosts = mutableStateListOf<ShortPostDto>() val isSearchBarVisible = mutableStateOf(false) val _searchText = MutableStateFlow("") val searchText = _searchText.asStateFlow() var _searchResults = MutableStateFlow<List<ShortPostDto>>(emptyList()) val searchResults = _searchResults.asStateFlow() fun getSortingList() = sortingList fun setActiveSortType(sortType: SortType) { activeSortType.value = sortType when (activeSortType.value) { SortType.HOT -> loadedPosts.sortWith(compareByDescending { it.postRating }) SortType.OLD -> loadedPosts.sortWith(compareBy { it.creationDate }) SortType.FRESH -> loadedPosts.sortWith(compareByDescending { it.creationDate }) else -> loadedPosts.sortWith(compareBy { it.postTitle }) } } fun getActiveSortType(): SortType = activeSortType.value fun getPostsCount(): Int = loadedPosts?.filter { it.category == activeCategory?.getStringValue()?.uppercase() }?.size ?: 0 }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post_list/PostListContentView.kt
3827288884
package com.example.openmind.ui.post_list import androidx.compose.foundation.ExperimentalFoundationApi 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.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.example.openmind.enums.PostCategories import com.example.openmind.ui.components.general.SortingSelector import com.example.openmind.ui.navigation.navigateToCreatePost import com.example.openmind.ui.navigation.navigateToPost import com.example.openmind.ui.post_list.components.PostShortView import com.example.openmind.ui.post_list.viewModel.PostListViewModel import com.example.openmind.ui.theme.LightText import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.ManropeSemiBoldW600 import com.example.openmind.ui.theme.NightBlue import com.example.openmind.ui.theme.SteelGray import com.example.openmind.ui.theme.spacing @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class) @Composable fun PostListContentView( navController: NavController, viewModel: PostListViewModel, modifier: Modifier = Modifier ) { val state = rememberPullToRefreshState() if (state.isRefreshing) { LaunchedEffect(true) { // fetch something viewModel.fetchPostList() state.endRefresh() } } Box( modifier = modifier .fillMaxSize() .nestedScroll(state.nestedScrollConnection), ) { LazyColumn() { item { Column { Row( modifier = Modifier.padding( end = MaterialTheme.spacing.large, start = MaterialTheme.spacing.large, bottom = 10.dp ) ) { Box(modifier = Modifier.padding(end = 13.dp)) { Box( modifier = Modifier .size(30.dp) .clip(RoundedCornerShape(50)) .background(viewModel.getActiveCategoryInfo().backgroundStyle), contentAlignment = Alignment.Center ) { Text( text = viewModel.getCategoryInitials(), fontFamily = FontFamily.ManropeSemiBoldW600, fontSize = 16.sp, lineHeight = 24.sp, textAlign = TextAlign.Center, color = LightText ) } } Column { Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth() ) { Text( text = viewModel.getActiveCategoryInfo().categoryTitle, style = MaterialTheme.typography.titleLarge, color = Color.Black ) } Column { Text( text = viewModel.getPostCount(), fontFamily = FontFamily.ManropeRegularW400, fontSize = 11.sp, lineHeight = 14.sp, color = SteelGray, modifier = Modifier.padding(bottom = 10.dp) ) Text( text = viewModel.getActiveCategoryInfo().categoryDescription.orEmpty(), fontFamily = FontFamily.ManropeRegularW400, fontSize = 12.sp, lineHeight = 16.sp, color = NightBlue, ) } } } Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = MaterialTheme.spacing.large), horizontalArrangement = Arrangement.SpaceBetween ) { SortingSelector( sortingList = viewModel.getSortingList(), activeSortType = viewModel.activeSortType(), setActiveSortType = { sortType -> viewModel.setActiveSortType(sortType) }, modifier = Modifier.padding(top = 10.dp, bottom = 10.dp), contentPaddings = PaddingValues( vertical = MaterialTheme.spacing.small, horizontal = 10.dp ) ) // Button( // onClick = { // }, // colors = ButtonDefaults.buttonColors( // containerColor = LightGray80, // contentColor = SteelBlue60 // ), // contentPadding = PaddingValues(vertical = 5.dp, horizontal = 15.dp), // shape = RoundedCornerShape(50), // modifier = Modifier // .defaultMinSize(minHeight = 1.dp) // .padding(top = 7.dp, bottom = 10.dp, start = 18.dp) // .align(Alignment.Top) // ) { // Row() { // Text( // text = "A to Z", // fontFamily = FontFamily.ManropeRegularW400, // fontSize = 14.sp, // color = SteelBlue60, // modifier = Modifier.padding(horizontal = 24.dp), // ) // Box( // contentAlignment = Alignment.Center // ) { // Icon( // Icons.Default.KeyboardArrowDown, // contentDescription = "sorting direction", // tint = SteelBlue60, // // modifier = Modifier // .size(20.dp) // ) // } // } // } } } } if (viewModel.postsIsLoading()) { item { Box( modifier = modifier .fillMaxSize(), contentAlignment = Alignment.Center ) { CircularProgressIndicator(modifier = Modifier.size(40.dp)) } } } else { if (!state.isRefreshing) { items(items = viewModel.getPostList(), key = { it.hashCode() }, itemContent = { item -> PostShortView( post = item, modifier = Modifier.animateItemPlacement(), onRatingChange = viewModel.onRatingChange(), navigateToPost = { navController.navigateToPost(postId = item.postId) } ) } ) } } } Box( modifier = Modifier .padding(end = 16.dp, bottom = 16.dp) .align(Alignment.BottomEnd) ) { Box( modifier = Modifier .shadow( elevation = 8.dp, shape = RoundedCornerShape(50), clip = true, ambientColor = Color(0x3D222222), ) .clip(RoundedCornerShape(50)) .clickable { navController.navigateToCreatePost(viewModel.getPostCategory()) } .background(Color(0xFF66CDBD)) .size(60.dp) .padding(12.dp), ) { Icon( Icons.Default.Add, contentDescription = "create", tint = Color.White, modifier = Modifier.size(36.dp) ) } } } LaunchedEffect(Unit) { viewModel.fetchPostList() } } @Preview @Composable fun PostListPreview() { val navController = NavController(LocalContext.current) val viewModel = PostListViewModel() viewModel.setCategory(PostCategories.BUG) viewModel.setActiveCategoryInfo() PostListContentView( navController = navController, viewModel = viewModel(), ) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/post_list/components/PostShortView.kt
1470090656
package com.example.openmind.ui.post_list.components import NoRippleInteractionSource import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert 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.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.draw.rotate import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.R import com.example.openmind.domain.model.post.ShortPostDto import com.example.openmind.domain.model.rating.RatingInfo import com.example.openmind.ui.components.general.RatingView import com.example.openmind.ui.components.general.borderBottom import com.example.openmind.ui.theme.BorderLight import com.example.openmind.ui.theme.DarkBlue40 import com.example.openmind.ui.theme.Delimiter import com.example.openmind.ui.theme.MaibPrimary import com.example.openmind.ui.theme.ManropeBoldW700 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.ManropeSemiBoldW600 import com.example.openmind.ui.theme.SteelBlue60 import com.example.openmind.ui.theme.spacing import com.example.openmind.utils.numberFormatted import com.example.openmind.ui.components.general.SharePost const val tag = "PostShortView" @Composable fun PostShortView( post: ShortPostDto, modifier: Modifier = Modifier, onRatingChange: (String, Int) -> Unit, navigateToPost: () -> Unit ) { val ratingInfo = remember { RatingInfo( ratingId = post.ratingId, rating = mutableIntStateOf(post.postRating ?: 0), isRated = mutableIntStateOf(post.isRated) ) } Row( modifier .fillMaxWidth() .padding(vertical = MaterialTheme.spacing.small) .clickable(onClick = { navigateToPost.invoke() }) ) { Column( modifier = Modifier .padding(horizontal = MaterialTheme.spacing.large) .borderBottom(1.dp, Delimiter) ) { Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { Row(verticalAlignment = Alignment.CenterVertically) { //UserIcon Image( painter = painterResource(R.drawable.user_pic), contentDescription = "user_icon", modifier = Modifier .size(24.dp) .padding(start = 0.dp, end = MaterialTheme.spacing.small, top = 6.dp) ) //Category name Text( text = post.creatorName ?: "johndoe", fontSize = 14.sp, lineHeight = 20.sp, maxLines = 1, fontFamily = FontFamily.ManropeSemiBoldW600, ) //Created Time Text( text = post.formatElapsedTime(), fontSize = 14.sp, lineHeight = 20.sp, maxLines = 1, fontFamily = FontFamily.ManropeRegularW400, modifier = Modifier.padding(start = 20.dp), color = SteelBlue60 ) } // more button (three dots) IconButton( onClick = { Log.d(tag, "Open Hamburger menu") }, modifier = Modifier .size(24.dp) .padding(end = 10.dp), interactionSource = NoRippleInteractionSource.INSTANCE ) { Icon( Icons.Default.MoreVert, contentDescription = stringResource(id = R.string.content_description_more), modifier = Modifier .size(24.dp) .rotate(90f) ) } } // Post Content Column( modifier = Modifier .padding(top = MaterialTheme.spacing.small), ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { //Post Title Text( text = post.postTitle!!.trimIndent(), fontSize = 14.sp, fontFamily = FontFamily.ManropeBoldW700, color = DarkBlue40, maxLines = 3, overflow = TextOverflow.Ellipsis, ) } } // FeedBack and Share Column { Row( modifier = Modifier .padding(vertical = 12.dp) .fillMaxWidth(), ) { //Rating RatingView(rating = ratingInfo, Modifier, onRatingChange = onRatingChange) //Comments Column( modifier = Modifier .padding(horizontal = 10.dp) ) { Row( modifier = Modifier .clip(CircleShape) .border(1.dp, BorderLight, CircleShape) .padding(end = 20.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( painter = painterResource(id = R.drawable.message), contentDescription = stringResource(id = R.string.content_description_decrease), modifier = Modifier .padding( start = 10.dp, top = 5.dp, bottom = 5.dp, end = 6.dp ) .size(20.dp), tint = MaibPrimary ) Text( text = numberFormatted(post.commentsCount), style = MaterialTheme.typography.titleMedium, maxLines = 1, textAlign = TextAlign.Center ) } } SharePost(postId = post.postId) } } } } } @Preview( backgroundColor = 0xFFFFFFFF, showBackground = true ) @Composable fun PostShortViewPreview(){ PostShortView( post = ShortPostDto(postId = "postId", postTitle = "title", creatorName = "John"), onRatingChange = {_,_->}, navigateToPost = {} ) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/GlobalViewModel.kt
102130774
package com.example.openmind.ui import android.util.Log import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.openmind.data.repository.RatingRepository import com.example.openmind.di.repository.RatingRepositoryProvider import kotlinx.coroutines.launch open class GlobalViewModel : ViewModel() { private val _errorMessageState = mutableStateOf("") private val ratingRepository: RatingRepository = RatingRepositoryProvider.provideRepository() protected val errorMessageState get() = _errorMessageState protected open fun handleError(throwable: Throwable) { Log.e("GlobalViewModel", "handleError", throwable) _errorMessageState.value = throwable.message.toString() } private fun upvote(ratingId: String) { viewModelScope.launch { ratingRepository.upvote(ratingId) } } private fun downvote(ratingId: String) { viewModelScope.launch { ratingRepository.downvote(ratingId) } } fun onRatingChange(): (String, Int) -> Unit = { ratingId, vote -> when (vote) { 1 -> upvote(ratingId) -1 -> downvote(ratingId) } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/success_post_register/SuccessRegisteredPostViewModel.kt
4199448121
package com.example.openmind.ui.success_post_register import com.example.openmind.ui.GlobalViewModel class SuccessRegisteredPostViewModel : GlobalViewModel() { }
OpenMind/openmind/src/main/java/com/example/openmind/ui/success_post_register/SuccessRegistrationPostView.kt
3931832073
package com.example.openmind.ui.success_post_register import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults 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.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.example.openmind.R import com.example.openmind.ui.theme.ManropeExtraBoldW800 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.NightBlue import com.example.openmind.ui.theme.spacing @Composable fun SuccessRegistrationPostView( navController: NavController, ) { Box(modifier = Modifier.fillMaxSize()) { Box(modifier = Modifier.fillMaxWidth()) { Image( painter = painterResource(id = R.drawable.success_post_create_header), contentDescription = "header", contentScale = ContentScale.FillWidth, ) } Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp) .align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(R.string.success_create_post), style = TextStyle( fontFamily = FontFamily.ManropeExtraBoldW800, fontSize = 24.sp, lineHeight = 30.sp, letterSpacing = (-0.5).sp, textAlign = TextAlign.Center, color = Color.DarkGray ) ) Text( text = stringResource(R.string.create_post_info), style = TextStyle( fontFamily = FontFamily.ManropeRegularW400, fontSize = 14.sp, lineHeight = 20.sp, textAlign = TextAlign.Center, color = Color.DarkGray ) ) Spacer(modifier = Modifier.height(7.dp)) Button( onClick = { navController.navigateUp() navController.navigateUp() }, modifier = Modifier .fillMaxWidth() .padding( start = MaterialTheme.spacing.large, end = MaterialTheme.spacing.large, top = 16.dp ), contentPadding = PaddingValues(vertical = 16.dp), colors = ButtonDefaults.buttonColors( contentColor = Color.White, containerColor = NightBlue ), shape = RoundedCornerShape(8.dp) ) { Text( text = "OK", style = MaterialTheme.typography.titleLarge ) } } } BackHandler( enabled = true ) { navController.navigateUp() navController.navigateUp() } } @Preview( backgroundColor = 0xFFF7F8FA, showBackground = true ) @Composable fun PreviewSuccessRegistrationPost() { SuccessRegistrationPostView( navController = rememberNavController(), ) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/MainFragment.kt
820787306
package com.example.openmind.ui import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.example.openmind.ui.navigation.Navigation import com.example.openmind.utils.SessionManager import com.example.openmindproject.ui.theme.OpenMindProjectTheme class MainFragment : Fragment() { private lateinit var navController: NavHostController private lateinit var viewModel: MainViewModel override fun onAttach(context: Context) { super.onAttach(context) SessionManager.init(requireContext()) viewModel = ViewModelProvider(this)[MainViewModel::class.java] } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return ComposeView(requireContext()).apply { setContent { OpenMindProjectTheme { navController = rememberNavController() Navigation(navController) } } } } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/categories/CategoriesView.kt
1221672912
package com.example.openmind.ui.categories import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import com.example.openmind.enums.PostCategories import com.example.openmind.ui.categories.viewModel.CategoriesViewModel import com.example.openmind.ui.components.general.BasicTopAppBar import com.example.openmind.ui.navigation.navigateToPostList import com.example.openmind.ui.screen.Screen import com.example.openmind.ui.theme.spacing @Composable fun CategoriesView( viewModel: CategoriesViewModel, navController: NavController, modifier: Modifier = Modifier ) { if (viewModel.isLoading().value) { Box( modifier = modifier .fillMaxSize(), contentAlignment = Alignment.Center ) { CircularProgressIndicator(modifier = Modifier.size(40.dp)) } } else { Column( modifier = modifier .fillMaxSize() .padding(MaterialTheme.spacing.large), ) { LazyColumn { items(items = viewModel.getCategoriesList()) { category -> CategoryView( navigateToPostList = { navController.navigateToPostList( PostCategories.valueOf( category.categoryName ) ) }, base64ToImageBitmapConverter = { base64Image -> base64Image?.let { viewModel.stringToBitMap(it) .asImageBitmap() } }, categoryDto = category ) } } } } } @Preview @Composable fun CategoriesViewPreview() { Scaffold(topBar = { BasicTopAppBar( viewModel = viewModel(), navController = rememberNavController(), currentScreen = Screen.CategoriesScreen ) }, content = { paddingValues -> CategoriesView( viewModel = CategoriesViewModel(), navController = rememberNavController(), modifier = Modifier.padding(paddingValues) ) }) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/categories/viewModel/CategoriesViewState.kt
1320578777
package com.example.openmind.ui.categories.viewModel import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import com.example.openmind.domain.model.category.CategoryDto class CategoriesViewState { val loadedCategories = mutableStateListOf<CategoryDto>() val isLoading = mutableStateOf(true) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/categories/viewModel/CategoriesViewModel.kt
1100652609
package com.example.openmind.ui.categories.viewModel import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import androidx.lifecycle.viewModelScope import com.example.openmind.data.repository.CategoriesRepository import com.example.openmind.di.repository.CategoriesRepositoryProvider import com.example.openmind.ui.GlobalViewModel import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi class CategoriesViewModel : GlobalViewModel() { private val viewState = CategoriesViewState() var repository: CategoriesRepository = CategoriesRepositoryProvider.provideRepository() fun isLoading() = viewState.isLoading @OptIn(ExperimentalEncodingApi::class) fun stringToBitMap(encodedString: String): Bitmap { val imageBytes = Base64.decode(encodedString, 0) return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) } fun getCategoriesList() = viewState.loadedCategories init { fetchList() } private fun fetchList() { viewModelScope.launch { viewState.isLoading.value = true repository.fetchAll().catch { cause: Throwable -> handleError(cause) } .collect { viewState.loadedCategories.clear() viewState.loadedCategories.addAll(it) viewState.isLoading.value = false } } } override fun onCleared() { super.onCleared() Log.e("CategoriesViewModel", "ViewModel cleared") } }
OpenMind/openmind/src/main/java/com/example/openmind/ui/categories/components/CategoriesTopBar.kt
1571491969
package com.example.openmind.ui.categories.components import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.openmind.ui.categories.viewModel.CategoriesViewModel import com.example.openmind.ui.components.general.BasicTopAppBar import com.example.openmind.ui.screen.Screen import com.example.openmind.ui.theme.DarkGray20 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmindproject.ui.theme.NavigationIconStyle @Composable fun CategoriesAppBar( viewModel: CategoriesViewModel, navController: NavController, screen: Screen<*>, ) { BasicTopAppBar( viewModel = viewModel, navController = navController, currentScreen = screen, titleStyle = MaterialTheme.typography.titleLarge.merge(textAlign = TextAlign.Center), navIconStyle = NavigationIconStyle(modifier = Modifier.size(30.dp)) ) }
OpenMind/openmind/src/main/java/com/example/openmind/ui/categories/components/CategoriesInfoList.kt
3964996298
package com.example.openmind.ui.categories.components import com.example.openmind.domain.model.category.CategoryInfo import com.example.openmind.enums.PostCategories import com.example.openmind.ui.theme.LightGreenGradient import com.example.openmind.ui.theme.OrangeGradient fun getCategoriesInfoList() = listOf( CategoryInfo( categoryType = PostCategories.BUG, categoryTitle = "Report bugs", categoryDescription = "Reports of bugs and issues with the app.", backgroundStyle = OrangeGradient, ), CategoryInfo( categoryType = PostCategories.FEATURE, backgroundStyle = LightGreenGradient, categoryTitle = "Recommend features", categoryDescription = "New features and improvements to the app.", ) )
OpenMind/openmind/src/main/java/com/example/openmind/ui/categories/CategoryView.kt
2043804806
package com.example.openmind.ui.categories import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape 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.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.openmind.domain.model.category.CategoryDto import com.example.openmind.ui.theme.DarkGray20 import com.example.openmind.ui.theme.ManropeBoldW700 import com.example.openmind.ui.theme.ManropeRegularW400 import com.example.openmind.ui.theme.spacing @Composable fun CategoryView( base64ToImageBitmapConverter: ((String?) -> ImageBitmap?)? = null, navigateToPostList: () -> Unit, categoryDto: CategoryDto, ) { Column(modifier = Modifier.padding(top = 22.dp)) { Text( text = categoryDto.categoryTitle, style= MaterialTheme.typography.titleLarge, maxLines = 1, color = DarkGray20, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(bottom = MaterialTheme.spacing.small) ) Box( modifier = Modifier .fillMaxWidth() .defaultMinSize(minHeight = 100.dp) ) { Box(modifier = Modifier .clip(RoundedCornerShape(8.dp)) .clickable { navigateToPostList.invoke() }, contentAlignment = Alignment.CenterStart) { val image = base64ToImageBitmapConverter?.invoke(categoryDto.categoryImage) if (image != null) { Image( bitmap = image, contentDescription = "navigate", ) } Column( modifier = Modifier.padding(horizontal = 20.dp, vertical = 22.dp) ) { Text( text = "${categoryDto.postCount} posts", fontFamily = FontFamily.ManropeRegularW400, fontSize = 12.sp, lineHeight = 16.sp, color = Color.White, overflow = TextOverflow.Ellipsis ) Text( text = changeWordStyle( categoryDto.tagLine, 0, SpanStyle(fontFamily = FontFamily.ManropeBoldW700) ), fontFamily = FontFamily.ManropeRegularW400, fontSize = 20.sp, lineHeight = 28.sp, color = Color.White, overflow = TextOverflow.Ellipsis ) } } } } } fun changeWordStyle(text: String, wordIndex: Int, style: SpanStyle): AnnotatedString { val words = text.split(' ') require(wordIndex in words.indices) { "Invalid word index" } val builder = AnnotatedString.Builder() var startIndex = 0 for (i in words.indices) { val word = words[i] val endIndex = startIndex + word.length if (i == wordIndex) { builder.withStyle(style) { append(word) } } else { builder.append(word) } if (i < words.size - 1) { builder.append(" ") } startIndex = endIndex + 1 } return builder.toAnnotatedString() }
OpenMind/openmind/src/main/java/com/example/openmind/di/repository/RatingRepositoryProvider.kt
10013959
package com.example.openmind.di.repository import com.example.openmind.data.repository.RatingRepository object RatingRepositoryProvider { private val ratingRepository = RatingRepository() fun provideRepository(): RatingRepository = ratingRepository }
OpenMind/openmind/src/main/java/com/example/openmind/di/repository/CommentsRepositoryProvider.kt
1831144983
package com.example.openmind.di.repository import com.example.openmind.data.repository.CommentsRepository object CommentsRepositoryProvider { private val repository = CommentsRepository() fun provideRepository(): CommentsRepository = repository }
OpenMind/openmind/src/main/java/com/example/openmind/di/repository/PostRepositoryProvider.kt
1196907419
package com.example.openmind.di.repository import com.example.openmind.data.repository.PostRepository object PostRepositoryProvider { private val repository = PostRepository() fun provideRepository(): PostRepository = repository }