content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package app.xlei.vipexam.core.data.repository
import app.xlei.vipexam.core.database.dao.ExamHistoryDao
import app.xlei.vipexam.core.database.module.ExamHistory
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class ExamHistoryRepositoryImpl @Inject constructor(
private val examHistoryDao: ExamHistoryDao
): ExamHistoryRepository {
override fun getAllExamHistory(): Flow<List<ExamHistory>> {
return examHistoryDao.getAllExamHistory()
}
override suspend fun removeAllHistory() {
return examHistoryDao.removeAllHistory()
}
override suspend fun getExamHistoryByExamId(examId: String): ExamHistory? {
return examHistoryDao.getExamHistoryByExamId(examId)
}
override suspend fun getLastOpened(): Flow<ExamHistory?> {
return examHistoryDao.getLastOpened()
}
override suspend fun removeHistory(examHistory: ExamHistory) {
examHistoryDao.deleteHistory(examHistory)
}
override suspend fun insertHistory(examName: String, examId: String) {
examHistoryDao.insert(
ExamHistory(examName = examName, examId = examId)
)
}
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/repository/ExamHistoryRepositoryImpl.kt | 1960969947 |
package app.xlei.vipexam.core.data.repository
import kotlinx.coroutines.flow.Flow
interface Repository<T> {
fun getAll(): Flow<List<T>>
suspend fun add(item: T)
suspend fun remove(item: T)
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/repository/Repository.kt | 2456479529 |
package app.xlei.vipexam.core.data.repository
import app.xlei.vipexam.core.database.dao.UserDao
import app.xlei.vipexam.core.database.module.User
import javax.inject.Inject
class UserRepository @Inject constructor(
private val userDao: UserDao
) : Repository<User> {
override fun getAll() = userDao.getAllUsers()
override suspend fun remove(item: User) = userDao.delete(item)
override suspend fun add(item: User) = userDao.insert(item)
}
| vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/repository/UserRepository.kt | 3313168887 |
package app.xlei.vipexam.core.data.repository
import app.xlei.vipexam.core.database.module.Bookmark
import kotlinx.coroutines.flow.Flow
interface BookmarkRepository {
fun getAllBookmarks(): Flow<List<Bookmark>>
suspend fun addBookmark(
examName: String,
examId: String,
question: String,
)
suspend fun deleteBookmark(bookmark: Bookmark)
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/repository/BookmarkRepository.kt | 3019125740 |
package app.xlei.vipexam.core.data.repository
import app.xlei.vipexam.core.database.dao.BookmarkDao
import app.xlei.vipexam.core.database.module.Bookmark
import app.xlei.vipexam.core.network.module.NetWorkRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
class BookmarkRepositoryImpl @Inject constructor(
private val bookmarkDao: BookmarkDao
): BookmarkRepository {
override fun getAllBookmarks(): Flow<List<Bookmark>> {
return bookmarkDao.getAllBookMarks()
}
override suspend fun addBookmark(
examName: String,
examId: String,
question: String,
) {
val addFirstLevelQuestions = suspend {
NetWorkRepository.getExam(examId).onSuccess {
val firstLevelQuestion = it.muban.firstOrNull { _muban ->
_muban.cname == question
}
firstLevelQuestion?.shiti?.map { shiti ->
NetWorkRepository.addQCollect(examId, shiti.questionCode)
.onSuccess { println(it) }
}
}
}
val addSecondLevelQuestions = suspend {
NetWorkRepository.getExam(examId).onSuccess {
it.muban.firstOrNull { _muban ->
_muban.cname == question
}?.shiti?.forEach { shiti ->
shiti.children.map { children ->
NetWorkRepository.addQCollect(examId, children.questionCode)
.onSuccess { println(it) }
}
}
}
}
bookmarkDao.insertBookmark(
Bookmark(
examId = examId,
examName = examName,
question = question,
)
)
.also {
withContext(Dispatchers.IO) {
coroutineScope {
async { addFirstLevelQuestions.invoke() }.await()
async { addSecondLevelQuestions.invoke() }.await()
}
}
}
}
override suspend fun deleteBookmark(bookmark: Bookmark) {
val examId = bookmark.examId
val question = bookmark.question
val deleteFirstLevelQuestions = suspend {
NetWorkRepository.getExam(examId).onSuccess {
val firstLevelQuestion = it.muban.firstOrNull { _muban ->
_muban.cname == question
}
firstLevelQuestion?.shiti?.map { shiti ->
NetWorkRepository.deleteQCollect(examId, shiti.questionCode)
.onSuccess { println(it) }
}
}
}
val deleteSecondLevelQuestions = suspend {
NetWorkRepository.getExam(examId).onSuccess {
it.muban.firstOrNull { _muban ->
_muban.cname == question
}?.shiti?.forEach { shiti ->
shiti.children.map { children ->
NetWorkRepository.deleteQCollect(examId, children.questionCode)
.onSuccess { println(it) }
}
}
}
}
bookmarkDao.deleteBookmark(bookmark)
.also {
withContext(Dispatchers.IO) {
coroutineScope {
async { deleteFirstLevelQuestions.invoke() }.await()
async { deleteSecondLevelQuestions.invoke() }.await()
}
}
}
}
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/repository/BookmarkRepositoryImpl.kt | 1277563676 |
package app.xlei.vipexam.core.data.di
import app.xlei.vipexam.core.data.repository.BookmarkRepository
import app.xlei.vipexam.core.data.repository.BookmarkRepositoryImpl
import app.xlei.vipexam.core.data.repository.ExamHistoryRepository
import app.xlei.vipexam.core.data.repository.ExamHistoryRepositoryImpl
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.data.repository.UserRepository
import app.xlei.vipexam.core.data.repository.WordRepository
import app.xlei.vipexam.core.data.util.ConnectivityManagerNetworkMonitor
import app.xlei.vipexam.core.data.util.NetworkMonitor
import app.xlei.vipexam.core.database.module.User
import app.xlei.vipexam.core.database.module.Word
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface DataModule {
@Binds
fun bindsWordRepository(
wordRepository: WordRepository
): Repository<Word>
@Binds
fun bindsUserRepository(
userRepository: UserRepository
): Repository<User>
@Binds
fun bindsExamHistoryRepository(
examHistoryRepositoryImpl: ExamHistoryRepositoryImpl
): ExamHistoryRepository
@Binds
fun bindsBookmarkRepository(
bookmarkRepository: BookmarkRepositoryImpl
): BookmarkRepository
@Binds
fun bindsNetworkMonitor(
networkMonitor: ConnectivityManagerNetworkMonitor,
): NetworkMonitor
}
| vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/di/DataModule.kt | 2536991352 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.xlei.vipexam.core.data.util
import android.content.Context
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest.Builder
import androidx.core.content.getSystemService
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import javax.inject.Inject
class ConnectivityManagerNetworkMonitor @Inject constructor(
@ApplicationContext private val context: Context,
) : NetworkMonitor {
override val isOnline: Flow<Boolean> = callbackFlow {
val connectivityManager = context.getSystemService<ConnectivityManager>()
if (connectivityManager == null) {
channel.trySend(false)
channel.close()
return@callbackFlow
}
val callback = object : NetworkCallback() {
private val networks = mutableSetOf<Network>()
override fun onAvailable(network: Network) {
networks += network
channel.trySend(true)
}
override fun onLost(network: Network) {
networks -= network
channel.trySend(networks.isNotEmpty())
}
}
val request = Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
connectivityManager.registerNetworkCallback(request, callback)
channel.trySend(connectivityManager.isCurrentlyConnected())
awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
}
}
.conflate()
private fun ConnectivityManager.isCurrentlyConnected() = activeNetwork
?.let(::getNetworkCapabilities)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
}
| vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/util/ConnectivityManagerNetworkMonitor.kt | 3841165608 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.xlei.vipexam.core.data.util
import kotlinx.coroutines.flow.Flow
interface NetworkMonitor {
val isOnline: Flow<Boolean>
}
| vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/util/NetworkMonitor.kt | 3036587108 |
package app.xlei.vipexam.core.data.paging
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingSource
import androidx.paging.PagingState
import app.xlei.vipexam.core.data.constant.ExamType
import app.xlei.vipexam.core.data.repository.ExamHistoryRepository
import app.xlei.vipexam.core.network.module.NetWorkRepository
import app.xlei.vipexam.core.network.module.getExamList.Exam
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton
interface ExamListRepository {
suspend fun getExamList(): Flow<PagingData<ExamListItem>>
suspend fun search(query: String): Flow<PagingData<ExamListItem>>
}
interface ExamListRemoteDataSource {
suspend fun getExamList(
pageNumber: Int
): List<Exam>
suspend fun search(
pageNumber: Int,
query: String
): List<Exam>
}
object ExamListApi {
private var examStyle = 5
private var examTypeCode = "ve01002"
fun setType(type: ExamType) {
examStyle = type.examStyle
examTypeCode = type.examTypeCode
}
suspend fun getExamList(pageNumber: Int): List<Exam> {
var examList = listOf<Exam>()
NetWorkRepository.getExamList(
page = pageNumber.toString(),
examStyle = examStyle,
examTypeEName = examTypeCode
)
.onSuccess {
examList = it.list
}
.onFailure {
examList = emptyList()
}
return examList
}
suspend fun searchExam(
pageNumber: Int,
searchContent: String,
): List<Exam>{
var examList = listOf<Exam>()
NetWorkRepository.searchExam(
page = pageNumber.toString(),
searchContent = searchContent
)
.onSuccess {
examList = it.list
}
.onFailure {
examList = emptyList()
}
return examList
}
}
class ExamListRemoteDataSourceImpl : ExamListRemoteDataSource {
override suspend fun getExamList(
pageNumber: Int
): List<Exam> {
return ExamListApi.getExamList(pageNumber = pageNumber)
}
override suspend fun search(pageNumber: Int, query: String): List<Exam> {
return ExamListApi.searchExam(
pageNumber = pageNumber,
searchContent = query,
)
}
}
class ExamListRepositoryImpl @Inject constructor(
private val remoteDataSource: ExamListRemoteDataSource,
private val examHistoryRepository: ExamHistoryRepository,
private val coroutineScope: CoroutineScope,
) : ExamListRepository {
override suspend fun getExamList(): Flow<PagingData<ExamListItem>> {
return Pager(
config = PagingConfig(pageSize = 9999, prefetchDistance = 2),
pagingSourceFactory = {
ExamPagingSource(remoteDataSource,examHistoryRepository,coroutineScope)
}
).flow
}
override suspend fun search(query: String): Flow<PagingData<ExamListItem>> {
return Pager(
config = PagingConfig(pageSize = 9999, prefetchDistance = 10),
pagingSourceFactory = {
SearchExamPagingSource(remoteDataSource,examHistoryRepository,coroutineScope,query)
}
).flow
}
}
data class ExamListItem(
val exam: Exam,
val lastOpen: Long?,
)
class SearchExamPagingSource @Inject constructor(
private val remoteDataSource: ExamListRemoteDataSource,
private val examHistoryRepository: ExamHistoryRepository,
private val coroutineScope: CoroutineScope,
private val query: String,
): PagingSource<Int, ExamListItem>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ExamListItem> {
return try {
val currentPage = params.key ?: 1
val examList = remoteDataSource.search(
pageNumber = currentPage,
query = query,
)
val examItemList = examList.map { exam ->
coroutineScope.async {
val lastOpen = withContext(Dispatchers.IO) {
examHistoryRepository.getExamHistoryByExamId(exam.examid)?.lastOpen
}
ExamListItem(
exam = exam,
lastOpen = lastOpen
)
}
}.awaitAll()
LoadResult.Page(
data = examItemList,
prevKey = if (currentPage == 1) null else currentPage - 1,
nextKey = if (examList.isEmpty()) null else currentPage + 1
)
} catch (exception: Exception) {
return LoadResult.Error(exception)
}
}
override fun getRefreshKey(state: PagingState<Int, ExamListItem>): Int? {
return state.anchorPosition
}
}
class ExamPagingSource @Inject constructor(
private val remoteDataSource: ExamListRemoteDataSource,
private val examHistoryRepository: ExamHistoryRepository,
private val coroutineScope: CoroutineScope,
): PagingSource<Int, ExamListItem>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ExamListItem> {
return try {
val currentPage = params.key ?: 1
val examList = remoteDataSource.getExamList(
pageNumber = currentPage,
)
val examItemList = examList.map { exam ->
coroutineScope.async {
val lastOpen = withContext(Dispatchers.IO) {
examHistoryRepository.getExamHistoryByExamId(exam.examid)?.lastOpen
}
ExamListItem(
exam = exam,
lastOpen = lastOpen
)
}
}.awaitAll()
LoadResult.Page(
data = examItemList,
prevKey = if (currentPage == 1) null else currentPage - 1,
nextKey = if (examList.isEmpty()) null else currentPage + 1
)
} catch (exception: Exception) {
return LoadResult.Error(exception)
}
}
override fun getRefreshKey(state: PagingState<Int, ExamListItem>): Int? {
return state.anchorPosition
}
}
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun providesExamListRemoteDataSource(): ExamListRemoteDataSource {
return ExamListRemoteDataSourceImpl()
}
@Singleton
@Provides
fun providesExamListRepository(
examListRemoteDataSource: ExamListRemoteDataSource,
examHistoryRepository: ExamHistoryRepository,
coroutineScope: CoroutineScope,
): ExamListRepository {
return ExamListRepositoryImpl(examListRemoteDataSource,examHistoryRepository,coroutineScope)
}
@Singleton
@Provides
fun providesGetMoviesUseCase(
examListRepository: ExamListRepository
): GetExamListUseCase {
return GetExamListUseCase(examListRepository)
}
}
interface BaseUseCase<In, Out>{
suspend fun execute(input: In): Out
}
class GetExamListUseCase @Inject constructor(
private val repository: ExamListRepository
) : BaseUseCase<Unit, Flow<PagingData<ExamListItem>>> {
override suspend fun execute(input: Unit): Flow<PagingData<ExamListItem>> {
return repository.getExamList()
}
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/paging/ExamPaingSource.kt | 1572184463 |
package app.xlei.vipexam.core.data.paging
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingSource
import androidx.paging.PagingState
import app.xlei.vipexam.core.network.module.NetWorkRepository
import app.xlei.vipexam.core.network.module.momoLookUp.Phrase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton
interface MomoLookUpRepository {
suspend fun search(): Flow<PagingData<Phrase>>
}
interface MomoLookUpRemoteDataSource {
suspend fun search(
offset: Int,
): List<Phrase>
}
class MomoLookUpRepositoryImpl @Inject constructor(
private val remoteDataSource: MomoLookUpRemoteDataSource
) : MomoLookUpRepository {
override suspend fun search(): Flow<PagingData<Phrase>> {
return Pager(
config = PagingConfig(pageSize = 9999, prefetchDistance = 2),
pagingSourceFactory = {
MomoLookUpPagingSource(remoteDataSource)
}
).flow
}
}
enum class Source(val value: String, val displayName: String) {
ALL("ALL", "全部"),
CET4("CET4", "四级"),
CET6("CET6", "六级"),
KAOYAN("POSTGRADUATE", "考研")
}
object MomoLookUpApi {
var keyword = ""
var source = Source.ALL
suspend fun search(offset: Int) =
NetWorkRepository.momoLookUp(offset = offset, keyword = keyword, paperType = source.value)
}
class MomoLookUpRemoteDataSourceImpl : MomoLookUpRemoteDataSource {
override suspend fun search(offset: Int): List<Phrase> {
var phrases = listOf<Phrase>()
MomoLookUpApi
.search(offset = offset)
.onSuccess {
phrases = it.data.phrases
}
.onFailure {
phrases = emptyList()
}
return phrases
}
}
class MomoLookUpPagingSource @Inject constructor(
private val remoteDataSource: MomoLookUpRemoteDataSource
) : PagingSource<Int, Phrase>() {
override fun getRefreshKey(state: PagingState<Int, Phrase>): Int? {
return state.anchorPosition
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Phrase> {
return try {
val offset = params.key ?: 0
val searchResult = remoteDataSource.search(
offset = offset
)
println(offset)
LoadResult.Page(
data = searchResult,
prevKey = if (offset == 0) null else offset - 10,
nextKey = if (searchResult.isEmpty()) null else offset + 10
)
} catch (e: Exception) {
println(e)
LoadResult.Error(e)
}
}
}
@Module
@InstallIn(SingletonComponent::class)
object MomoLookModule {
@Singleton
@Provides
fun providesMomoLookUpRemoteDataSource(): MomoLookUpRemoteDataSource {
return MomoLookUpRemoteDataSourceImpl()
}
@Singleton
@Provides
fun providesMomoLookUpRepository(
remoteDataSource: MomoLookUpRemoteDataSource
): MomoLookUpRepository {
return MomoLookUpRepositoryImpl(remoteDataSource)
}
}
| vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/paging/MomoLookUpPagingSource.kt | 1313840605 |
package app.xlei.vipexam.core.data.constant
enum class ShowAnswerOption(
val value: Int
) {
ALWAYS(0),
ONCE(1)
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/constant/ShowAnswerOption.kt | 2870312791 |
package app.xlei.vipexam.core.data.constant
enum class ThemeMode(val value: Int) {
AUTO(0),
LIGHT(1),
DARK(2),
BLACK(3)
}
| vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/constant/ThemeMode.kt | 1228675298 |
package app.xlei.vipexam.core.data.constant
enum class ExamType(
val examTypeCode: String,
val examStyle: Int,
val examTypeName: String,
val isReal: Boolean,
) {
CET4_REAL("ve01001", 5, "大学英语四级真题", true),
CET4_PRACTICE("ve01001", 4, "大学英语四级模拟试题", false),
CET6_REAL("ve01002", 5, "大学英语六级真题", true),
CET6_PRACTICE("ve01002", 4, "大学英语六级模拟试题", false),
KAOYAN_ENGLISH_I_REAL("ve03001", 5, "考研英语一真题", true),
KAOYAN_ENGLISH_I_PRACTICE("ve03001", 4, "考研英语一模拟试题", false),
KAOYAN_ENGLISH_II_REAL("ve03002", 5, "考研英语二真题", true),
KAOYAN_ENGLISH_II_PRACTICE("ve03002", 4, "考研英语二模拟试题", false),
KAOYAN_408_REAL("ve03201003", 5, "考研408真题", true),
KAOYAN_408_PRACTICE("ve03201003", 4, "考研408模拟试题", false),
RUANKAO_1("ve02102001", 4, "软件水平考试(中级)软件设计师上午(基础知识)", false),
RUANKAO_2("ve02102002", 4, "软件水平考试(中级)软件设计师下午(应用技术)", false),
KAOYAN_ZHENGZHI_REAL("ve03006", 5, "考研政治真题", true),
KAOYAN_ZHENGZHI_PRACTICE("ve03006", 4, "考研政治模拟试题", false)
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/constant/ExamType.kt | 978997221 |
package app.xlei.vipexam.core.data.constant
enum class LongPressAction(
val value: Int
) {
SHOW_QUESTION(0),
TRANSLATE(1),
NONE(2),
} | vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/constant/LongPressAction.kt | 2240429556 |
package app.xlei.vipexam.core.data.constant
object Constants {
const val ORGANIZATION = "吉林大学"
}
| vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/constant/Constants.kt | 330427130 |
package app.xlei.vipexam.core.domain
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("app.xlei.vipexam.core.domain.test", appContext.packageName)
}
} | vipexam/core/domain/src/androidTest/java/app/xlei/vipexam/core/domain/ExampleInstrumentedTest.kt | 1650166239 |
package app.xlei.vipexam.core.domain
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)
}
} | vipexam/core/domain/src/test/java/app/xlei/vipexam/core/domain/ExampleUnitTest.kt | 1898231474 |
package app.xlei.vipexam.core.domain
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.database.module.User
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
class GetAllUsersUseCase @Inject constructor(
private val userRepository: Repository<User>,
) {
private fun getAllUsers(): Flow<List<User>> {
return userRepository.getAll()
}
operator fun invoke() = getAllUsers()
}
| vipexam/core/domain/src/main/java/app/xlei/vipexam/core/domain/GetAllUsersUseCase.kt | 3925127180 |
package app.xlei.vipexam.core.domain
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.database.module.User
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class AddUserUseCase @Inject constructor(
private val userRepository: Repository<User>,
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
private suspend fun addUser(user: User) {
return userRepository.add(user)
}
suspend operator fun invoke(user: User) = withContext(defaultDispatcher){
addUser(user)
}
} | vipexam/core/domain/src/main/java/app/xlei/vipexam/core/domain/AddUserUseCase.kt | 1680030791 |
package app.xlei.vipexam.core.domain
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.database.module.User
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class DeleteUserUseCase @Inject constructor(
private val userRepository: Repository<User>,
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
private suspend fun deleteUser(user: User) {
return userRepository.remove(user)
}
suspend operator fun invoke(user: User) = withContext(defaultDispatcher){
deleteUser(user)
}
}
| vipexam/core/domain/src/main/java/app/xlei/vipexam/core/domain/RemoveUserUseCase.kt | 4073596696 |
package app.xlei.vipexam.core.domain
import app.xlei.vipexam.core.data.repository.UserRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class DomainModule {
@Singleton
@Provides
fun providesGetAllUsersUseCase(
userRepository: UserRepository
) = GetAllUsersUseCase(userRepository)
@Singleton
@Provides
fun providesAddUserUseCase(
userRepository: UserRepository
) = AddUserUseCase(userRepository)
@Singleton
@Provides
fun providesDeleteUserUseCase(
userRepository: UserRepository
) = DeleteUserUseCase(userRepository)
} | vipexam/core/domain/src/main/java/app/xlei/vipexam/core/domain/DomainModule.kt | 2191003011 |
package app.xlei.vipexam
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("app.xlei.vipexam", appContext.packageName)
}
} | vipexam/app/src/androidTest/java/app/xlei/vipexam/ExampleInstrumentedTest.kt | 1161289513 |
package app.xlei.vipexam
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)
}
} | vipexam/app/src/test/java/app/xlei/vipexam/ExampleUnitTest.kt | 2395923767 |
package app.xlei.vipexam.ui.appbar
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.xlei.vipexam.core.data.repository.BookmarkRepository
import app.xlei.vipexam.core.database.module.Bookmark
import app.xlei.vipexam.core.network.module.NetWorkRepository
import app.xlei.vipexam.core.network.module.TiJiaoTest.TestQuestion
import app.xlei.vipexam.core.network.module.TiJiaoTest.TiJiaoTestPayload
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* App bar view model
*
* @property bookmarkRepository 用于书签按钮
* @constructor Create empty App bar view model
*/
@HiltViewModel
class AppBarViewModel @Inject constructor(
private val bookmarkRepository: BookmarkRepository
) : ViewModel() {
private val _bookmarks = MutableStateFlow(emptyList<Bookmark>())
val bookmarks = _bookmarks.asStateFlow()
private val _submitState = MutableStateFlow<SubmitState<Nothing>>(SubmitState.Default)
val submitState
get() = _submitState.asStateFlow()
init {
getBookmarks()
}
/**
* Get bookmarks
* 获得全部书签
*/
private fun getBookmarks() {
viewModelScope.launch {
bookmarkRepository
.getAllBookmarks()
.flowOn(Dispatchers.IO)
.collect { bookmark: List<Bookmark> ->
_bookmarks.update {
bookmark
}
}
}
}
/**
* Add to bookmark
* 添加到书签
* @param examName 试卷名称
* @param examId 试卷id
* @param question 问题名称
*/
fun addToBookmark(
examName: String,
examId: String,
question: String,
) {
viewModelScope.launch {
bookmarkRepository
.addBookmark(
examName = examName,
examId = examId,
question = question,
)
}
}
/**
* Remove from bookmarks
* 移除书签
* @param bookmark 书签对象
*/
fun removeFromBookmarks(bookmark: Bookmark) {
viewModelScope.launch {
bookmarkRepository
.deleteBookmark(
bookmark = bookmark
)
}
}
fun submit(exam: GetExamResponse, myAnswer: Map<String, String>) {
println(myAnswer)
viewModelScope.launch {
_submitState.update {
SubmitState.Submitted
}
NetWorkRepository.tiJiaoTest(
payload = TiJiaoTestPayload(
count = exam.count.toString(),
examID = exam.examID,
examName = exam.examName,
examStyle = exam.examstyle,
examTypeCode = exam.examTypeCode,
testQuestion = exam.muban.flatMap { muban ->
muban.shiti.flatMap { shiti ->
listOf(
TestQuestion(
basic = muban.basic,
grade = muban.grade,
questiontype = muban.ename,
questionCode = shiti.questionCode,
refAnswer = myAnswer[shiti.questionCode] ?: ""
)
) + shiti.children.map { child ->
TestQuestion(
basic = muban.basic,
grade = muban.grade,
questiontype = muban.ename,
questionCode = child.questionCode,
refAnswer = myAnswer[child.questionCode] ?: ""
)
}
}
}
)
).onSuccess {
_submitState.update {
SubmitState.Success(
grade = exam.muban.flatMap { muban ->
muban.shiti.flatMap { shiti ->
listOf(
if (shiti.refAnswer != "" && shiti.refAnswer == (myAnswer[shiti.questionCode]
?: "")
)
1 else 0
) + shiti.children.map { child ->
if (child.refAnswer != "" && child.refAnswer == (myAnswer[child.questionCode]
?: "")
)
1 else 0
}
}
}.sum(),
gradeCount = exam.muban.joinToString(";") {
it.cname + ": " + it.shiti.flatMap { shiti ->
listOf(
if (shiti.refAnswer != "" && shiti.refAnswer == (myAnswer[shiti.questionCode]
?: "")
)
1 else 0
) + shiti.children.map { child ->
if (child.refAnswer != "" && child.refAnswer == (myAnswer[child.questionCode]
?: "")
)
1 else 0
}
}.sum().toString() + "/" + it.shiti.flatMap { shiti ->
listOf(
if (shiti.refAnswer != "")
1 else 0
) + shiti.children.map { child ->
if (child.refAnswer != "")
1 else 0
}
}.sum().toString()
}
)
}
}.onFailure { err ->
_submitState.update { SubmitState.Failed(msg = err.toString()) }
}
}
}
fun resetSubmitState() {
_submitState.update {
SubmitState.Default
}
}
}
sealed class SubmitState<out T> {
data object Default : SubmitState<Nothing>()
data object Submitted : SubmitState<Nothing>()
data class Success(val grade: Int, val gradeCount: String) : SubmitState<Nothing>()
data class Failed(val msg: String) : SubmitState<Nothing>()
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/appbar/AppBarViewModel.kt | 1604255051 |
package app.xlei.vipexam.ui.appbar
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalShowAnswer
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import app.xlei.vipexam.ui.components.VipexamCheckbox
import compose.icons.FeatherIcons
import compose.icons.feathericons.Menu
import compose.icons.feathericons.Star
import kotlinx.coroutines.launch
/**
* Vip exam app bar
*
* @param modifier
* @param scrollable 大屏情况下禁用滚动
* @param appBarTitle 标题
* @param canNavigateBack 是否能导航返回
* @param navigateUp 导航返回的函数
* @param openDrawer 打开侧边抽屉
* @param scrollBehavior 滚动行为
* @param viewModel 标题vm
* @receiver
* @receiver
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun VipExamAppBar(
modifier: Modifier = Modifier,
scrollable: Boolean = true,
appBarTitle: AppBarTitle,
canNavigateBack: Boolean,
navigateUp: () -> Unit,
openDrawer: () -> Unit,
scrollBehavior: TopAppBarScrollBehavior,
myAnswer: Map<String, String>,
viewModel: AppBarViewModel = hiltViewModel()
) {
var showMenu by remember { mutableStateOf(false) }
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
val showAnswer = LocalShowAnswer.current.isShowAnswer()
val uiState by viewModel.bookmarks.collectAsState()
val submitState by viewModel.submitState.collectAsState()
val isInBookmark = when (appBarTitle) {
is AppBarTitle.Exam -> uiState.any { it.examId == appBarTitle.exam.examID && it.question == appBarTitle.question }
else -> false
}
val title = @Composable {
when (appBarTitle) {
is AppBarTitle.Exam -> Text(text = appBarTitle.question)
else -> Text(text = stringResource(id = appBarTitle.nameId))
}
}
val navigationIcon = @Composable {
when {
canNavigateBack -> {
IconButton(
onClick = {
navigateUp()
if (showAnswer) {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.ShowAnswer,
false
)
}
}
}
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.back_button)
)
}
}
scrollable ->
IconButton(onClick = openDrawer) {
Icon(
imageVector = FeatherIcons.Menu,
contentDescription = null,
)
}
}
}
val actions = @Composable {
when (appBarTitle) {
is AppBarTitle.Exam -> {
IconButton(onClick = {
if (isInBookmark) viewModel.removeFromBookmarks(
bookmark = uiState.first {
it.examId == appBarTitle.exam.examID
&& it.question == appBarTitle.question
}
)
else viewModel.addToBookmark(
appBarTitle.exam.examName,
appBarTitle.exam.examID,
appBarTitle.question,
)
}) {
Icon(
imageVector = if (isInBookmark) Icons.Default.Star else FeatherIcons.Star,
contentDescription = null
)
}
IconButton(
onClick = { showMenu = !showMenu }
) {
Icon(Icons.Default.MoreVert, "")
}
DropdownMenu(
expanded = showMenu,
onDismissRequest = { showMenu = false }
) {
DropdownMenuItem(
text = {
Row {
VipexamCheckbox(
checked = showAnswer,
onCheckedChange = null,
)
Text(
text = stringResource(R.string.show_answer),
modifier = Modifier
.padding(horizontal = 24.dp)
)
}
},
onClick = {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.ShowAnswer,
showAnswer.not()
)
}
showMenu = false
}
)
DropdownMenuItem(
text = {
Text(
text = stringResource(id = R.string.submit),
modifier = Modifier
.padding(horizontal = 24.dp)
)
},
onClick = {
viewModel.submit(appBarTitle.exam, myAnswer)
}
)
}
}
else -> {}
}
}
when (scrollable) {
true -> LargeTopAppBar(
title = title,
navigationIcon = navigationIcon,
actions = { actions() },
scrollBehavior = scrollBehavior,
modifier = modifier
)
false -> TopAppBar(
title = title,
navigationIcon = navigationIcon,
actions = { actions() },
modifier = modifier
)
}
if (submitState is SubmitState.Success || submitState is SubmitState.Failed) {
AlertDialog(
text = {
when (submitState) {
is SubmitState.Success -> {
Column {
Text(
style = MaterialTheme.typography.bodyLarge,
text = "${stringResource(id = R.string.total)}: ${(submitState as SubmitState.Success).grade}"
)
Text(
text = (submitState as SubmitState.Success).gradeCount.split(";")
.joinToString("\n")
)
}
}
is SubmitState.Failed -> {
Text(text = (submitState as SubmitState.Failed).msg)
}
else -> {}
}
},
onDismissRequest = { viewModel.resetSubmitState() },
confirmButton = { }
)
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/appbar/VipExamAppBar.kt | 2220986911 |
package app.xlei.vipexam.ui.appbar
import app.xlei.vipexam.R
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
/**
* App bar title
* 主页面的标题
* @property nameId
* @constructor Create empty App bar title
*/
sealed class AppBarTitle(
val nameId: Int
) {
data object Login : AppBarTitle(R.string.login)
data object ExamType : AppBarTitle(R.string.examtype)
data object ExamList : AppBarTitle(R.string.examlist)
/**
* Exam
* 试卷页面的标题,由于附加了收藏功能,
* 所以需要提供用于记录收藏的试卷名称、
* ID、问题
* @property question
* @property exam
* @constructor Create empty Exam
*/
data class Exam(
var question: String,
var exam: GetExamResponse
) : AppBarTitle(R.string.exam)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/appbar/AppBarTitle.kt | 1993815544 |
package app.xlei.vipexam.ui.expanded
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
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.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.paging.compose.collectAsLazyPagingItems
import app.xlei.vipexam.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalShowAnswerOption
import app.xlei.vipexam.preference.LocalVibrate
import app.xlei.vipexam.preference.ShowAnswerOptionPreference
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.components.Timer
import app.xlei.vipexam.ui.components.vm.SearchViewModel
import compose.icons.FeatherIcons
import compose.icons.feathericons.Clock
import compose.icons.feathericons.RotateCw
import kotlinx.coroutines.launch
/**
* Exam screen supporting pane
* 试卷页面显示的信息
* @param modifier
* @param viewModel
* @param questionListUiState 当前试卷页面要显示的问题列表
* @param navController 导航控制器,用于切换问题
*/
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun ExamScreenSupportingPane(
modifier: Modifier = Modifier,
viewModel: ExamScreenSupportingPaneViewModel = hiltViewModel(),
searchViewModel: SearchViewModel = hiltViewModel(),
questionListUiState: VipexamUiState.QuestionListUiState,
navController: NavHostController,
onExamClick: (String) -> Unit,
) {
val showAnswerOption = LocalShowAnswerOption.current
val bookmarks by viewModel.bookmarks.collectAsState()
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
var showTimer by remember {
mutableStateOf(false)
}
val relatedExam = searchViewModel.examListState.collectAsLazyPagingItems()
LaunchedEffect(Unit) {
if (questionListUiState.exam.examName.contains(Regex("[0-9]+")))
searchViewModel.search(
questionListUiState.exam.examName.filterNot { it in '0'..'9' }
)
}
val pagerState = rememberPagerState(pageCount = {
if (relatedExam.itemCount > 0) 2 else 1
})
val selectedTabIndex = pagerState.currentPage
val coroutineScope = rememberCoroutineScope()
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
text = questionListUiState.exam.examName,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
)
},
bottomBar = {
Card(
modifier = Modifier
.padding(bottom = 24.dp)
) {
BottomAppBar(
containerColor = CardDefaults.elevatedCardColors().containerColor,
actions = {
AnimatedVisibility(
visible = showTimer,
enter = fadeIn(animationSpec = tween(200), 0F),
exit = fadeOut(animationSpec = tween(200), 0F)
) {
Timer(
isTimerStart = showTimer,
isResetTimer = !showTimer,
modifier = Modifier
.padding(start = 24.dp)
)
}
},
floatingActionButton = {
FloatingActionButton(onClick = {
showTimer = !showTimer
}) {
if (!showTimer) Icon(imageVector = FeatherIcons.Clock, contentDescription = null)
else Icon(imageVector = FeatherIcons.RotateCw, contentDescription = null)
}
},
// scroll behavior
// Scrolling
// Upon scroll, the bottom app bar can appear or disappear:
// * Scrolling downward hides the bottom app bar. If a FAB is present, it detaches from the bar and remains on screen.
// * Scrolling upward reveals the bottom app bar, and reattaches to a FAB if one is present
)
}
},
modifier = modifier
){padding->
ElevatedCard (
modifier = Modifier
.padding(padding)
.padding(bottom = 24.dp)
.fillMaxSize()
){
val vibrate = LocalVibrate.current
val haptics = LocalHapticFeedback.current
if (relatedExam.itemCount > 0)
TabRow(selectedTabIndex = selectedTabIndex) {
Tab(
selected = selectedTabIndex == 0,
onClick = {
coroutineScope.launch {
pagerState.animateScrollToPage(0)
}
},
text = { Text(text = stringResource(id = R.string.question)) }
)
Tab(
selected = selectedTabIndex == 1,
onClick = {
coroutineScope.launch {
pagerState.animateScrollToPage(1)
}
},
text = { Text(text = stringResource(id = R.string.related_exam)) }
)
}
HorizontalPager(state = pagerState) { page: Int ->
if (page == 0) {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
questionListUiState.questions.forEach {
item {
ListItem(
headlineContent = { Text(text = it.second) },
trailingContent = {
if (bookmarks.any { bookmark ->
bookmark.examName == questionListUiState.exam.examName
&& bookmark.question == it.second
})
Icon(
imageVector = Icons.Default.Star,
contentDescription = null
)
},
modifier = Modifier
.clickable {
// examName: String ,examId: String, question: String
navController.navigate(it.first) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
if (vibrate.isVibrate()) haptics.performHapticFeedback(
HapticFeedbackType.LongPress
)
if (showAnswerOption == ShowAnswerOptionPreference.Once) {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.ShowAnswer,
false
)
}
}
}
)
}
}
}
} else {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
items(relatedExam.itemCount) {
if (relatedExam[it]?.exam?.examname != questionListUiState.exam.examName)
ListItem(
headlineContent = {
Text(text = relatedExam[it]?.exam?.examname ?: "")
},
modifier = Modifier.clickable {
onExamClick(relatedExam[it]!!.exam.examid)
}
)
}
}
}
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/expanded/ExamScreenSupportingPane.kt | 2456424370 |
package app.xlei.vipexam.ui.expanded
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.xlei.vipexam.core.data.repository.BookmarkRepository
import app.xlei.vipexam.core.database.module.Bookmark
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Exam screen supporting pane view model
* 试卷页面显示试卷标题和问题列表,切换问题
* @property bookmarkRepository 用于显示是否已经加入书签
* @constructor Create empty Exam screen supporting pane view model
*/
@HiltViewModel
class ExamScreenSupportingPaneViewModel @Inject constructor(
private val bookmarkRepository: BookmarkRepository
) : ViewModel() {
private val _bookmarks = MutableStateFlow(emptyList<Bookmark>())
val bookmarks = _bookmarks.asStateFlow()
init {
getBookmarks()
}
private fun getBookmarks(){
viewModelScope.launch {
bookmarkRepository
.getAllBookmarks()
.flowOn(Dispatchers.IO)
.collect { bookmark: List<Bookmark> ->
_bookmarks.update {
bookmark
}
}
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/expanded/ExamScreenSupportingPaneViewModel.kt | 1396331604 |
package app.xlei.vipexam.ui.expanded
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.R
import app.xlei.vipexam.core.ui.DateText
import app.xlei.vipexam.feature.history.HistoryViewModel
/**
* Exam list screen supporting pane
* 试卷列表屏幕的历史记录部分
* @param modifier
* @param viewModel 历史记录vm
* @param onExamClick 历史记录点击事件
* @receiver
*/
@Composable
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3Api::class)
fun ExamListScreenSupportingPane(
modifier: Modifier = Modifier,
viewModel: HistoryViewModel = hiltViewModel(),
onExamClick: (String) -> Unit = {},
){
val history by viewModel.examHistory.collectAsState()
Scaffold(
topBar = { TopAppBar(title = { Text(text = stringResource(id = R.string.history)) }) },
modifier = modifier
) {padding->
ElevatedCard(
modifier = Modifier
.padding(padding)
.fillMaxSize()
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
){
items(history.size){
ListItem(
headlineContent = {
Text(
text = history[it].examName
) },
supportingContent = {
DateText(history[it].lastOpen)
},
modifier = Modifier
.clickable {
onExamClick.invoke(history[it].examId)
}
)
}
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/expanded/ExamListScreenSupportingPane.kt | 490554806 |
package app.xlei.vipexam.ui
import androidx.annotation.StringRes
import app.xlei.vipexam.core.database.module.User
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import app.xlei.vipexam.core.network.module.login.LoginResponse
import app.xlei.vipexam.ui.appbar.AppBarTitle
import kotlinx.coroutines.flow.Flow
data class VipexamUiState(
var loginUiState: UiState<LoginUiState>,
var examTypeListUiState: UiState<ExamTypeListUiState>,
var examListUiState: UiState<ExamListUiState>,
var questionListUiState: UiState<QuestionListUiState>,
val title: AppBarTitle,
) {
data class LoginUiState(
val account: String,
val password: String,
val loginResponse: LoginResponse?,
val users: Flow<List<User>>,
)
data class ExamTypeListUiState(
val examListUiState: UiState<ExamListUiState>,
)
data class ExamListUiState(
val isReal: Boolean,
val questionListUiState: UiState<QuestionListUiState>,
)
data class QuestionListUiState(
val exam: GetExamResponse,
val questions: List<Pair<String, String>>,
val question: String?,
)
}
sealed class UiState<out T> {
data class Success<T>(val uiState: T) : UiState<T>()
data class Loading<T>(@StringRes val loadingMessageId: Int) : UiState<T>()
data class Error(@StringRes val errorMessageId: Int, val msg: String? = null) : UiState<Nothing>()
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/VipexamUiState.kt | 462658427 |
package app.xlei.vipexam.ui.page
import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import app.xlei.vipexam.LocalScrollAwareWindowInsets
import app.xlei.vipexam.core.data.paging.ExamListItem
import app.xlei.vipexam.core.ui.DateText
import app.xlei.vipexam.core.ui.ErrorMessage
import app.xlei.vipexam.core.ui.LoadingNextPageItem
import app.xlei.vipexam.core.ui.PageLoader
import app.xlei.vipexam.core.ui.util.isScrollingUp
import kotlinx.coroutines.launch
/**
* Exam list view
*
* @param modifier
* @param isReal 试卷类型:模拟还是真题
* @param viewModel 试卷列表vm
* @param onExamClick 试卷点击事件
* @receiver
*/
@OptIn(
ExperimentalMaterialApi::class,
)
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun ExamListView(
modifier: Modifier = Modifier,
isReal: Boolean,
viewModel: ExamListViewModel = hiltViewModel(),
onExamClick: (String) -> Unit,
) {
val scrollState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
val firstVisibleItemIndex by remember { derivedStateOf { scrollState.firstVisibleItemIndex } }
val examListPagingItems: LazyPagingItems<ExamListItem> = viewModel.examListState.collectAsLazyPagingItems()
Scaffold(
floatingActionButton = {
AnimatedVisibility(
visible = firstVisibleItemIndex > 10 && scrollState.isScrollingUp(),
enter = slideInVertically { it },
exit = slideOutVertically { it },
modifier = Modifier
.windowInsetsPadding(
LocalScrollAwareWindowInsets.current
.only(WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal)
)
) {
FloatingActionButton(
onClick = {
coroutineScope.launch {
scrollState.animateScrollToItem(0)
}
}
) {
Icon(Icons.Default.KeyboardArrowUp, "back to top")
}
}
},
floatingActionButtonPosition = FabPosition.End,
modifier = modifier,
) {padding ->
val refreshing = when (examListPagingItems.loadState.refresh) {
is LoadState.Loading -> true
else -> false
}
val state = rememberPullRefreshState(refreshing, { examListPagingItems.refresh() })
Box (
modifier = Modifier
.pullRefresh(state)
.padding(bottom = padding.calculateBottomPadding())
){
Column{
LazyColumn(
state = scrollState,
) {
items(examListPagingItems.itemCount) {
if (!isReal)
ListItem(
headlineContent = { Text(getExamNameAndNo(examListPagingItems[it]!!.exam.examname).first) },
trailingContent = { Text(getExamNameAndNo(examListPagingItems[it]!!.exam.examname).second) },
leadingContent = {
Box(
modifier = Modifier
.height(40.dp)
.clip(CircleShape)
.aspectRatio(1f)
.background(MaterialTheme.colorScheme.primaryContainer)
) {
Text(
text = getExamCET6Keyword(examListPagingItems[it]!!.exam.examname),
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier
.align(Alignment.Center)
)
}
},
supportingContent = { examListPagingItems[it]?.lastOpen?.let { time->
DateText(time)
} },
modifier = Modifier
.clickable {
onExamClick(examListPagingItems[it]!!.exam.examid)
}
)
else
ListItem(
headlineContent = { Text(examListPagingItems[it]!!.exam.examname) },
leadingContent = {
Box(
modifier = Modifier
.height(40.dp)
.clip(CircleShape)
.aspectRatio(1f)
.background(MaterialTheme.colorScheme.primaryContainer)
) {
Text(
text = "真题",
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier
.align(Alignment.Center)
)
}
},
supportingContent = { examListPagingItems[it]?.lastOpen?.let { time->
DateText(time)
} },
modifier = Modifier
.clickable {
onExamClick(examListPagingItems[it]!!.exam.examid)
}
)
HorizontalDivider()
}
examListPagingItems.apply {
when {
loadState.refresh is LoadState.Loading -> {
item { PageLoader(modifier = Modifier.fillParentMaxSize()) }
}
loadState.refresh is LoadState.Error -> {
val error = examListPagingItems.loadState.refresh as LoadState.Error
item {
ErrorMessage(
modifier = Modifier.fillParentMaxSize(),
message = error.error.localizedMessage!!,
onClickRetry = { retry() })
}
}
loadState.append is LoadState.Loading -> {
item { LoadingNextPageItem(modifier = Modifier) }
}
loadState.append is LoadState.Error -> {
val error = examListPagingItems.loadState.append as LoadState.Error
item {
ErrorMessage(
modifier = Modifier,
message = error.error.localizedMessage!!,
onClickRetry = { retry() })
}
}
}
}
}
}
PullRefreshIndicator(
refreshing = refreshing,
state = state,
modifier = Modifier.align(Alignment.TopCenter)
)
}
}
}
private fun getExamNameAndNo(text: String):Pair<String,String>{
val result = mutableListOf<String>()
val pattern = Regex("""[0-9]+""")
val matches = pattern.findAll(text)
for(match in matches){
result.add(match.value)
}
return text.split(result.last())[0] to result.last()
}
private fun getExamCET6Keyword(text: String):String{
val keywords = listOf("作文", "阅读", "听力","翻译")
val regex = Regex(keywords.joinToString("|"))
val matches = regex.findAll(text)
matches.forEach {
if (keywords.contains(it.value))return it.value
}
return "模拟"
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/page/ExamListPage.kt | 72554002 |
package app.xlei.vipexam.ui.page
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
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.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowRight
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.R
import app.xlei.vipexam.core.data.constant.ExamType
import app.xlei.vipexam.core.ui.Banner
import app.xlei.vipexam.core.ui.OnError
import app.xlei.vipexam.core.ui.OnLoading
import app.xlei.vipexam.feature.history.HistoryViewModel
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalPinnedExams
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import app.xlei.vipexam.ui.UiState
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.components.ExamSearchBar
import compose.icons.FeatherIcons
import compose.icons.TablerIcons
import compose.icons.feathericons.Clock
import compose.icons.tablericons.Pin
import kotlinx.coroutines.launch
/**
* Exam type list view
* 试卷类型列表
* @param examTypeListUiState 试卷类型列表
* @param onExamTypeClick 试卷类型点击事件
* @param modifier
* @receiver
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ExamTypeListView(
examTypeListUiState: UiState<VipexamUiState.ExamTypeListUiState>,
onExamTypeClick: (ExamType) -> Unit,
onLastViewedClick: (String) -> Unit,
modifier: Modifier = Modifier,
viewModel: HistoryViewModel = hiltViewModel(),
) {
val localPinnedExams = LocalPinnedExams.current
val examTypes =
ExamType.entries.sortedByDescending { localPinnedExams.value.contains(it.examTypeName) }
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
Column(
modifier = modifier
) {
ExamSearchBar(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp)
.padding(bottom = 24.dp)
)
when (examTypeListUiState) {
is UiState.Loading -> {
OnLoading(examTypeListUiState.loadingMessageId)
}
is UiState.Success -> {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
item {
viewModel.examHistory.collectAsState().value.firstOrNull()?.let {
Banner(
title = stringResource(id = R.string.lastViewd),
desc = it.examName,
icon = FeatherIcons.Clock,
action = {
Icon(
imageVector = Icons.AutoMirrored.Outlined.KeyboardArrowRight,
contentDescription = null
)
}
) {
onLastViewedClick.invoke(it.examId)
}
}
}
items(examTypes.size) {
ListItem(
headlineContent = { Text(examTypes[it].examTypeName) },
colors = ListItemDefaults.colors(
containerColor = MaterialTheme.colorScheme.surface,
headlineColor = MaterialTheme.colorScheme.onSurface
),
trailingContent = {
if (examTypes[it].examTypeName == localPinnedExams.value) IconButton(
onClick = {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.PinnedExams,
""
)
}
}) {
Icon(imageVector = TablerIcons.Pin, contentDescription = null)
}
},
modifier = Modifier
.combinedClickable(
onClick = {
onExamTypeClick(ExamType.entries[it])
},
onLongClick = {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.PinnedExams,
examTypes[it].examTypeName
)
}
}
)
)
HorizontalDivider()
}
}
}
is UiState.Error -> {
OnError(
textId = examTypeListUiState.errorMessageId,
error = examTypeListUiState.msg
)
}
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/page/ExamTypeListPage.kt | 4167111728 |
package app.xlei.vipexam.ui.page
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import app.xlei.vipexam.core.data.paging.ExamListItem
import app.xlei.vipexam.core.data.paging.GetExamListUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Exam list view model
* 事件列表vm
* @property getExamListUseCase 获得试卷列表vm
* @constructor Create empty Exam list view model
*/
@HiltViewModel
class ExamListViewModel @Inject constructor(
private val getExamListUseCase: GetExamListUseCase,
) : ViewModel() {
private val _examListState: MutableStateFlow<PagingData<ExamListItem>> = MutableStateFlow(value = PagingData.empty())
val examListState: MutableStateFlow<PagingData<ExamListItem>> get() = _examListState
init {
viewModelScope.launch {
getExamList()
}
}
private suspend fun getExamList() {
getExamListUseCase.execute(Unit)
.distinctUntilChanged()
.cachedIn(viewModelScope)
.collect {
_examListState.value = it
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/page/ExamListViewModel.kt | 500961858 |
package app.xlei.vipexam.ui.page
import android.annotation.SuppressLint
import androidx.compose.animation.core.*
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import app.xlei.vipexam.core.network.module.NetWorkRepository.getQuestions
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalShowAnswerOption
import app.xlei.vipexam.preference.LocalVibrate
import app.xlei.vipexam.preference.ShowAnswerOptionPreference
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import app.xlei.vipexam.template.Render
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.components.CustomFloatingActionButton
import app.xlei.vipexam.ui.question.*
import app.xlei.vipexam.ui.question.cloze.clozeView
import app.xlei.vipexam.ui.question.listening.ListeningView
import app.xlei.vipexam.ui.question.qread.QreadView
import app.xlei.vipexam.ui.question.translate.TranslateView
import app.xlei.vipexam.ui.question.writing.WritingView
import app.xlei.vipexam.ui.question.zread.ZreadView
import kotlinx.coroutines.launch
/**
* Exam page
* 试卷页面
* @param modifier
* @param questionListUiState 问题列表状态
* @param viewModel 问题列表vm
* @param setQuestion 问题点击事件
* @param navController 导航控制器
* @param showFab 显示按钮
* @receiver
*/
@Composable
fun ExamPage(
modifier: Modifier = Modifier,
questionListUiState: VipexamUiState.QuestionListUiState,
viewModel: QuestionsViewModel = hiltViewModel(),
setQuestion: (String, GetExamResponse) -> Unit,
navController: NavHostController,
showFab: Boolean = true,
submitMyAnswer: (String, String) -> Unit
) {
val context = LocalContext.current
val vibrate = LocalVibrate.current
val showAnswerOption = LocalShowAnswerOption.current
val haptics = LocalHapticFeedback.current
viewModel.setMubanList(mubanList = questionListUiState.exam.muban)
val uiState by viewModel.uiState.collectAsState()
val coroutine = rememberCoroutineScope()
val questions = getQuestions(uiState.mubanList!!)
if (questions.isNotEmpty())
Questions(
mubanList = questionListUiState.exam.muban,
question = if (questions.toMap().containsKey(questionListUiState.question)) {
questionListUiState.question!!
} else {
questions.first().first
},
questions = questions,
navController = navController,
setQuestion = { question ->
setQuestion(
question,
questionListUiState.exam,
)
},
modifier = modifier,
submitMyAnswer = submitMyAnswer
) {
if (showFab)
CustomFloatingActionButton(
expandable = true,
onFabClick = {
if (vibrate.isVibrate()) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
iconExpanded = Icons.Filled.KeyboardArrowDown,
iconUnExpanded = Icons.Filled.KeyboardArrowUp,
items = questions,
onItemClick = {
navController.navigate(it) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
if (vibrate.isVibrate()) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
if (showAnswerOption == ShowAnswerOptionPreference.Once) {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.ShowAnswer,
false
)
}
}
}
)
}
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun Questions(
modifier: Modifier = Modifier,
mubanList: List<Muban>,
question: String,
questions: List<Pair<String, String>>,
navController: NavHostController,
setQuestion: (String) -> Unit,
submitMyAnswer: (String, String) -> Unit,
FAB: @Composable () -> Unit,
) {
Scaffold(
floatingActionButton = FAB,
modifier = modifier
) {
Column(
modifier = Modifier
.fillMaxSize()
) {
NavHost(
navController = navController,
startDestination = question,
modifier = Modifier
.fillMaxSize()
) {
for ((index, q) in questions.withIndex()) {
composable(route = q.first) {
setQuestion(mubanList[index].cname)
QuestionMapToView(
question = q.first,
muban = mubanList[index],
submitMyAnswer = submitMyAnswer
)
}
}
}
}
}
}
/**
* Question map to view
* 根据问题类型切换不同的显示方式
* @param question 问题
* @param muban 模板
*/
@Composable
fun QuestionMapToView(
question: String,
muban: Muban,
submitMyAnswer: (String, String) -> Unit,
) {
return when (question) {
"ecswriting" -> WritingView(muban = muban)
"ecscloze" -> clozeView(muban = muban, submitMyAnswer = submitMyAnswer)
"ecsqread" -> QreadView(muban = muban, submitMyAnswer = submitMyAnswer)
"ecszread" -> ZreadView(muban = muban, submitMyAnswer = submitMyAnswer)
"ecstranslate" -> TranslateView(muban = muban)
"ecfwriting" -> WritingView(muban = muban)
"ecfcloze" -> clozeView(muban = muban, submitMyAnswer = submitMyAnswer)
"ecfqread" -> QreadView(muban = muban, submitMyAnswer = submitMyAnswer)
"ecfzread" -> ZreadView(muban = muban, submitMyAnswer = submitMyAnswer)
"ecftranslate" -> TranslateView(muban = muban)
"eylhlisteninga" -> ListeningView(muban = muban, submitMyAnswer = submitMyAnswer)
"eylhlisteningb" -> ListeningView(muban = muban, submitMyAnswer = submitMyAnswer)
"eylhlisteningc" -> ListeningView(muban = muban, submitMyAnswer = submitMyAnswer)
"kettrans" -> TranslateView(muban = muban)
"ketwrite" -> WritingView(muban = muban)
else -> Render(question = question, muban = muban, submitMyAnswer = submitMyAnswer)
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/page/ExamPage.kt | 472295559 |
package app.xlei.vipexam.ui.page
import androidx.compose.foundation.clickable
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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.R
import app.xlei.vipexam.core.database.module.User
import app.xlei.vipexam.core.network.module.login.LoginResponse
/**
* Login screen
*
* @param modifier
* @param account 账号
* @param password 密码
* @param users 用户列表
* @param loginResponse 登录事件响应
* @param onAccountChange 输入账号改变事件
* @param onPasswordChange 输入密码改变事件
* @param onDeleteUser 删除用户事件
* @param onLoginButtonClicked 登录按钮点击事件
* @receiver
* @receiver
* @receiver
* @receiver
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(
modifier: Modifier = Modifier,
account: String,
password: String,
users: List<User>,
loginResponse: LoginResponse?,
onAccountChange: (String) -> Unit,
onPasswordChange: (String) -> Unit,
onDeleteUser: (User) -> Unit,
onLoginButtonClicked: () -> Unit,
) {
var showUsers by remember { mutableStateOf(false) }
Column(
modifier = modifier
.fillMaxSize()
) {
Column(
modifier = Modifier
.weight(3f)
.align(Alignment.CenterHorizontally)
.padding(horizontal = 24.dp)
) {
ExposedDropdownMenuBox(
expanded = showUsers,
onExpandedChange = { showUsers = true }
) {
OutlinedTextField(
value = account,
onValueChange = onAccountChange,
label = { Text(stringResource(R.string.account)) },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = showUsers)
},
modifier = Modifier
.fillMaxWidth()
.menuAnchor(),
shape = RoundedCornerShape(8.dp),
)
ExposedDropdownMenu(
expanded = showUsers,
onDismissRequest = { showUsers = false }
) {
users.forEach {
DropdownMenuItem(
text = { Text(it.account) },
trailingIcon = {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "delete user",
modifier = Modifier
.clickable {
onDeleteUser(it)
}
)
},
onClick = {
onAccountChange(it.account)
onPasswordChange(it.password)
showUsers = false
},
modifier = Modifier
.fillMaxWidth()
)
}
}
}
OutlinedTextField(
value = password,
onValueChange = onPasswordChange,
label = { Text(stringResource(R.string.password)) },
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier
.padding(top = 20.dp)
.fillMaxWidth(),
shape = RoundedCornerShape(8.dp),
)
if (loginResponse != null) {
Text(loginResponse.msg)
}
Button(
onClick = onLoginButtonClicked,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 20.dp)
) {
Text(stringResource(R.string.login))
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/page/LoginPage.kt | 3077017272 |
package app.xlei.vipexam.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.xlei.vipexam.R
import app.xlei.vipexam.core.data.constant.ExamType
import app.xlei.vipexam.core.data.paging.ExamListApi
import app.xlei.vipexam.core.data.repository.ExamHistoryRepository
import app.xlei.vipexam.core.database.module.User
import app.xlei.vipexam.core.domain.AddUserUseCase
import app.xlei.vipexam.core.domain.DeleteUserUseCase
import app.xlei.vipexam.core.domain.GetAllUsersUseCase
import app.xlei.vipexam.core.network.module.NetWorkRepository
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import app.xlei.vipexam.ui.appbar.AppBarTitle
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
/**
* Vip exam main screen view model
*
* @property getAllUsersUseCase
* @property addUserUseCase
* @property deleteUserUseCase
* @property examHistoryRepository
* @constructor
*
* @param vipexamUiState
*/
@HiltViewModel
class VipExamMainScreenViewModel @Inject constructor(
vipexamUiState: VipexamUiState,
private val getAllUsersUseCase: GetAllUsersUseCase,
private val addUserUseCase: AddUserUseCase,
private val deleteUserUseCase: DeleteUserUseCase,
private val examHistoryRepository: ExamHistoryRepository,
) : ViewModel() {
private val _uiState = MutableStateFlow(vipexamUiState)
val uiState: StateFlow<VipexamUiState> = _uiState.asStateFlow()
private val _myAnswer = MutableStateFlow(mutableMapOf<String, String>())
val myAnswer
get() = _myAnswer.asStateFlow()
init {
_uiState.update {
it.copy(
loginUiState = UiState.Loading(R.string.loading)
)
}
viewModelScope.launch {
withContext(Dispatchers.IO) {
val users = getAllUsersUseCase()
users.collect { usersList ->
_uiState.update {
it.copy(
loginUiState = UiState.Success(
uiState = VipexamUiState.LoginUiState(
account = usersList.firstOrNull()?.account ?: "",
password = usersList.firstOrNull()?.password ?: "",
loginResponse = null,
users = users,
)
)
)
}
}
}
}
}
/**
* Login
*
*/
fun login(organization: String) {
_uiState.update {
it.copy(
examTypeListUiState = UiState.Loading(R.string.loading)
)
}
viewModelScope.launch {
val loginUiState = (_uiState.value.loginUiState as UiState.Success).uiState
NetWorkRepository.getToken(
account = loginUiState.account,
password = loginUiState.password,
organization = organization,
).onSuccess { loginResponse ->
_uiState.update {
it.copy(
examTypeListUiState = UiState.Success(
uiState = VipexamUiState.ExamTypeListUiState(
examListUiState = UiState.Loading(R.string.loading)
),
),
loginUiState = UiState.Success(
uiState = loginUiState.copy(
loginResponse = loginResponse
)
),
)
}
addCurrentUser()
}.onFailure { error ->
_uiState.update {
it.copy(
examTypeListUiState = UiState.Error(
errorMessageId = R.string.login_error,
msg = error.message
)
)
}
return@launch
}
}
}
/**
* Add current user
* 记录成功登录的账号
*/
private fun addCurrentUser() {
viewModelScope.launch {
val loginUiState = (_uiState.value.loginUiState as UiState.Success).uiState
addUserUseCase(
User(
account = loginUiState.account,
password = loginUiState.password,
)
)
}
}
/**
* Set account
*
* @param account
*/
fun setAccount(account: String) {
val loginUiState = (_uiState.value.loginUiState as UiState.Success).uiState
_uiState.update {
it.copy(
loginUiState = UiState.Success(
loginUiState.copy(
account = account,
),
)
)
}
}
/**
* Set password
*
* @param password
*/
fun setPassword(password: String) {
val loginUiState = (_uiState.value.loginUiState as UiState.Success).uiState
_uiState.update {
it.copy(
loginUiState = UiState.Success(
loginUiState.copy(
password = password,
),
)
)
}
}
/**
* Set exam type
*
* @param type
*/
fun setExamType(type: ExamType) {
ExamListApi.setType(type)
val examTypeListUiState =
(_uiState.value.examTypeListUiState as UiState.Success).uiState
val examListUiState = UiState.Success(
uiState = VipexamUiState.ExamListUiState(
isReal = type.isReal,
questionListUiState = UiState.Loading(R.string.loading)
)
)
_uiState.update {
it.copy(
examTypeListUiState = UiState.Success(
examTypeListUiState.copy(
examListUiState = examListUiState
),
),
examListUiState = examListUiState
)
}
}
/**
* Set title
*
* @param title
*/
fun setTitle(title: AppBarTitle) {
_uiState.update {
it.copy(
title = title
)
}
}
/**
* Set question
*
* @param examName
* @param examId
* @param question
*/
fun setQuestion(
question: String,
exam: GetExamResponse,
) {
val questionListUiState =
(_uiState.value.questionListUiState as UiState.Success<VipexamUiState.QuestionListUiState>).uiState
_uiState.update {
it.copy(
questionListUiState = UiState.Success(
questionListUiState.copy(
question = question,
)
),
title = AppBarTitle.Exam(
question = question,
exam = exam,
)
)
}
}
/**
* Delete user
*
* @param user
*/
fun deleteUser(user: User) {
viewModelScope.launch {
deleteUserUseCase(user)
}
}
/**
* Set exam
*
* @param examId
*/
suspend fun setExam(examId: String) {
_uiState.update {
it.copy(
questionListUiState = UiState.Loading(R.string.loading)
)
}
NetWorkRepository.getExam(examId)
.onSuccess { exam ->
when (val _questionListUiState = _uiState.value.questionListUiState) {
is UiState.Success -> {
_uiState.update {
it.copy(
questionListUiState = UiState.Success(
_questionListUiState.uiState.copy(
exam = exam,
questions = NetWorkRepository.getQuestions(exam.muban)
)
),
)
}
}
else -> {
val questionListUiState = when {
exam.count > 0 -> {
UiState.Success(
VipexamUiState.QuestionListUiState(
exam = exam,
questions = NetWorkRepository.getQuestions(exam.muban),
question = exam.muban.map { muban ->
muban.ename
}.first()
)
)
}
else -> {
UiState.Error(R.string.unknown_error, exam.msg)
}
}
_uiState.update {
it.copy(
questionListUiState = questionListUiState,
)
}
}
}
if (exam.count > 0)
withContext(Dispatchers.IO) {
examHistoryRepository.insertHistory(
examName = exam.examName,
examId = examId
)
}
}.onFailure {
_uiState.update {
it.copy(
questionListUiState = UiState.Error(R.string.internet_error)
)
}
return
}
}
fun submitMyAnswer(questionCode: String, myAnswer: String) {
_myAnswer.value[questionCode] = myAnswer
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/VipExamMainScreenViewModel.kt | 1479435027 |
package app.xlei.vipexam.ui
import android.content.res.Configuration
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.rememberDrawerState
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import app.xlei.vipexam.R
import app.xlei.vipexam.ui.components.AppDrawer
import app.xlei.vipexam.ui.components.AppNavRail
import app.xlei.vipexam.ui.navigation.AppDestinations
import app.xlei.vipexam.ui.navigation.VipExamNavHost
import kotlinx.coroutines.launch
/**
* App
*
* @param widthSizeClass 屏幕宽度
* @param appState
*/
@Composable
fun App(
widthSizeClass: WindowWidthSizeClass,
appState: VipExamState,
) {
val homeNavController = rememberNavController()
val navBackStackEntry by appState.navController.currentBackStackEntryAsState()
val currentRoute =
navBackStackEntry?.destination?.route ?: AppDestinations.HOME_ROUTE.name
val sizeAwareDrawerState = rememberSizeAwareDrawerState(appState.shouldShowTopBar)
val coroutine = rememberCoroutineScope()
val snackBarHostState = remember { SnackbarHostState() }
val isOffline by appState.isOffline.collectAsState()
val notConnectedMessage = stringResource(R.string.not_connected)
val configuration = LocalConfiguration.current
LaunchedEffect(isOffline) {
if (isOffline) {
snackBarHostState.showSnackbar(
message = notConnectedMessage,
duration = SnackbarDuration.Indefinite,
)
}
}
// consider replace with material3/adaptive/navigationsuite
Scaffold(
containerColor = MaterialTheme.colorScheme.surfaceContainer,
snackbarHost = { SnackbarHost(snackBarHostState) },
) { padding ->
ModalNavigationDrawer(
drawerContent = {
AppDrawer(
currentRoute = currentRoute,
navigationToTopLevelDestination = { appState.navigateToAppDestination(it) },
closeDrawer = { coroutine.launch { sizeAwareDrawerState.close() } },
modifier = Modifier
.width(300.dp)
)
},
drawerState = sizeAwareDrawerState,
gesturesEnabled = appState.shouldShowTopBar ||
appState.shouldShowAppDrawer && configuration.orientation == Configuration.ORIENTATION_PORTRAIT,
modifier = Modifier
.padding(padding)
.consumeWindowInsets(padding)
) {
Row (
modifier = Modifier
.fillMaxSize()
){
when (configuration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
if (appState.shouldShowAppDrawer)
AppDrawer(
currentRoute = currentRoute,
navigationToTopLevelDestination = { appState.navigateToAppDestination(it) },
closeDrawer = {},
modifier = Modifier
.width(300.dp)
.padding(top = 24.dp)
)
}
else -> {
if (appState.shouldShowNavRail) {
AppNavRail(
homeNavController = homeNavController,
currentRoute = currentRoute,
navigationToTopLevelDestination = { appState.navigateToAppDestination(it) },
)
}
}
}
VipExamNavHost(
navHostController = appState.navController,
homeNavController = homeNavController,
widthSizeClass = widthSizeClass,
openDrawer = {
if (appState.shouldShowAppDrawer.not() || configuration.orientation == Configuration.ORIENTATION_PORTRAIT)
coroutine.launch {
sizeAwareDrawerState.open()
}
},
modifier = Modifier
.run {
if (appState.shouldShowAppDrawer && configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
clip(MaterialTheme.shapes.extraLarge)
else
this
}
.fillMaxSize()
)
}
}
}
}
@Composable
private fun rememberSizeAwareDrawerState(isExpandedScreen: Boolean): DrawerState {
val drawerState = rememberDrawerState(DrawerValue.Closed)
return if (!isExpandedScreen) {
drawerState
} else {
DrawerState(DrawerValue.Closed)
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/VipExamApp.kt | 3610352835 |
package app.xlei.vipexam.ui.navigation
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.Icon
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import app.xlei.vipexam.core.network.module.NetWorkRepository
import app.xlei.vipexam.feature.bookmarks.BookmarksScreen
import app.xlei.vipexam.feature.history.HistoryScreen
import app.xlei.vipexam.feature.settings.SettingsScreen
import app.xlei.vipexam.feature.wordlist.WordListScreen
import app.xlei.vipexam.ui.VipExamMainScreenViewModel
import app.xlei.vipexam.ui.screen.HomeScreen
/**
* Vip exam nav host
*
* @param logoText logo
* @param navHostController app导航控制器
* @param homeNavController 主页导航控制器
* @param widthSizeClass 屏幕宽度
* @param openDrawer 打开抽屉事件
* @receiver
* @receiver
*/
@Composable
fun VipExamNavHost(
modifier: Modifier = Modifier,
logoText: @Composable () -> Unit = {},
navHostController: NavHostController,
homeNavController: NavHostController,
widthSizeClass: WindowWidthSizeClass,
openDrawer: () -> Unit,
) {
val viewModel : VipExamMainScreenViewModel = hiltViewModel()
NavHost(
navController = navHostController,
startDestination = AppDestinations.HOME_ROUTE.name,
modifier = modifier
) {
composable(
route = AppDestinations.HOME_ROUTE.name,
) {
HomeScreen(
logoText = { Icon(imageVector = Icons.Default.Home, contentDescription = null) },
widthSizeClass = widthSizeClass,
navController = homeNavController,
viewModel = viewModel,
openDrawer = openDrawer,
modifier = Modifier
.fillMaxSize()
)
}
composable(
route = AppDestinations.SECOND_ROUTE.name,
) { _ ->
WordListScreen(
openDrawer = openDrawer,
modifier = Modifier
.fillMaxSize()
)
}
composable(
route = AppDestinations.SETTINGS_ROUTE.name,
) { _ ->
SettingsScreen(
openDrawer = openDrawer,
modifier = Modifier
.fillMaxSize()
)
}
composable(
route = AppDestinations.BOOKMARKS.name
){
BookmarksScreen(
openDrawer = openDrawer,
modifier = Modifier
.fillMaxSize()
){examId,question->
when (NetWorkRepository.isAvailable()) {
true -> {
navHostController.navigate(AppDestinations.HOME_ROUTE.name){
popUpTo(navHostController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
homeNavController.navigate(Screen.Question.createRoute(examId,question)){
launchSingleTop = true
}
true
}
false -> false
}
}
}
composable(
route = AppDestinations.HISTORY.name
){
HistoryScreen(
openDrawer = openDrawer,
onHistoryClick = {
when (NetWorkRepository.isAvailable()) {
true -> {
navHostController.navigate(AppDestinations.HOME_ROUTE.name){
popUpTo(navHostController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
homeNavController.navigate(Screen.Exam.createRoute(it)){
launchSingleTop = true
restoreState = true
}
true
}
false -> false
}
},
modifier = Modifier
.fillMaxSize()
)
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/navigation/VipExamNavHost.kt | 2215894241 |
package app.xlei.vipexam.ui.navigation
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Settings
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import app.xlei.vipexam.R
import compose.icons.FeatherIcons
import compose.icons.feathericons.Bookmark
/**
* App destinations
* 导航栏的按钮,按出现顺序排列
* @property title 显示的标题
* @property icon 显示的图标
* @constructor Create empty App destinations
*/
enum class AppDestinations(@StringRes val title: Int, val icon: ImageVector) {
HOME_ROUTE(title = R.string.main, icon = Icons.Filled.Home),
SECOND_ROUTE(title = R.string.word, icon = Icons.Filled.Edit),
HISTORY(title = R.string.history, icon = Icons.Filled.DateRange),
BOOKMARKS(title = R.string.bookmarks, icon = FeatherIcons.Bookmark),
SETTINGS_ROUTE(title = R.string.settings, icon = Icons.Filled.Settings),
}
/**
* Vip exam navigation actions
* app导航事件
* @constructor
*
* @param navController
*/
class VipExamNavigationActions(navController: NavController) {
val navigateToHome: () -> Unit = {
navController.navigate(AppDestinations.HOME_ROUTE.name) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
val navigateToWords: () -> Unit = {
navController.navigate(AppDestinations.SECOND_ROUTE.name) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
val navigateToSettings: () -> Unit = {
navController.navigate(AppDestinations.SETTINGS_ROUTE.name) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
val navigateToHistory: () -> Unit = {
navController.navigate(AppDestinations.HISTORY.name) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
val navigateToBookmarks: () -> Unit = {
navController.navigate(AppDestinations.BOOKMARKS.name) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/navigation/VipExamNavigation.kt | 3366444535 |
package app.xlei.vipexam.ui.navigation
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
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.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.navigation.NamedNavArgument
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import app.xlei.vipexam.R
import app.xlei.vipexam.core.network.module.NetWorkRepository
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import app.xlei.vipexam.core.ui.OnError
import app.xlei.vipexam.core.ui.OnLoading
import app.xlei.vipexam.preference.LocalOrganization
import app.xlei.vipexam.ui.UiState
import app.xlei.vipexam.ui.VipExamMainScreenViewModel
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.appbar.AppBarTitle
import app.xlei.vipexam.ui.page.LoginScreen
import app.xlei.vipexam.ui.page.QuestionMapToView
import app.xlei.vipexam.ui.screen.ExamListScreen
import app.xlei.vipexam.ui.screen.ExamScreen
import app.xlei.vipexam.ui.screen.ExamTypeListScreen
import kotlinx.coroutines.launch
/**
* Main screen navigation
*
* @param modifier
* @param navHostController 主页导航控制器,在主页页面之间跳转
* @param viewModel 主页vm
* @param widthSizeClass 用于根据屏幕宽度切换显示内容
*/
@Composable
fun MainScreenNavigation(
modifier: Modifier = Modifier,
navHostController: NavHostController,
viewModel: VipExamMainScreenViewModel,
widthSizeClass: WindowWidthSizeClass,
){
val organization = LocalOrganization.current
val uiState by viewModel.uiState.collectAsState()
val coroutine = rememberCoroutineScope()
NavHost(
navController = navHostController,
startDestination = Screen.Login.route,
modifier = modifier
.fillMaxSize(), // must add this to avoid weird navigation animation
){
slideInSlideOutNavigationContainer(
route = Screen.Login.route,
){
viewModel.setTitle(AppBarTitle.Login)
when (uiState.loginUiState) {
is UiState.Loading -> {
OnLoading()
}
is UiState.Success -> {
val loginUiState = (uiState.loginUiState as UiState.Success<VipexamUiState.LoginUiState>).uiState
LoginScreen(
account = loginUiState.account,
password = loginUiState.password,
users = loginUiState.users.collectAsState(initial = emptyList()).value,
loginResponse = loginUiState.loginResponse,
onAccountChange = viewModel::setAccount,
onPasswordChange = viewModel::setPassword,
onDeleteUser = viewModel::deleteUser,
onLoginButtonClicked = {
coroutine.launch {
viewModel.login(organization.value)
navHostController.navigate(Screen.ExamTypeList.route)
}
},
modifier = Modifier
.fillMaxSize()
)
}
is UiState.Error -> {
OnError()
}
}
}
slideInSlideOutNavigationContainer(
route = Screen.ExamTypeList.route,
){
viewModel.setTitle(AppBarTitle.ExamType)
Column(
modifier = Modifier
.fillMaxSize()
) {
ExamTypeListScreen(
examTypeListUiState = uiState.examTypeListUiState,
onExamTypeClick = {
viewModel.setExamType(it)
navHostController.navigate(Screen.ExamList.createRoute(it.name))
},
widthSizeClass = widthSizeClass,
onLastViewedClick = {
navHostController.navigate(Screen.Exam.createRoute(it))
},
modifier = Modifier
.fillMaxSize()
)
}
}
slideInSlideOutNavigationContainer(
route = Screen.ExamList.route,
arguments = Screen.ExamList.navArguments,
){
viewModel.setTitle(AppBarTitle.ExamList)
ExamListScreen(
examListUiState = uiState.examListUiState,
onLastExamClick = { navHostController.navigate(Screen.Exam.route) },
onExamClick = {
coroutine.launch {
navHostController.navigate(Screen.Exam.createRoute(it))
}
},
widthSizeClass = widthSizeClass,
modifier = Modifier
.fillMaxSize()
)
}
slideInSlideOutNavigationContainer(
route = Screen.Exam.route,
arguments = Screen.Exam.navArguments,
) { backStackEntry ->
LaunchedEffect(key1 = Unit, block = {
backStackEntry.arguments?.let { bundle ->
bundle.getString(Screen.Question.navArguments[0].name)?.let {examId->
coroutine.launch {
uiState.questionListUiState.let {
when (it) {
is UiState.Success -> {
it.uiState.exam.let {exam->
if (exam.examID != examId)
viewModel.setExam(examId)
}
}
else -> {
viewModel.setExam(examId)
}
}
}
}
}
}
})
when (uiState.questionListUiState) {
is UiState.Loading -> {
OnLoading((uiState.questionListUiState as UiState.Loading).loadingMessageId)
}
is UiState.Success -> {
val questionListUiState = (uiState.questionListUiState as UiState.Success<VipexamUiState.QuestionListUiState>).uiState
questionListUiState.question?.let {
AppBarTitle.Exam(
it,
questionListUiState.exam
)
}?.let {
viewModel.setTitle(it)
}
ExamScreen(
questionListUiState = questionListUiState,
setQuestion = viewModel::setQuestion,
widthSizeClass = widthSizeClass,
submitMyAnswer = viewModel::submitMyAnswer,
modifier = Modifier
.fillMaxSize(),
onExamClick = {
navHostController.navigate(Screen.Exam.createRoute(it))
}
)
}
is UiState.Error -> {
uiState.questionListUiState.let {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource((it as UiState.Error).errorMessageId),
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
it.msg?.let {
Text(
text = it,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
}
}
}
}
slideInSlideOutNavigationContainer(
route = Screen.Question.route,
arguments = Screen.Question.navArguments
) { backStackEntry ->
var exam by remember {
mutableStateOf<GetExamResponse?>(null)
}
var question by remember {
mutableStateOf<String?>(null)
}
backStackEntry.arguments?.let { bundle ->
bundle.getString(Screen.Question.navArguments[0].name)?.let {
if (exam == null)
coroutine.launch {
NetWorkRepository.getExam(it)
.onSuccess {
exam = it
}
}
}
bundle.getString(Screen.Question.navArguments[1].name)?.let {
if (question == null)
question = it
}
}
if (exam!=null) {
when {
exam!!.count > 0 -> {
question?.let { q ->
viewModel.setTitle(
AppBarTitle.Exam(
question = q,
exam = exam!!
)
)
Column(
modifier = Modifier
.fillMaxSize()
) {
exam!!.muban.firstOrNull { it.cname == question }.let {
when (it) {
null -> {
OnError(
textId = R.string.internet_error,
error = stringResource(
id = R.string.resource_not_exist
)
)
}
else -> {
QuestionMapToView(
question = it.ename,
muban = it,
submitMyAnswer = viewModel::submitMyAnswer
)
}
}
}
}
}
}
else -> {
OnError(textId = R.string.unknown_error, error = exam!!.msg)
}
}
} else {
OnLoading()
}
}
}
}
private fun NavGraphBuilder.slideInSlideOutNavigationContainer(
route: String,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
content: @Composable AnimatedVisibilityScope.(NavBackStackEntry) -> Unit){
return composable(
route = route,
arguments = arguments,
deepLinks = deepLinks,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(200)
)
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(200)
)
},
popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(200)
)
},
popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(200)
)
},
content = content
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/navigation/HomeScreenNavigation.kt | 3998086491 |
package app.xlei.vipexam.ui.navigation
import androidx.navigation.NamedNavArgument
import androidx.navigation.NavType
import androidx.navigation.navArgument
/**
* Screen
* 主页页面
* @property route
* @property navArguments
* @constructor Create empty Screen
*/
sealed class Screen(
val route: String,
val navArguments: List<NamedNavArgument> = emptyList()
) {
data object Login : Screen("login")
data object ExamTypeList : Screen(
route = "examTypeList",
)
data object ExamList : Screen(
route = "examList/{examType}",
navArguments = listOf(navArgument("examType") {
type = NavType.StringType
})
) {
fun createRoute(examType: String) = "examList/${examType}"
}
data object Exam : Screen(
route = "exam/{examId}",
navArguments = listOf(navArgument("examId") {
type = NavType.StringType
})
){
fun createRoute(examId: String) = "exam/${examId}"
}
data object Question : Screen(
route = "question/{examId}/{questionName}",
navArguments = listOf(
navArgument("examId") {
type = NavType.StringType
},
navArgument("questionName") {
type = NavType.StringType
},
)
){
fun createRoute(examId: String, question: String) = "question/${examId}/${question}"
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/navigation/Screen.kt | 3954793145 |
package app.xlei.vipexam.ui.question.zread
import androidx.compose.runtime.MutableState
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class ZreadUiState(
val muban: Muban?=null,
var showBottomSheet: Boolean = false,
var showQuestionsSheet: Boolean = false,
val articles: List<Article>,
){
data class Article(
val index: String,
val content: String,
val questions: List<Question>,
val options: List<String> = listOf("A","B","C","D")
)
data class Question(
val index: String,
val question: String,
val options: List<Option>,
val choice: MutableState<String>,
val refAnswer: String,
val description: String,
)
data class Option(
val index: String,
val option: String,
)
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/question/zread/ZreadUiState.kt | 3908994442 |
package app.xlei.vipexam.ui.question.zread
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Children
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class ZreadViewModel @Inject constructor(
zreadUiState: ZreadUiState,
) : ViewModel() {
private val _uiState = MutableStateFlow(zreadUiState)
val uiState: StateFlow<ZreadUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban
)
}
}
@Composable
fun SetArticles() {
val articles = mutableListOf<ZreadUiState.Article>()
_uiState.value.muban!!.shiti.forEachIndexed {index,it->
articles.add(
ZreadUiState.Article(
index = "${index + 1}",
content = it.primQuestion,
questions = getQuestions(it.children)
)
)
}
_uiState.update {
it.copy(
articles = articles
)
}
}
@Composable
private fun getQuestions(children: List<Children>): MutableList<ZreadUiState.Question> {
val questions = mutableListOf<ZreadUiState.Question>()
children.forEachIndexed { index, it ->
val options = mutableListOf<String>()
options.add(it.first)
options.add(it.second)
options.add(it.third)
options.add(it.fourth)
questions.add(
ZreadUiState.Question(
index = "${index + 1}",
question = it.secondQuestion,
options = getOptions(it),
choice = rememberSaveable { mutableStateOf("") },
refAnswer = it.refAnswer,
description = it.discription,
)
)
}
return questions
}
private fun getOptions(children: Children): MutableList<ZreadUiState.Option> {
val options = mutableListOf<ZreadUiState.Option>()
options.add(
ZreadUiState.Option(
index = "A",
option = children.first,
)
)
options.add(
ZreadUiState.Option(
index = "B",
option = children.second,
)
)
options.add(
ZreadUiState.Option(
index = "C",
option = children.third,
)
)
options.add(
ZreadUiState.Option(
index = "D",
option = children.fourth,
)
)
return options
}
fun setOption(selectedArticleIndex: Int, selectedQuestionIndex: Int, option: String) {
_uiState.value.articles[selectedArticleIndex].questions[selectedQuestionIndex].choice.value = option
}
fun toggleBottomSheet() {
_uiState.update {
it.copy(
showBottomSheet = !it.showBottomSheet
)
}
}
fun toggleQuestionsSheet() {
_uiState.update {
it.copy(
showQuestionsSheet = !it.showQuestionsSheet
)
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/zread/ZreadViewModel.kt | 3155564731 |
package app.xlei.vipexam.ui.question.zread
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
@Composable
fun ZreadView(
submitMyAnswer: (String, String) -> Unit,
muban: Muban,
viewModel: ZreadViewModel = hiltViewModel(),
){
viewModel.setMuban(muban)
viewModel.SetArticles()
val uiState by viewModel.uiState.collectAsState()
val haptics = LocalHapticFeedback.current
var selectedQuestionIndex by rememberSaveable { mutableIntStateOf(0) }
Zread(
articles = uiState.articles,
showBottomSheet = uiState.showBottomSheet,
showQuestionsSheet = uiState.showQuestionsSheet,
toggleBottomSheet = viewModel::toggleBottomSheet,
toggleQuestionsSheet = viewModel::toggleQuestionsSheet,
onArticleLongClick = {
selectedQuestionIndex = it
haptics.performHapticFeedback(hapticFeedbackType = HapticFeedbackType.LongPress)
},
onQuestionClicked = {
selectedQuestionIndex = it
viewModel.toggleBottomSheet()
haptics.performHapticFeedback(hapticFeedbackType = HapticFeedbackType.LongPress)
},
onOptionClicked = { selectedArticleIndex, option ->
submitMyAnswer(
muban.shiti[selectedArticleIndex].children[selectedQuestionIndex].questionCode,
option
)
viewModel.setOption(selectedArticleIndex, selectedQuestionIndex, option)
viewModel.toggleBottomSheet()
haptics.performHapticFeedback(hapticFeedbackType = HapticFeedbackType.LongPress)
},
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun Zread(
articles: List<ZreadUiState.Article>,
showBottomSheet: Boolean,
showQuestionsSheet: Boolean,
toggleBottomSheet: () -> Unit,
toggleQuestionsSheet: () -> Unit,
onArticleLongClick: (Int) -> Unit,
onQuestionClicked: (Int) -> Unit,
onOptionClicked: (Int, String) -> Unit,
){
val showAnswer = LocalShowAnswer.current.isShowAnswer()
val scrollState = rememberLazyListState()
var selectedArticle by rememberSaveable { mutableIntStateOf(0) }
Column {
LazyColumn(
state = scrollState,
) {
articles.forEachIndexed { articleIndex, ti ->
item {
VipexamArticleContainer(
onArticleLongClick = {
selectedArticle = articleIndex
onArticleLongClick(articleIndex)
toggleQuestionsSheet.invoke()
},
onDragContent = articles[articleIndex].content
+ "\n" + articles[articleIndex].questions.joinToString("") { it ->
"\n\n${it.index}. ${it.question}" + "\n" + it.options.joinToString("\n") { "[${it.index}] ${it.option}" }
}
) {
Column(
modifier = Modifier
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
) {
Text(ti.index)
Text(
text = ti.content,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier
.padding(16.dp)
)
}
}
HorizontalDivider(
modifier = Modifier
.padding(start = 16.dp, end = 16.dp),
thickness = 1.dp,
color = Color.Gray
)
}
items(ti.questions.size){index->
VipexamArticleContainer {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
selectedArticle = articleIndex
onQuestionClicked(index)
}
) {
Column(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = "${ti.questions[index].index}. "+ti.questions[index].question,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.Bold
)
HorizontalDivider(
modifier = Modifier
.padding(start = 16.dp, end = 16.dp),
thickness = 1.dp,
color = Color.Gray
)
ti.questions[index].options.forEach { option ->
Text(
text = "[${option.index}]" + option.option,
color = MaterialTheme.colorScheme.onPrimaryContainer,
)
}
if (ti.questions[index].choice.value != "")
SuggestionChip(
onClick = {},
label = { Text(ti.questions[index].choice.value) }
)
}
}
if (showAnswer)
articles[articleIndex].questions[index].let {
Text(
text = "${it.index}." + it.refAnswer,
modifier = Modifier
.padding(horizontal = 24.dp)
)
Text(
text = it.description,
modifier = Modifier
.padding(horizontal = 24.dp)
)
}
}
}
}
}
if (showBottomSheet) {
ModalBottomSheet(
onDismissRequest = toggleBottomSheet,
) {
articles[selectedArticle].options.forEach {
SuggestionChip(
onClick = {
onOptionClicked(selectedArticle, it)
},
label = {
Text(it)
}
)
}
}
}
if (showQuestionsSheet) {
ModalBottomSheet(
onDismissRequest = toggleQuestionsSheet,
) {
articles[selectedArticle].questions.forEach {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
toggleQuestionsSheet()
}
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(
text = it.question,
color = MaterialTheme.colorScheme.onPrimaryContainer,
)
}
}
}
}
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/zread/Zread.kt | 2132223536 |
package app.xlei.vipexam.ui.question.listening
import android.media.MediaPlayer
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.rememberTooltipState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Children
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.network.module.getExamResponse.Shiti
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class ListeningViewModel @Inject constructor(
listeningUiState: ListeningUiState
) : ViewModel() {
private val _uiState = MutableStateFlow(listeningUiState)
val uiState: StateFlow<ListeningUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban
)
}
}
@Composable
fun SetListening() {
_uiState.update {
it.copy(
listenings = getListenings()
)
}
}
fun toggleOptionsSheet() {
_uiState.update {
it.copy(
showOptionsSheet = !it.showOptionsSheet
)
}
}
fun setOption(selectedListeningIndex: Int,selectedQuestionIndex: Int, option: String){
_uiState.value.listenings[selectedListeningIndex].questions[selectedQuestionIndex].choice.value = option
}
@Composable
private fun getListenings(): MutableList<ListeningUiState.Listening> {
val listenings = mutableListOf<ListeningUiState.Listening>()
_uiState.value.muban!!.shiti.forEach {
listenings.add(
ListeningUiState.Listening(
originalText = it.originalText,
audioFile = "https://rang.vipexam.org/Sound/${it.audioFiles}.mp3",
questions = getQuestions(it),
options = listOf("A","B","C","D"),
player = getPlayers()
)
)
}
return listenings
}
@Composable
fun getPlayers(): ListeningUiState.Player {
return ListeningUiState.Player(
mediaPlayer = remember { MediaPlayer() },
prepared = rememberSaveable { mutableStateOf(false) }
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun getQuestions(shiti: Shiti): MutableList<ListeningUiState.Question> {
val questions = mutableListOf<ListeningUiState.Question>()
questions.add(
ListeningUiState.Question(
index = "1",
options = listOf(
ListeningUiState.Option(
index = "A",
option = shiti.first,
),
ListeningUiState.Option(
index = "B",
option = shiti.second,
),
ListeningUiState.Option(
index = "C",
option = shiti.third,
),
ListeningUiState.Option(
index = "D",
option = shiti.fourth,
)
),
choice = rememberSaveable { mutableStateOf("") },
refAnswer = shiti.refAnswer,
tooltipState = rememberTooltipState(isPersistent = true),
description = shiti.discription,
)
)
shiti.children.forEachIndexed {index,it->
questions.add(
ListeningUiState.Question(
index = "${index + 2}",
options = getOptions(it),
choice = rememberSaveable { mutableStateOf("") },
refAnswer = it.refAnswer,
tooltipState = rememberTooltipState(isPersistent = true),
description = it.discription,
)
)
}
return questions
}
private fun getOptions(children: Children): MutableList<ListeningUiState.Option> {
val options = mutableListOf<ListeningUiState.Option>()
options.add(
ListeningUiState.Option(
index = "A",
option = children.first,
)
)
options.add(
ListeningUiState.Option(
index = "B",
option = children.second,
)
)
options.add(
ListeningUiState.Option(
index = "C",
option = children.third,
)
)
options.add(
ListeningUiState.Option(
index = "D",
option = children.fourth,
)
)
return options
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/listening/ListeningViewModel.kt | 1680922405 |
package app.xlei.vipexam.ui.question.listening
import android.media.MediaPlayer
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.RichTooltip
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.material3.TooltipBox
import androidx.compose.material3.TooltipDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
import app.xlei.vipexam.preference.LocalVibrate
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
fun ListeningView(
submitMyAnswer: (String, String) -> Unit,
muban: Muban,
viewModel: ListeningViewModel = hiltViewModel(),
){
viewModel.setMuban(muban)
viewModel.SetListening()
val showAnswer = LocalShowAnswer.current.isShowAnswer()
val uiState by viewModel.uiState.collectAsState()
val vibrate = LocalVibrate.current.isVibrate()
var selectedQuestionIndex by remember { mutableIntStateOf(0) }
val haptics = LocalHapticFeedback.current
Listening(
listenings = uiState.listenings,
showOptionsSheet = uiState.showOptionsSheet,
toggleOptionsSheet = { viewModel.toggleOptionsSheet() },
onQuestionClick = {
selectedQuestionIndex = it
viewModel.toggleOptionsSheet()
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
onOptionClick = { selectedListeningIndex, option ->
if (selectedListeningIndex == 0)
submitMyAnswer(muban.shiti[selectedListeningIndex].questionCode, option)
else
submitMyAnswer(
muban.shiti[selectedListeningIndex].children[selectedQuestionIndex - 1].questionCode,
option
)
viewModel.setOption(selectedListeningIndex, selectedQuestionIndex, option)
viewModel.toggleOptionsSheet()
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
showAnswer = showAnswer,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun Listening(
listenings: List<ListeningUiState.Listening>,
showOptionsSheet: Boolean,
toggleOptionsSheet: () -> Unit,
onQuestionClick: (Int) -> Unit,
onOptionClick: (Int, String) -> Unit,
showAnswer: Boolean,
){
var selectedListening by rememberSaveable { mutableIntStateOf(0) }
val scrollState = rememberLazyListState()
val coroutine = rememberCoroutineScope()
DisposableEffect(Unit) {
coroutine.launch {
withContext(Dispatchers.IO){
listenings.forEach{
it.player.mediaPlayer.setDataSource(it.audioFile)
it.player.mediaPlayer.prepare()
it.player.prepared.value = true
}
}
}
onDispose {
listenings.forEach {
it.player.mediaPlayer.release()
}
}
}
Column {
LazyColumn(
state = scrollState
) {
items(listenings.size) {
Text("${it + 1}")
AudioPlayer(
mediaPlayer = listenings[it].player.mediaPlayer,
enabled = listenings[it].player.prepared.value
)
listenings[it].questions.forEachIndexed {index,question ->
TooltipBox(
positionProvider = TooltipDefaults.rememberRichTooltipPositionProvider(),
tooltip = {
if (showAnswer)
RichTooltip(
title = { Text(question.index + question.refAnswer) },
modifier = Modifier
.padding(top = 100.dp, bottom = 100.dp)
) {
LazyColumn {
item { Text(listenings[it].originalText) }
}
}
},
state = question.tooltipState
) {
VipexamArticleContainer(
onDragContent = listenings[selectedListening].originalText
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
selectedListening = it
onQuestionClick(index)
}
) {
Text(question.index)
Column (
modifier = Modifier
.padding(start = 16.dp, end = 16.dp, bottom = 16.dp)
){
question.options.forEach { option ->
Text("${option.index}. " + option.option)
}
if (showAnswer) {
Spacer(
Modifier
.fillMaxWidth()
.height(24.dp)
)
Text(
text = question.description,
modifier = Modifier
.padding(horizontal = 24.dp)
)
}
}
if (question.choice.value!="")
SuggestionChip(
onClick = {},
label = {
Text(question.choice.value)
}
)
}
}
}
}
}
}
if(showOptionsSheet){
ModalBottomSheet(
onDismissRequest = toggleOptionsSheet
){
listenings[selectedListening].options.forEach {
SuggestionChip(
onClick = {
onOptionClick(selectedListening,it) },
label = {
Text(it)
}
)
}
}
}
}
}
@Stable
@Composable
fun AudioPlayer(
mediaPlayer: MediaPlayer,
enabled: Boolean,
) {
val vibrate = LocalVibrate.current.isVibrate()
var isPlaying by rememberSaveable { mutableStateOf(false) }
val haptics = LocalHapticFeedback.current
Column {
Button(
onClick = {
isPlaying = !isPlaying
if (isPlaying) {
mediaPlayer.start()
} else {
mediaPlayer.pause()
}
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
enabled = enabled
) {
Text(if (isPlaying) "Pause" else "Play")
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/listening/Listening.kt | 1054445354 |
package app.xlei.vipexam.ui.question.listening
import android.media.MediaPlayer
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.TooltipState
import androidx.compose.runtime.MutableState
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class ListeningUiState(
val muban: Muban?=null,
var showOptionsSheet: Boolean=false,
val listenings: List<Listening>,
){
data class Listening(
val originalText: String,
val audioFile: String,
val questions: List<Question>,
val options: List<String>,
val player: Player,
)
data class Question @OptIn(ExperimentalMaterial3Api::class) constructor(
val index: String,
val options: List<Option>,
var choice: MutableState<String>,
val refAnswer: String,
val description: String,
val tooltipState: TooltipState,
)
data class Option(
val index: String,
val option: String,
)
data class Player(
val mediaPlayer: MediaPlayer,
val prepared: MutableState<Boolean>,
)
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/question/listening/ListeningUiState.kt | 1458912462 |
package app.xlei.vipexam.ui.question.cloze
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.database.module.Word
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.network.module.getExamResponse.Shiti
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ClozeViewModel @Inject constructor(
clozeUiState: ClozeUiState,
private val repository: Repository<Word>,
) : ViewModel() {
private val _uiState = MutableStateFlow(clozeUiState)
val uiState: StateFlow<ClozeUiState> = _uiState.asStateFlow()
private var addToWordListState = AddToWordListState.PROCESSING
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban
)
}
}
@Composable
fun SetClozes(){
val clozes = mutableListOf<ClozeUiState.Cloze>()
_uiState.collectAsState().value.muban!!.shiti.forEach {
clozes.add(
ClozeUiState.Cloze(
article = getClickableArticle(it.primQuestion),
blanks = getBlanks(it),
options = getOptions(it.primQuestion),
)
)
}
_uiState.update {
it.copy(
clozes = clozes
)
}
when (addToWordListState) {
AddToWordListState.PROCESSING -> addToWordList()
AddToWordListState.OK -> return
}
}
private fun addToWordList(string: String? = null) {
viewModelScope.launch(Dispatchers.IO) {
string?.let {
repository.add(
Word(
word = it
)
)
return@launch
}
viewModelScope.launch(Dispatchers.IO) {
_uiState.value.clozes.forEach { cloze ->
cloze.options.forEach { option ->
repository.add(
Word(
word = option.word
)
)
}
}
addToWordListState = AddToWordListState.OK
}
}
}
@Composable
private fun getBlanks(shiti: Shiti): MutableList<ClozeUiState.Blank> {
val blanks = mutableListOf<ClozeUiState.Blank>()
shiti.children.forEach {
blanks.add(
ClozeUiState.Blank(
index = it.secondQuestion,
choice = rememberSaveable { mutableStateOf("") },
refAnswer = it.refAnswer,
description = it.discription,
)
)
}
return blanks
}
private fun getOptions(text: String): List<ClozeUiState.Option>{
val pattern = Regex("""([A-O])\)\s*([^A-O]+)""")
val matches = pattern.findAll(text)
val options = mutableListOf<ClozeUiState.Option>()
for (match in matches) {
val index = match.groupValues[1]
val word = match.groupValues[2].trim()
options.add(
ClozeUiState.Option(
index = index,
word = word,
)
)
}
return options.sortedBy { it.index }
}
private fun getClickableArticle(text: String): ClozeUiState.Article {
val pattern = Regex("""C\d+""")
val matches = pattern.findAll(text)
val tags = mutableListOf<String>()
val annotatedString = buildAnnotatedString {
var currentPosition = 0
for (match in matches) {
val startIndex = match.range.first
val endIndex = match.range.last + 1
append(text.substring(currentPosition, startIndex))
val tag = text.substring(startIndex, endIndex)
pushStringAnnotation(tag = tag, annotation = tag )
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Unspecified)) {
append(text.substring(startIndex, endIndex))
}
pop()
tags.add(tag)
currentPosition = endIndex
}
if (currentPosition < text.length) {
append(text.substring(currentPosition, text.length))
}
}
return ClozeUiState.Article(
article = annotatedString,
tags = tags
)
}
fun toggleBottomSheet() {
_uiState.update {
it.copy(
showBottomSheet = !it.showBottomSheet
)
}
}
fun setOption(
selectedClozeIndex: Int,
selectedQuestionIndex: Int,
option: ClozeUiState.Option
) {
_uiState.value.clozes[selectedClozeIndex].blanks[selectedQuestionIndex].choice.value =
option.word
}
}
enum class AddToWordListState {
OK,
PROCESSING
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/cloze/ClozeViewModel.kt | 353729913 |
package app.xlei.vipexam.ui.question.cloze
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
import app.xlei.vipexam.preference.LocalVibrate
@Composable
fun clozeView(
submitMyAnswer: (String, String) -> Unit,
viewModel: ClozeViewModel = hiltViewModel(),
muban: Muban,
) {
viewModel.setMuban(muban)
viewModel.SetClozes()
val vibrate = LocalVibrate.current.isVibrate()
val showAnswer = LocalShowAnswer.current.isShowAnswer()
val uiState by viewModel.uiState.collectAsState()
val haptics = LocalHapticFeedback.current
var selectedQuestionIndex by rememberSaveable { mutableIntStateOf(0) }
cloze(
clozes = uiState.clozes,
showBottomSheet = uiState.showBottomSheet,
onBlankClick = {
selectedQuestionIndex = it
viewModel.toggleBottomSheet()
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
onOptionClicked = { selectedClozeIndex, option ->
submitMyAnswer(
muban.shiti[selectedClozeIndex].children[selectedQuestionIndex].questionCode,
option.index
)
viewModel.setOption(selectedClozeIndex, selectedQuestionIndex, option)
viewModel.toggleBottomSheet()
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
toggleBottomSheet = { viewModel.toggleBottomSheet() },
showAnswer = showAnswer,
)
}
@OptIn(
ExperimentalMaterial3Api::class,
ExperimentalLayoutApi::class
)
@Composable
private fun cloze(
clozes: List<ClozeUiState.Cloze>,
showBottomSheet: Boolean,
onBlankClick: (Int) -> Unit,
onOptionClicked: (Int, ClozeUiState.Option) -> Unit,
toggleBottomSheet: () -> Unit,
showAnswer: Boolean,
) {
val scrollState = rememberLazyListState()
var selectedClozeIndex by rememberSaveable { mutableStateOf(0) }
Column {
LazyColumn(
state = scrollState,
modifier = Modifier
) {
items(clozes.size) { clozeIndex ->
Column(
modifier = Modifier
.padding(top = 16.dp, start = 16.dp, end = 16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
) {
VipexamArticleContainer {
ClickableText(
text = clozes[clozeIndex].article.article,
style = LocalTextStyle.current.copy(
color = MaterialTheme.colorScheme.onPrimaryContainer
),
onClick = {
clozes[clozeIndex].article.tags.forEachIndexed { index, tag ->
clozes[clozeIndex].article.article.getStringAnnotations(
tag = tag,
start = it,
end = it
).firstOrNull()?.let {
selectedClozeIndex = clozeIndex
onBlankClick(index)
}
}
},
modifier = Modifier
.padding(start = 4.dp, end = 4.dp)
)
}
}
FlowRow(
horizontalArrangement = Arrangement.Start,
maxItemsInEachRow = 2,
) {
clozes[clozeIndex].blanks.forEachIndexed {index,blank->
Column(
modifier = Modifier
.weight(1f)
) {
SuggestionChip(
onClick = {
selectedClozeIndex = clozeIndex
onBlankClick(index)
},
label = {
Text(
text = blank.index + blank.choice.value
)
}
)
}
}
}
if(showAnswer)
clozes[clozeIndex].blanks.forEach { blank ->
Text(
text = blank.index + blank.refAnswer,
modifier = Modifier
.padding(horizontal = 24.dp)
)
Text(
text = blank.description,
modifier = Modifier
.padding(horizontal = 24.dp)
)
}
}
}
if (showBottomSheet) {
ModalBottomSheet(
onDismissRequest = toggleBottomSheet,
) {
FlowRow(
horizontalArrangement = Arrangement.Start,
maxItemsInEachRow = 2,
modifier = Modifier
.padding(bottom = 24.dp)
) {
clozes[selectedClozeIndex].options.forEach{
Column(
modifier = Modifier
.weight(1f)
){
SuggestionChip(
onClick = {
onOptionClicked(selectedClozeIndex,it)
},
label = {
Text("[${it.index}]${it.word}")
},
)
}
}
}
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/question/cloze/cloze.kt | 2872986865 |
package app.xlei.vipexam.ui.question.cloze
import androidx.compose.runtime.MutableState
import androidx.compose.ui.text.AnnotatedString
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class ClozeUiState(
val muban: Muban?=null,
var showBottomSheet: Boolean = false,
val clozes: List<Cloze>,
){
data class Cloze(
val article: Article,
val blanks: List<Blank>,
val options: List<Option>,
)
data class Article(
val article: AnnotatedString,
val tags: List<String>,
)
data class Blank(
val index: String,
val choice: MutableState<String>,
val refAnswer: String="",
val description: String="",
)
data class Option(
val index: String,
val word: String,
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/cloze/ClozeUiState.kt | 3390355640 |
package app.xlei.vipexam.ui.question.translate
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class TranslateUiState(
val muban: Muban?=null,
val translations: List<Translation>,
){
data class Translation(
val question: String,
val refAnswer: String,
val description: String,
)
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/question/translate/TranslateUiState.kt | 3352570348 |
package app.xlei.vipexam.ui.question.translate
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class TranslateViewModel @Inject constructor(
translateUiState: TranslateUiState
) : ViewModel() {
private val _uiState = MutableStateFlow(translateUiState)
val uiState: StateFlow<TranslateUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban
)
}
}
fun setTranslations(){
val translations = mutableListOf<TranslateUiState.Translation>()
_uiState.value.muban!!.shiti.forEach {
translations.add(
TranslateUiState.Translation(
question = it.primQuestion,
refAnswer = it.refAnswer,
description = it.discription,
)
)
}
_uiState.update {
it.copy(
translations = translations
)
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/translate/TranslateViewModel.kt | 2831446222 |
package app.xlei.vipexam.ui.question.translate
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
@Composable
fun TranslateView(
viewModel: TranslateViewModel = hiltViewModel(),
muban: Muban,
) {
val showAnswer = LocalShowAnswer.current.isShowAnswer()
viewModel.setMuban(muban)
viewModel.setTranslations()
val uiState by viewModel.uiState.collectAsState()
Translate(
translations = uiState.translations,
showAnswer = showAnswer,
)
}
@Composable
private fun Translate(
translations: List<TranslateUiState.Translation>,
showAnswer: Boolean,
){
val scrollState = rememberLazyListState()
LazyColumn(
state = scrollState
){
items(translations.size){
Column(
modifier = Modifier
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
) {
Text(
text = translations[it].question,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(16.dp)
)
}
if(showAnswer){
VipexamArticleContainer(
onDragContent = translations[it].question
+ "\n\n" + translations[it].refAnswer
+ "\n\n" + translations[it].description
) {
Column {
Text(
text = translations[it].refAnswer,
modifier = Modifier
.padding(horizontal = 24.dp)
)
Text(
text = translations[it].description,
modifier = Modifier
.padding(horizontal = 24.dp)
)
}
}
}
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/translate/Translate.kt | 724310282 |
package app.xlei.vipexam.ui.question
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class QuestionsViewModel @Inject constructor(
questionsUiState: QuestionsUiState
) : ViewModel() {
private val _uiState = MutableStateFlow(questionsUiState)
val uiState: StateFlow<QuestionsUiState> = _uiState.asStateFlow()
fun setMubanList(mubanList: List<Muban>) {
_uiState.update {
it.copy(
mubanList = mubanList
)
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/QuestionsViewModel.kt | 410083253 |
package app.xlei.vipexam.ui.question
import app.xlei.vipexam.R
import app.xlei.vipexam.ui.UiState
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.appbar.AppBarTitle
import app.xlei.vipexam.ui.question.cloze.ClozeUiState
import app.xlei.vipexam.ui.question.listening.ListeningUiState
import app.xlei.vipexam.ui.question.qread.QreadUiState
import app.xlei.vipexam.ui.question.translate.TranslateUiState
import app.xlei.vipexam.ui.question.writing.WritingUiState
import app.xlei.vipexam.ui.question.zread.ZreadUiState
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object QuestionModule {
@Provides
fun provideExamUiState() = VipexamUiState(
loginUiState = UiState.Loading(R.string.loading),
examTypeListUiState = UiState.Loading(R.string.loading),
examListUiState = UiState.Loading(R.string.loading),
questionListUiState = UiState.Loading(R.string.loading),
title = AppBarTitle.Login
)
@Provides
fun provideClozeUiState() = ClozeUiState(
clozes = emptyList()
)
@Provides
fun provideListeningUiState() = ListeningUiState(
listenings = emptyList()
)
@Provides
fun provideQreadUiState() = QreadUiState(
articles = emptyList()
)
@Provides
fun provideTranslateUiState() = TranslateUiState(
translations = emptyList()
)
@Provides
fun provideWritingUiState() = WritingUiState(
writings = emptyList()
)
@Provides
fun provideZreadUiState() = ZreadUiState(
articles = emptyList()
)
@Provides
fun provideQuestionsUiState() = QuestionsUiState()
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/QuestionsModule.kt | 2169955259 |
package app.xlei.vipexam.ui.question
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class QuestionsUiState(
val mubanList: List<Muban>?=null
) | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/QuestionsUiState.kt | 3238309759 |
package app.xlei.vipexam.ui.question.writing
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
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.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
import coil.compose.AsyncImage
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WritingView(
viewModel: WritingViewModel = hiltViewModel(),
muban: Muban,
){
val showAnswer = LocalShowAnswer.current.isShowAnswer()
viewModel.setMuban(muban)
viewModel.setWritings()
val uiState by viewModel.uiState.collectAsState()
writing(
writings = uiState.writings,
showAnswer = showAnswer
)
}
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
private fun writing(
writings: List<WritingUiState.Writing>,
showAnswer: Boolean,
) {
val scrollState = rememberLazyListState()
LazyColumn(
modifier = Modifier
.fillMaxWidth(),
state = scrollState
) {
items(writings.size) {
Column(
modifier = Modifier
.padding(top = 16.dp, start = 16.dp, end = 16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
) {
VipexamArticleContainer(
onDragContent = writings[it].question
+ "\n\n" + writings[it].refAnswer
+ "\n\n" + writings[it].description
) {
Text(
text = writings[it].question,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier
.padding(start = 4.dp, end = 4.dp)
)
}
if (shouldShowImage(writings[it].question)) {
Row {
Spacer(Modifier.weight(2f))
AsyncImage(
model = "https://rang.vipexam.org/images/${writings[it].image}.jpg",
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.padding(top = 24.dp)
.align(Alignment.CenterVertically)
.weight(6f)
.fillMaxWidth()
)
Spacer(Modifier.weight(2f))
}
}
}
if (showAnswer) {
Column {
Text(
text = writings[it].refAnswer,
modifier = Modifier
.padding(horizontal = 24.dp),
)
Text(
text = writings[it].description,
modifier = Modifier
.padding(horizontal = 24.dp),
)
}
}
}
}
}
private fun shouldShowImage(text: String): Boolean {
val pattern = Regex("""\[\*\]""")
return pattern.findAll(text).toList().isNotEmpty()
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/writing/writting.kt | 1958878183 |
package app.xlei.vipexam.ui.question.writing
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class WritingUiState(
val muban: Muban?=null,
val writings: List<Writing>
){
data class Writing(
val question: String,
val refAnswer: String,
val image: String,
val description: String,
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/writing/WritingUiState.kt | 4238676531 |
package app.xlei.vipexam.ui.question.writing
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class WritingViewModel @Inject constructor(
writingUiState: WritingUiState
) : ViewModel() {
private val _uiState = MutableStateFlow(writingUiState)
val uiState: StateFlow<WritingUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban // function scope
)
}
}
fun setWritings(){
val writings = mutableListOf<WritingUiState.Writing>()
_uiState.value.muban!!.shiti.forEach {
writings.add(
WritingUiState.Writing(
question = it.primQuestion,
refAnswer = it.refAnswer,
image = it.primPic,
description = it.discription
)
)
}
_uiState.update {
it.copy(
writings = writings
)
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/question/writing/WritingViewModel.kt | 948191637 |
package app.xlei.vipexam.ui.question.qread
import androidx.compose.runtime.MutableState
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class QreadUiState(
val muban: Muban?=null,
var showBottomSheet: Boolean = false,
var showOptionsSheet: Boolean = false,
val articles: List<Article>
){
data class Article(
val title: String,
val content: String,
val questions: List<Question>,
val options: List<Option>,
)
data class Question(
val index: String,
val question: String,
var choice: MutableState<String>,
val refAnswer: String,
val description: String,
)
data class Option(
val index: Int,
val option: String,
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/qread/QreadUiState.kt | 2877301944 |
package app.xlei.vipexam.ui.question.qread
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.database.module.Word
import app.xlei.vipexam.core.network.module.getExamResponse.Children
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class QreadViewModel @Inject constructor(
qreadUiState: QreadUiState,
private val repository: Repository<Word>,
) : ViewModel() {
private val _uiState = MutableStateFlow(qreadUiState)
val uiState: StateFlow<QreadUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban
)
}
}
@Composable
fun SetArticles () {
val articles = mutableListOf<QreadUiState.Article>()
_uiState.collectAsState().value.muban!!.shiti.forEach {
articles.add(
QreadUiState.Article(
title = extractFirstPart(it.primQuestion),
content = extractSecondPart(it.primQuestion),
questions = getQuestions(it.children),
options = getOptions(it.primQuestion),
)
)
}
_uiState.update {
it.copy(
articles = articles
)
}
}
fun toggleBottomSheet(){
_uiState.update {
it.copy(
showBottomSheet = !it.showBottomSheet
)
}
}
fun toggleOptionsSheet() {
_uiState.update {
it.copy(
showOptionsSheet = !it.showOptionsSheet
)
}
}
fun setOption(selectedArticleIndex: Int, selectedQuestion: Int, option: String) {
_uiState.value.articles[selectedArticleIndex].questions[selectedQuestion].choice.value = option
}
private fun getOptions(text: String): MutableList<QreadUiState.Option> {
val result = mutableListOf<QreadUiState.Option>()
var pattern = Regex("""([A-Z])([)])""")
var matches = pattern.findAll(text)
if (matches.count() < 10) {
pattern = Regex("""([A-Z])(])""")
matches = pattern.findAll(text)
}
for ((index, match) in matches.withIndex()) {
result.add(
QreadUiState.Option(
index = index + 1,
option = match.groupValues[1]
)
)
}
return result
}
@Composable
private fun getQuestions(children: List<Children>): MutableList<QreadUiState.Question> {
val questions = mutableListOf<QreadUiState.Question>()
children.forEachIndexed {index,it->
questions.add(
QreadUiState.Question(
index = "${index + 1}",
question = it.secondQuestion,
choice = rememberSaveable { mutableStateOf("") },
refAnswer = it.refAnswer,
description = it.discription
)
)
}
return questions
}
private fun extractFirstPart(text: String): String {
val lines = text.split("\n")
if (lines.isNotEmpty()) {
return lines.first().trim()
}
return ""
}
private fun extractSecondPart(text: String): String {
val index = text.indexOf("\n")
if (index != -1) {
return text.substring(index + 1)
}
return ""
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/question/qread/QreadViewModel.kt | 1777456164 |
package app.xlei.vipexam.ui.question.qread
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
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.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
import app.xlei.vipexam.preference.LocalVibrate
@Composable
fun QreadView(
submitMyAnswer: (String, String) -> Unit,
viewModel: QreadViewModel = hiltViewModel(),
muban: Muban,
) {
viewModel.setMuban(muban)
viewModel.SetArticles()
val vibrate = LocalVibrate.current.isVibrate()
val showAnswer = LocalShowAnswer.current.isShowAnswer()
val uiState by viewModel.uiState.collectAsState()
val haptics = LocalHapticFeedback.current
var selectedQuestionIndex by rememberSaveable { mutableIntStateOf(0) }
Qread(
showBottomSheet = uiState.showBottomSheet,
showOptionsSheet = uiState.showOptionsSheet,
articles = uiState.articles,
toggleBottomSheet = viewModel::toggleBottomSheet,
toggleOptionsSheet = viewModel::toggleOptionsSheet,
onArticleLongClicked = {
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
onQuestionClicked = {
selectedQuestionIndex = it
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
onOptionClicked = { selectedArticleIndex, option ->
submitMyAnswer(
muban.shiti[selectedArticleIndex].children[selectedQuestionIndex].questionCode,
option
)
viewModel.setOption(selectedArticleIndex, selectedQuestionIndex, option)
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
showAnswer = showAnswer,
)
}
@OptIn(
ExperimentalMaterial3Api::class,
ExperimentalLayoutApi::class
)
@Composable
private fun Qread(
showBottomSheet: Boolean,
showOptionsSheet: Boolean,
articles: List<QreadUiState.Article>,
toggleBottomSheet: () -> Unit,
toggleOptionsSheet: () -> Unit,
onArticleLongClicked: () -> Unit,
onQuestionClicked: (Int) -> Unit,
onOptionClicked: (Int, String) -> Unit,
showAnswer: Boolean,
){
val scrollState = rememberLazyListState()
val selectedArticle by rememberSaveable { mutableIntStateOf(0) }
Column {
LazyColumn(
state = scrollState
) {
articles.forEachIndexed { articleIndex, article ->
item {
VipexamArticleContainer(
onArticleLongClick = {
onArticleLongClicked.invoke()
toggleBottomSheet.invoke()
},
onDragContent = article.title
+ "\n\n" + article.content
+ article.questions.joinToString{ "\n\n" + it.index + ". " + it.question }
) {
Column(
modifier = Modifier
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
) {
Text(
text = articles[articleIndex].title,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontSize = 24.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.align(Alignment.CenterHorizontally)
)
Text(
text = articles[articleIndex].content,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier
.padding(16.dp)
)
}
}
}
items(article.questions.size) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
onQuestionClicked(it)
toggleOptionsSheet()
}
) {
Column(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = "${article.questions[it].index}. ${article.questions[it].question}",
color = MaterialTheme.colorScheme.onPrimaryContainer,
)
if (article.questions[it].choice.value != "") {
SuggestionChip(
onClick = toggleOptionsSheet,
label = { Text(article.questions[it].choice.value) }
)
}
}
}
if (showAnswer)
articles[articleIndex].questions[it].let { question ->
Text(
text = question.index + question.refAnswer,
modifier = Modifier.padding(horizontal = 24.dp)
)
Text(
text = question.description,
modifier = Modifier
.padding(horizontal = 24.dp)
)
}
}
}
}
// Questions
if (showBottomSheet) {
ModalBottomSheet(
onDismissRequest = toggleBottomSheet,
) {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
) {
articles[selectedArticle].questions.forEachIndexed { index, it ->
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
onQuestionClicked(index)
toggleOptionsSheet()
}
) {
Text(
text = "${it.index}. ${it.question}",
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(16.dp)
)
if (it.choice.value != "") {
SuggestionChip(
onClick = toggleOptionsSheet,
label = { Text(it.choice.value) }
)
}
}
}
}
}
}
// options
if (showOptionsSheet) {
ModalBottomSheet(
onDismissRequest = toggleOptionsSheet,
) {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
){
FlowRow(
horizontalArrangement = Arrangement.Start,
maxItemsInEachRow = 5,
modifier = Modifier
.padding(bottom = 24.dp)
) {
articles[selectedArticle].options.forEach {
Column(
modifier = Modifier
.weight(1f)
) {
SuggestionChip(
onClick = {
onOptionClicked(selectedArticle, it.option)
toggleOptionsSheet()
},
label = {
Text(it.option)
}
)
}
}
}
}
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/question/qread/Qread.kt | 868406433 |
package app.xlei.vipexam.ui.components
import androidx.compose.material3.Checkbox
import androidx.compose.runtime.Composable
/**
* Vipexam checkbox
*
* @param checked
* @param onCheckedChange
*/
@Composable
fun VipexamCheckbox(
checked: Boolean,
onCheckedChange: ((Boolean) -> Unit)?,
){
Checkbox(
checked = checked,
onCheckedChange = onCheckedChange,
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/components/CheckBox.kt | 262100628 |
package app.xlei.vipexam.ui.components
| vipexam/app/src/main/java/app/xlei/vipexam/ui/components/HideOnScrollFAB.kt | 2024194698 |
package app.xlei.vipexam.ui.components
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Spacer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import app.xlei.vipexam.ui.navigation.AppDestinations
/**
* App nav rail
*
* @param logo 侧边导航的logo
* @param homeNavController 主页导航控制器
* @param currentRoute 当前导航页面
* @param navigationToTopLevelDestination 导航函数
* @param modifier
* @receiver
* @receiver
*/
@Composable
fun AppNavRail(
logo: @Composable () -> Unit = {},
homeNavController: NavHostController,
currentRoute: String,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
@SuppressLint("ModifierParameter") modifier: Modifier = Modifier
) {
NavigationRail(
header = {
logo()
},
containerColor = NavigationRailDefaults.ContainerColor,
modifier = modifier
) {
Spacer(Modifier.weight(1f))
AppDestinations.entries.forEach {
NavigationRailItem(
currentRoute = currentRoute,
appDestination = it,
navigationToTopLevelDestination = navigationToTopLevelDestination
)
}
if (currentRoute == AppDestinations.HOME_ROUTE.name &&
homeNavController.previousBackStackEntry != null
)
IconButton(
onClick = { homeNavController.navigateUp() },
) {
Icon(Icons.AutoMirrored.Filled.KeyboardArrowLeft, null)
}
Spacer(Modifier.weight(1f))
}
}
@Composable
private fun NavigationRailItem(
currentRoute: String,
appDestination: AppDestinations,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
){
NavigationRailItem(
selected = currentRoute == appDestination.name,
onClick = { navigationToTopLevelDestination(appDestination) },
icon = { Icon(appDestination.icon, stringResource(appDestination.title)) },
label = { Text(stringResource(appDestination.title)) },
alwaysShowLabel = false
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/components/AppNavRail.kt | 2617237517 |
package app.xlei.vipexam.ui.components
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.vector.ImageVector
/**
* Text icon dialog
*
* @param onDismissRequest 忽略事件
* @param onConfirmation 确认事件
* @param dialogTitle 对话框标题
* @param dialogText 对话框文字内容
* @param icon 图标
* @receiver
* @receiver
*/
@Composable
fun TextIconDialog(
onDismissRequest: () -> Unit,
onConfirmation: () -> Unit,
dialogTitle: String,
dialogText: String,
icon: ImageVector,
) {
AlertDialog(
icon = {
Icon(icon, contentDescription = "Icon")
},
title = {
Text(text = dialogTitle)
},
text = {
Text(text = dialogText)
},
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(
onClick = onConfirmation
) {
Text("Confirm")
}
},
dismissButton = {
TextButton(
onClick = onDismissRequest
) {
Text("Dismiss")
}
}
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/components/Dialog.kt | 1012172805 |
package app.xlei.vipexam.ui.components.vm
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import app.xlei.vipexam.core.data.paging.ExamListItem
import app.xlei.vipexam.core.data.paging.ExamListRepository
import app.xlei.vipexam.core.network.module.NetWorkRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Search view model
*
* @property examListRepository 试卷列表
* @constructor Create empty Search view model
*/
@HiltViewModel
class SearchViewModel @Inject constructor(
private val examListRepository : ExamListRepository,
) : ViewModel() {
private val _examListState: MutableStateFlow<PagingData<ExamListItem>> =
MutableStateFlow(value = PagingData.empty())
val examListState: MutableStateFlow<PagingData<ExamListItem>>
get() = _examListState
/**
* Search
* 搜索试卷
* @param query 搜索关键词
*/
fun search(query: String) {
viewModelScope.launch {
examListRepository.search(query)
.distinctUntilChanged()
.cachedIn(viewModelScope)
.collect {
_examListState.value = it
}
}
}
/**
* Download
* 下载试卷
* @param fileName 文件名
* @param examId 试卷id
*/
fun download(
fileName: String,
examId: String,
) {
viewModelScope.launch {
NetWorkRepository
.download(
fileName = fileName,
examId = examId
)
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/components/vm/SearchViewModel.kt | 218477334 |
package app.xlei.vipexam.ui.components
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.R
/**
* Custom floating action button
*
* @param expandable 是否能展开
* @param onFabClick 按钮点击事件
* @param iconUnExpanded 未展开图标
* @param iconExpanded 展开图标
* @param items 展开显示的内容,按从上到下排列
* @param onItemClick 内容点击事件
* @receiver
* @receiver
*/
@Composable
fun CustomFloatingActionButton(
expandable: Boolean,
onFabClick: () -> Unit,
iconUnExpanded: ImageVector,
iconExpanded: ImageVector,
items: List<Pair<String, String>>,
onItemClick: (String) -> Unit,
) {
var isExpanded by remember { mutableStateOf(false) }
if (!expandable) { // Close the expanded fab if you change to non expandable nav destination
isExpanded = false
}
val fabSize = 56.dp
val expandedFabWidth by animateDpAsState(
targetValue = if (isExpanded) 200.dp else fabSize,
animationSpec = spring(dampingRatio = 3f), label = ""
)
val expandedFabHeight by animateDpAsState(
targetValue = if (isExpanded) 56.dp else fabSize,
animationSpec = spring(dampingRatio = 3f), label = ""
)
Column {
Column(
modifier = Modifier
.offset(y = (16).dp)
.size(
width = expandedFabWidth,
height = (animateDpAsState(
if (isExpanded) 225.dp else 0.dp,
animationSpec = spring(dampingRatio = 4f), label = ""
)).value
)
.background(
MaterialTheme.colorScheme.surfaceContainer,
shape = RoundedCornerShape(16.dp)
)
.verticalScroll(rememberScrollState())
) {
Column(
modifier = Modifier
.padding(bottom = 16.dp)
) {
items.forEach{
Column(
modifier = Modifier
.fillMaxWidth()
.height(fabSize)
.padding(4.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
onItemClick(it.first)
isExpanded = false
}
) {
Spacer(modifier = Modifier.weight(1f))
Text(
text = it.second,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = MaterialTheme.typography.bodyLarge.fontWeight,
modifier = Modifier
.align(Alignment.CenterHorizontally)
)
Spacer(modifier = Modifier.weight(1f))
}
}
}
}
FloatingActionButton(
onClick = {
onFabClick()
if (expandable) {
isExpanded = !isExpanded
}
},
modifier = Modifier
.width(expandedFabWidth)
.height(expandedFabHeight),
shape = RoundedCornerShape(16.dp)
) {
Icon(
imageVector = if(isExpanded){iconExpanded}else{iconUnExpanded},
contentDescription = null,
modifier = Modifier
.size(24.dp)
.offset(
x = animateDpAsState(
if (isExpanded) -70.dp else 0.dp,
animationSpec = spring(dampingRatio = 3f), label = ""
).value
)
)
Text(
text = stringResource(R.string.close_button),
softWrap = false,
modifier = Modifier
.offset(
x = animateDpAsState(
if (isExpanded) 10.dp else 50.dp,
animationSpec = spring(dampingRatio = 3f), label = ""
).value
)
.alpha(
animateFloatAsState(
targetValue = if (isExpanded) 1f else 0f,
animationSpec = tween(
durationMillis = if (isExpanded) 350 else 100,
delayMillis = if (isExpanded) 100 else 0,
easing = EaseIn
), label = ""
).value
)
)
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/components/CustomFloatingButton.kt | 2784525198 |
package app.xlei.vipexam.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.ui.navigation.AppDestinations
/**
* App drawer
*
* @param currentRoute 当前导航
* @param navigationToTopLevelDestination 导航函数
* @param closeDrawer 关闭抽屉函数
* @param modifier
* @receiver
* @receiver
*/
@Composable
fun AppDrawer(
currentRoute: String,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
closeDrawer: () -> Unit,
modifier: Modifier = Modifier
) {
ModalDrawerSheet(
drawerContainerColor = MaterialTheme.colorScheme.surfaceContainer,
drawerContentColor = MaterialTheme.colorScheme.surface,
modifier = modifier
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(top = 24.dp)
) {
AppDestinations.entries.forEach {
VipexamDrawerItem(
currentRoute = currentRoute,
destination = it,
navigationToTopLevelDestination = navigationToTopLevelDestination
) {
closeDrawer.invoke()
}
}
}
}
}
@Composable
private fun VipexamDrawerItem(
currentRoute: String,
destination: AppDestinations,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
closeDrawer: () -> Unit,
){
NavigationDrawerItem(
label = { Text(stringResource(id = destination.title)) },
icon = { Icon(destination.icon, null) },
selected = currentRoute == destination.name,
onClick = { navigationToTopLevelDestination(destination); closeDrawer() },
colors = NavigationDrawerItemDefaults.colors(
unselectedContainerColor = MaterialTheme.colorScheme.surfaceContainer
),
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/components/AppDrawer.kt | 1185275010 |
package app.xlei.vipexam.ui.components
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
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.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
/**
* Timer view model
* 计时器vm
* @constructor Create empty Timer view model
*/
class TimerViewModel : ViewModel() {
private val _time = MutableStateFlow(0)
val time: StateFlow<Int> = _time
private var timerJob: Job? = null
fun startTimer() {
timerJob?.cancel()
timerJob = viewModelScope.launch {
while (true) {
delay(1000)
_time.value++
}
}
}
fun stopTimer() {
timerJob?.cancel()
}
fun resetTimer() {
_time.value = 0
}
}
/**
* Timer
* 计时器
* @param timerViewModel 计时器vm
* @param isTimerStart 开始
* @param isResetTimer 结束
* @param modifier
*/
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun Timer(
timerViewModel: TimerViewModel = viewModel(),
isTimerStart: Boolean,
isResetTimer: Boolean,
@SuppressLint("ModifierParameter") modifier: Modifier = Modifier,
) {
val time by timerViewModel.time.collectAsState()
Column(
modifier = modifier,
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = formatTime(time), style = MaterialTheme.typography.labelLarge)
}
if (isTimerStart)
timerViewModel.startTimer()
else
timerViewModel.stopTimer()
if (isResetTimer)
timerViewModel.resetTimer()
}
@SuppressLint("DefaultLocale")
private fun formatTime(seconds: Int): String {
val minutes = seconds / 60
val remainingSeconds = seconds % 60
return String.format("%02d:%02d", minutes, remainingSeconds)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/components/Timer.kt | 2058787557 |
package app.xlei.vipexam.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.SearchBar
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import app.xlei.vipexam.core.ui.ErrorMessage
import app.xlei.vipexam.core.ui.LoadingNextPageItem
import app.xlei.vipexam.core.ui.PageLoader
import app.xlei.vipexam.ui.components.vm.SearchViewModel
import compose.icons.FeatherIcons
import compose.icons.feathericons.Search
import compose.icons.feathericons.X
/**
* Exam search bar
*
* @param modifier
* @param viewModel 搜索vm
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExamSearchBar(
modifier: Modifier = Modifier,
viewModel: SearchViewModel = hiltViewModel()
){
var queryString by remember {
mutableStateOf("")
}
var isActive by remember {
mutableStateOf(false)
}
SearchBar(
query = queryString,
onQueryChange = { queryString = it },
onSearch = { viewModel.search(queryString) },
active = isActive,
onActiveChange = { isActive = it },
leadingIcon = {
IconButton(onClick = { isActive = true }) {
Icon(imageVector = FeatherIcons.Search, contentDescription = null)
}
},
trailingIcon = {
if (isActive)
IconButton(onClick = {
isActive = false
queryString = ""
}) {
Icon(imageVector = FeatherIcons.X, contentDescription = null)
}
},
modifier = modifier,
) {
val results = viewModel.examListState.collectAsLazyPagingItems()
LazyColumn {
items(results.itemCount) {
ListItem(
headlineContent = { results[it]?.exam?.let { exam->
Text(text = exam.examname) } },
modifier = Modifier
.clickable {
results[it]?.exam?.let { exam ->
viewModel.download(
fileName = exam.examname,
examId = exam.examid,
)
}
}
)
}
results.apply {
when {
loadState.refresh is LoadState.Loading -> {
item { PageLoader(modifier = Modifier.fillParentMaxSize()) }
}
loadState.refresh is LoadState.Error -> {
val error = results.loadState.refresh as LoadState.Error
item {
ErrorMessage(
modifier = Modifier.fillParentMaxSize(),
message = error.error.localizedMessage!!,
onClickRetry = { retry() })
}
}
loadState.append is LoadState.Loading -> {
item { LoadingNextPageItem(modifier = Modifier) }
}
loadState.append is LoadState.Error -> {
val error = results.loadState.append as LoadState.Error
item {
ErrorMessage(
modifier = Modifier,
message = error.error.localizedMessage!!,
onClickRetry = { retry() })
}
}
}
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/components/ExamSearchBar.kt | 4287023011 |
package app.xlei.vipexam.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF9B404F)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFFFD9DC)
val md_theme_light_onPrimaryContainer = Color(0xFF400011)
val md_theme_light_secondary = Color(0xFF765659)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFFFD9DC)
val md_theme_light_onSecondaryContainer = Color(0xFF2C1518)
val md_theme_light_tertiary = Color(0xFF785830)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFDDB7)
val md_theme_light_onTertiaryContainer = Color(0xFF2A1700)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF201A1A)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF201A1A)
val md_theme_light_surfaceVariant = Color(0xFFF4DDDE)
val md_theme_light_onSurfaceVariant = Color(0xFF524344)
val md_theme_light_outline = Color(0xFF847374)
val md_theme_light_inverseOnSurface = Color(0xFFFBEEEE)
val md_theme_light_inverseSurface = Color(0xFF362F2F)
val md_theme_light_inversePrimary = Color(0xFFFFB2BA)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF9B404F)
val md_theme_light_outlineVariant = Color(0xFFD7C1C3)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFFFB2BA)
val md_theme_dark_onPrimary = Color(0xFF5F1224)
val md_theme_dark_primaryContainer = Color(0xFF7D2939)
val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9DC)
val md_theme_dark_secondary = Color(0xFFE5BDC0)
val md_theme_dark_onSecondary = Color(0xFF43292C)
val md_theme_dark_secondaryContainer = Color(0xFF5C3F42)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFD9DC)
val md_theme_dark_tertiary = Color(0xFFE9BF8F)
val md_theme_dark_onTertiary = Color(0xFF442B07)
val md_theme_dark_tertiaryContainer = Color(0xFF5E411B)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDDB7)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF201A1A)
val md_theme_dark_onBackground = Color(0xFFECE0E0)
val md_theme_dark_surface = Color(0xFF201A1A)
val md_theme_dark_onSurface = Color(0xFFECE0E0)
val md_theme_dark_surfaceVariant = Color(0xFF524344)
val md_theme_dark_onSurfaceVariant = Color(0xFFD7C1C3)
val md_theme_dark_outline = Color(0xFF9F8C8D)
val md_theme_dark_inverseOnSurface = Color(0xFF201A1A)
val md_theme_dark_inverseSurface = Color(0xFFECE0E0)
val md_theme_dark_inversePrimary = Color(0xFF9B404F)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFFFB2BA)
val md_theme_dark_outlineVariant = Color(0xFF524344)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFFFEDFE1) | vipexam/app/src/main/java/app/xlei/vipexam/ui/theme/Color.kt | 2563283388 |
package app.xlei.vipexam.ui.theme
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
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.core.view.WindowCompat
import app.xlei.vipexam.preference.ThemeModePreference
import com.google.android.material.color.utilities.Scheme
const val defaultAccentColor = "fedfe1"
fun String.hexToColor() = Color(android.graphics.Color.parseColor("#$this"))
@SuppressLint("RestrictedApi")
@Composable
fun VipexamTheme(
themeMode: ThemeModePreference,
shouldShowNavigationRegion: Boolean = false,
content: @Composable () -> Unit,
) {
val darkTheme = when (themeMode) {
ThemeModePreference.Auto -> isSystemInDarkTheme()
ThemeModePreference.Light -> false
ThemeModePreference.Dark, ThemeModePreference.Black -> true
}
var colorScheme = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
else -> {
val seed = defaultAccentColor.hexToColor().toArgb()
if (darkTheme) Scheme.dark(seed).toColorScheme() else Scheme.light(seed).toColorScheme()
}
}
if (themeMode == ThemeModePreference.Black) colorScheme =
colorScheme.copy(background = Color.Black, surface = Color.Black)
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val activity = view.context as Activity
activity.window.navigationBarColor = colorScheme.run {
if (shouldShowNavigationRegion)
this.surfaceContainer.toArgb()
else
this.surface.toArgb()
}
activity.window.statusBarColor = colorScheme.run {
if (shouldShowNavigationRegion)
this.surfaceContainer.toArgb()
else
this.surface.toArgb()
}
WindowCompat.getInsetsController(
activity.window,
view
).isAppearanceLightStatusBars = !darkTheme
WindowCompat.getInsetsController(
activity.window,
view
).isAppearanceLightNavigationBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@SuppressLint("RestrictedApi")
fun Scheme.toColorScheme() = ColorScheme(
primary = Color(primary),
onPrimary = Color(onPrimary),
primaryContainer = Color(primaryContainer),
onPrimaryContainer = Color(onPrimaryContainer),
inversePrimary = Color(inversePrimary),
secondary = Color(secondary),
onSecondary = Color(onSecondary),
secondaryContainer = Color(secondaryContainer),
onSecondaryContainer = Color(onSecondaryContainer),
tertiary = Color(tertiary),
onTertiary = Color(onTertiary),
tertiaryContainer = Color(tertiaryContainer),
onTertiaryContainer = Color(onTertiaryContainer),
background = Color(background),
onBackground = Color(onBackground),
surface = Color(surface),
onSurface = Color(onSurface),
surfaceVariant = Color(surfaceVariant),
onSurfaceVariant = Color(onSurfaceVariant),
surfaceTint = Color(primary),
inverseSurface = Color(inverseSurface),
inverseOnSurface = Color(inverseOnSurface),
error = Color(error),
onError = Color(onError),
errorContainer = Color(errorContainer),
onErrorContainer = Color(onErrorContainer),
outline = Color(outline),
outlineVariant = Color(outlineVariant),
scrim = Color(scrim)
) | vipexam/app/src/main/java/app/xlei/vipexam/ui/theme/Theme.kt | 3577379923 |
package app.xlei.vipexam.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | vipexam/app/src/main/java/app/xlei/vipexam/ui/theme/Type.kt | 990349594 |
package app.xlei.vipexam.ui.screen
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.expanded.ExamScreenSupportingPane
import app.xlei.vipexam.ui.page.ExamPage
/**
* Exam screen
* 试卷页面
* @param questionListUiState 问题列表
* @param setQuestion 问题点击事件
* @param widthSizeClass 屏幕宽度
* @param modifier
* @param navController 试卷页面导航控制器,用于切换问题
* @receiver
*/
@Composable
fun ExamScreen(
questionListUiState: VipexamUiState.QuestionListUiState,
setQuestion: (String, GetExamResponse) -> Unit,
widthSizeClass: WindowWidthSizeClass,
modifier: Modifier = Modifier,
navController: NavHostController = rememberNavController(),
submitMyAnswer: (String, String) -> Unit,
onExamClick: (String) -> Unit,
) {
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> {
ExamPage(
questionListUiState = questionListUiState,
setQuestion = setQuestion,
navController = navController,
submitMyAnswer = submitMyAnswer
)
}
WindowWidthSizeClass.Medium -> {
ExamPage(
questionListUiState = questionListUiState,
setQuestion = setQuestion,
navController = navController,
submitMyAnswer = submitMyAnswer
)
}
WindowWidthSizeClass.Expanded -> {
Row (
modifier = modifier
){
Column(
modifier = Modifier
.padding(horizontal = 24.dp)
.weight(1f)
) {
ExamPage(
questionListUiState = questionListUiState,
setQuestion = setQuestion,
navController = navController,
showFab = false,
submitMyAnswer = submitMyAnswer
)
}
ExamScreenSupportingPane(
questionListUiState = questionListUiState,
navController = navController,
modifier = Modifier
.width(360.dp)
.padding(end = 24.dp)
.fillMaxSize(),
onExamClick = onExamClick
)
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/ExamScreen.kt | 2087320433 |
package app.xlei.vipexam.ui.screen
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalConfiguration
import androidx.navigation.NavHostController
import app.xlei.vipexam.ui.VipExamMainScreenViewModel
import app.xlei.vipexam.ui.appbar.VipExamAppBar
import app.xlei.vipexam.ui.navigation.MainScreenNavigation
/**
* Home screen
*
* @param modifier
* @param logoText
* @param widthSizeClass 屏幕宽度
* @param viewModel 主页vm
* @param navController 主页导航控制器
* @param openDrawer 打开侧边抽屉事件
* @receiver
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
modifier: Modifier = Modifier,
logoText: (@Composable () -> Unit)? = null,
widthSizeClass: WindowWidthSizeClass,
viewModel: VipExamMainScreenViewModel,
navController: NavHostController,
openDrawer: () -> Unit,
) {
val uiState by viewModel.uiState.collectAsState()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
val localConfiguration = LocalConfiguration.current
Scaffold(
modifier = modifier
.fillMaxSize()
.statusBarsPadding()
.run {
// LazyColumn will not be scrollable without this in expanded width size
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> this.nestedScroll(scrollBehavior.nestedScrollConnection)
WindowWidthSizeClass.Expanded -> {
when (localConfiguration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> this
Configuration.ORIENTATION_PORTRAIT -> this.nestedScroll(scrollBehavior.nestedScrollConnection)
else -> this
}
}
else -> this
}
},
topBar = {
when (widthSizeClass) {
WindowWidthSizeClass.Compact ->
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
WindowWidthSizeClass.Medium -> {
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
}
WindowWidthSizeClass.Expanded -> {
when (localConfiguration.orientation) {
Configuration.ORIENTATION_PORTRAIT -> {
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
}
else -> {
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
scrollable = false,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
}
}
}
}
}
) { padding ->
MainScreenNavigation(
navHostController = navController,
widthSizeClass = widthSizeClass,
modifier = Modifier.padding(padding),
viewModel = viewModel,
)
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/HomeScreen.kt | 2599877859 |
package app.xlei.vipexam.ui.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.R
import app.xlei.vipexam.core.ui.OnError
import app.xlei.vipexam.core.ui.OnLoading
import app.xlei.vipexam.core.ui.PageLoader
import app.xlei.vipexam.ui.UiState
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.expanded.ExamListScreenSupportingPane
import app.xlei.vipexam.ui.page.ExamListView
/**
* Exam list screen
* 试卷列表页面
* @param examListUiState 试卷列表
* @param onLastExamClick 最近试卷点击事件
* @param onExamClick 试卷点击事件
* @param widthSizeClass 屏幕宽度
* @param modifier
* @receiver
* @receiver
* @receiver
*/
@Composable
fun ExamListScreen(
examListUiState: UiState<VipexamUiState.ExamListUiState>,
onLastExamClick: (String) -> Unit,
onExamClick: (String) -> Unit,
widthSizeClass: WindowWidthSizeClass,
modifier: Modifier = Modifier
) {
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> {
when (examListUiState) {
is UiState.Success -> {
ExamListView(
isReal = examListUiState.uiState.isReal,
onExamClick = onExamClick,
)
}
is UiState.Loading -> {
PageLoader()
}
is UiState.Error -> {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.internet_error),
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
}
}
WindowWidthSizeClass.Medium -> {
when (examListUiState) {
is UiState.Success -> {
ExamListView(
isReal = examListUiState.uiState.isReal,
onExamClick = onExamClick,
modifier = modifier
.background(MaterialTheme.colorScheme.surfaceContainer)
)
}
is UiState.Loading -> {
OnLoading()
}
is UiState.Error -> {
OnError()
}
}
}
WindowWidthSizeClass.Expanded -> {
Row(
modifier = modifier
) {
Card(
modifier = Modifier
.background(MaterialTheme.colorScheme.surface)
.padding(horizontal = 24.dp)
.weight(1f)
) {
when (examListUiState) {
is UiState.Success -> {
ExamListView(
isReal = examListUiState.uiState.isReal,
onExamClick = onExamClick,
modifier = Modifier
.background(MaterialTheme.colorScheme.primaryContainer)
.fillMaxSize()
)
}
is UiState.Loading -> {
OnLoading()
}
is UiState.Error -> {
OnError()
}
}
}
ExamListScreenSupportingPane(
modifier = Modifier
.width(360.dp)
.padding(end = 24.dp)
.fillMaxSize()
){
onExamClick.invoke(it)
}
}
}
}
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/ExamListScreen.kt | 154197823 |
package app.xlei.vipexam.ui.screen
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.core.data.constant.ExamType
import app.xlei.vipexam.ui.UiState
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.page.ExamTypeListView
/**
* Exam type list screen
* 试卷类型列表页面
* @param examTypeListUiState 试卷类型列表
* @param onExamTypeClick 试卷类型点击事件
* @param widthSizeClass 屏幕宽度
* @param modifier
* @receiver
* @receiver
*/
@Composable
fun ExamTypeListScreen(
examTypeListUiState: UiState<VipexamUiState.ExamTypeListUiState>,
onExamTypeClick: (ExamType) -> Unit,
onLastViewedClick: (String) -> Unit,
widthSizeClass: WindowWidthSizeClass,
modifier: Modifier = Modifier
) {
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> {
ExamTypeListView(
examTypeListUiState = examTypeListUiState,
onExamTypeClick = onExamTypeClick,
onLastViewedClick = onLastViewedClick
)
}
WindowWidthSizeClass.Medium -> {
ExamTypeListView(
examTypeListUiState = examTypeListUiState,
onExamTypeClick = onExamTypeClick,
onLastViewedClick = onLastViewedClick
)
}
WindowWidthSizeClass.Expanded -> {
Column(
modifier = modifier
.padding(horizontal = 24.dp)
.clip(MaterialTheme.shapes.extraLarge)
//.background(MaterialTheme.colorScheme.surfaceContainer)
) {
ExamTypeListView(
examTypeListUiState = examTypeListUiState,
onExamTypeClick = onExamTypeClick,
onLastViewedClick = onLastViewedClick,
modifier = Modifier
.fillMaxSize()
)
}
}
}
}
| vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/ExamTypeListScreen.kt | 160440491 |
package app.xlei.vipexam.ui
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import app.xlei.vipexam.core.data.util.NetworkMonitor
import app.xlei.vipexam.ui.navigation.AppDestinations
import app.xlei.vipexam.ui.navigation.VipExamNavigationActions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
@Composable
fun rememberVipExamAppState(
windowSizeClass: WindowWidthSizeClass,
networkMonitor: NetworkMonitor,
coroutineScope: CoroutineScope = rememberCoroutineScope(),
navController: NavHostController = rememberNavController(),
): VipExamState {
return remember(
navController,
coroutineScope,
windowSizeClass,
) {
VipExamState(
vipExamNavigationActions = VipExamNavigationActions(navController),
coroutineScope = coroutineScope,
widthSizeClass = windowSizeClass,
navController = navController,
networkMonitor,
)
}
}
@Stable
class VipExamState(
val vipExamNavigationActions: VipExamNavigationActions,
val coroutineScope: CoroutineScope,
val widthSizeClass: WindowWidthSizeClass,
val navController: NavHostController,
networkMonitor: NetworkMonitor,
) {
val shouldShowTopBar: Boolean
get() = widthSizeClass == WindowWidthSizeClass.Compact
val shouldShowNavRail: Boolean
get() = widthSizeClass == WindowWidthSizeClass.Medium
val shouldShowAppDrawer: Boolean
get() = widthSizeClass == WindowWidthSizeClass.Expanded
fun navigateToAppDestination(appDestination: AppDestinations) {
when (appDestination) {
AppDestinations.HOME_ROUTE -> vipExamNavigationActions.navigateToHome()
AppDestinations.SECOND_ROUTE -> vipExamNavigationActions.navigateToWords()
AppDestinations.SETTINGS_ROUTE -> vipExamNavigationActions.navigateToSettings()
AppDestinations.HISTORY -> vipExamNavigationActions.navigateToHistory()
AppDestinations.BOOKMARKS -> vipExamNavigationActions.navigateToBookmarks()
}
}
val isOffline = networkMonitor.isOnline
.map(Boolean::not)
.stateIn(
scope = coroutineScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = false,
)
} | vipexam/app/src/main/java/app/xlei/vipexam/ui/VipExamState.kt | 1208998739 |
package app.xlei.vipexam
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.systemBars
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.data.util.NetworkMonitor
import app.xlei.vipexam.core.database.module.Word
import app.xlei.vipexam.core.ui.AddToWordListButton
import app.xlei.vipexam.core.ui.TranslateDialog
import app.xlei.vipexam.feature.wordlist.WordListScreen
import app.xlei.vipexam.feature.wordlist.components.copyToClipboard
import app.xlei.vipexam.feature.wordlist.constant.SortMethod
import app.xlei.vipexam.preference.LanguagePreference
import app.xlei.vipexam.preference.LocalThemeMode
import app.xlei.vipexam.preference.SettingsProvider
import app.xlei.vipexam.preference.languages
import app.xlei.vipexam.ui.App
import app.xlei.vipexam.ui.rememberVipExamAppState
import app.xlei.vipexam.ui.theme.VipexamTheme
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var networkMonitor: NetworkMonitor
@Inject
lateinit var wordRepository: Repository<Word>
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT < 33) {
LanguagePreference.fromValue(languages).let {
LanguagePreference.setLocale(it)
}
}
setContent {
val widthSizeClass = calculateWindowSizeClass(this).widthSizeClass
val appState = rememberVipExamAppState(
windowSizeClass = widthSizeClass,
networkMonitor = networkMonitor,
)
val density = LocalDensity.current
val windowsInsets = WindowInsets.systemBars
val bottomInset = with(density) { windowsInsets.getBottom(density).toDp() }
val scrollAwareWindowInsets = remember(bottomInset) {
windowsInsets
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top)
.add(WindowInsets(bottom = bottomInset))
}
CompositionLocalProvider(
LocalScrollAwareWindowInsets provides scrollAwareWindowInsets
) {
SettingsProvider {
VipexamTheme(
themeMode = LocalThemeMode.current,
shouldShowNavigationRegion = appState.shouldShowAppDrawer,
) {
App(
widthSizeClass = widthSizeClass,
appState = appState
)
}
}
}
}
handleIntentData()
}
private fun getIntentText(): String? {
return intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()
?: intent?.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString()
?: intent.getCharSequenceExtra(Intent.ACTION_SEND)?.toString()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
this.intent = intent
handleIntentData()
}
private fun handleIntentData() {
getIntentText()?.let {
this.copyToClipboard(it)
setContent {
SettingsProvider {
VipexamTheme(
themeMode = LocalThemeMode.current,
) {
var showTranslateDialog by remember {
mutableStateOf(true)
}
WordListScreen(
initSortMethod = SortMethod.NEW_TO_OLD
) {
}
val context = LocalContext.current
val successTip = stringResource(id = R.string.add_to_word_list_success)
if (showTranslateDialog)
TranslateDialog(
onDismissRequest = {
finish()
},
confirmButton = {
AddToWordListButton(onClick = {
showTranslateDialog = false
Toast.makeText(context, successTip, Toast.LENGTH_SHORT)
.show()
})
}
)
}
}
}
}
}
}
val LocalScrollAwareWindowInsets =
compositionLocalOf<WindowInsets> { error("No WindowInsets provided") } | vipexam/app/src/main/java/app/xlei/vipexam/MainActivity.kt | 2137856102 |
package app.xlei.vipexam
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class VipExamApplication : Application() {
} | vipexam/app/src/main/java/app/xlei/vipexam/VipExamApplication.kt | 1066240076 |
package app.xlei.vipexam.feature.settings
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("app.xlei.vipexam.feature.settings.test", appContext.packageName)
}
} | vipexam/feature/settings/src/androidTest/java/app/xlei/vipexam/feature/settings/ExampleInstrumentedTest.kt | 192857979 |
package app.xlei.vipexam.feature.settings
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)
}
} | vipexam/feature/settings/src/test/java/app/xlei/vipexam/feature/settings/ExampleUnitTest.kt | 2705382971 |
package app.xlei.vipexam.feature.settings
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.feature.settings.components.EudicApiKeyDialog
import app.xlei.vipexam.feature.settings.components.LanguagePreferenceDialog
import app.xlei.vipexam.feature.settings.components.LongPressActionDialog
import app.xlei.vipexam.feature.settings.components.OrganizationDialog
import app.xlei.vipexam.feature.settings.components.PreferenceItem
import app.xlei.vipexam.feature.settings.components.SettingsCategory
import app.xlei.vipexam.feature.settings.components.ShowAnswerDialog
import app.xlei.vipexam.feature.settings.components.SwitchPreference
import app.xlei.vipexam.feature.settings.components.ThemeModeDialog
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalVibrate
import app.xlei.vipexam.preference.VibratePreference
import compose.icons.FeatherIcons
import compose.icons.feathericons.Menu
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
openDrawer: () -> Unit,
modifier: Modifier = Modifier,
) {
var showLanguagePreference by remember {
mutableStateOf(false)
}
var showThemeOptions by remember {
mutableStateOf(false)
}
var showShowAnswerOptions by remember {
mutableStateOf(false)
}
var showLongPressActions by remember {
mutableStateOf(false)
}
var showOrganizationDialog by remember {
mutableStateOf(false)
}
var showEudicApiKeyDialog by remember {
mutableStateOf(false)
}
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
Scaffold(
modifier = modifier
.statusBarsPadding()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
LargeTopAppBar(
title = {
Text(
stringResource(R.string.settings)
)
},
navigationIcon = {
IconButton(
onClick = openDrawer
) {
Icon(
imageVector = FeatherIcons.Menu,
contentDescription = null,
)
}
},
scrollBehavior = scrollBehavior
)
}
) { paddingValues ->
LazyColumn(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize()
.padding(horizontal = 24.dp)
) {
item {
SettingsCategory(stringResource(R.string.general))
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.app_language),
summary = stringResource(id = R.string.app_language),
) {
showLanguagePreference = true
}
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(R.string.app_theme),
summary = stringResource(R.string.app_theme_summary)
) {
showThemeOptions = true
}
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(R.string.show_answer),
summary = stringResource(R.string.show_answer_summary)
) {
showShowAnswerOptions = true
}
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(R.string.long_press_action),
summary = stringResource(R.string.long_press_action)
) {
showLongPressActions = true
}
}
item {
SwitchPreference(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.vibrate),
summary = stringResource(id = R.string.vibrate_summary),
checked = LocalVibrate.current == VibratePreference.On,
preferencesKey = DataStoreKeys.Vibrate
)
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.organiztion),
summary = stringResource(id = R.string.edit_organiztion)
) {
showOrganizationDialog = true
}
}
item {
SettingsCategory(stringResource(R.string.advanced))
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.eudic),
summary = stringResource(id = R.string.edit_eudic_apikey),
) {
showEudicApiKeyDialog = true
}
}
}
if (showLanguagePreference)
LanguagePreferenceDialog {
showLanguagePreference = false
}
if (showThemeOptions)
ThemeModeDialog {
showThemeOptions = false
}
if (showShowAnswerOptions) {
ShowAnswerDialog {
showShowAnswerOptions = false
}
}
if (showLongPressActions)
LongPressActionDialog {
showLongPressActions = false
}
if (showOrganizationDialog)
OrganizationDialog {
showOrganizationDialog = false
}
if (showEudicApiKeyDialog)
EudicApiKeyDialog {
showEudicApiKeyDialog = false
}
}
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/SettingsScreen.kt | 2013500069 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun SettingsCategory(
title: String
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
top = 20.dp,
bottom = 5.dp,
end = 5.dp
)
) {
Text(
text = title.uppercase(),
fontSize = 12.sp,
color = MaterialTheme.colorScheme.secondary
)
}
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/SettingsCategory.kt | 2499468459 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalShowAnswerOption
import app.xlei.vipexam.preference.ShowAnswerOptionPreference
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun ShowAnswerDialog(
onDismiss: () -> Unit
) {
val showAnswerOption = LocalShowAnswerOption.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.show_answer),
onDismissRequest = {
onDismiss.invoke()
},
options = listOf(
ListPreferenceOption(
name = stringResource(R.string.always),
value = ShowAnswerOptionPreference.Always.value,
isSelected = showAnswerOption == ShowAnswerOptionPreference.Always
),
ListPreferenceOption(
name = stringResource(R.string.once),
value = ShowAnswerOptionPreference.Once.value,
isSelected = showAnswerOption == ShowAnswerOptionPreference.Once
),
),
onOptionSelected = { option ->
context.dataStore.put(
DataStoreKeys.ShowAnswerOption,
option.value
)
}
)
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ShowAnswerDialog.kt | 2228119022 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun DialogButton(
modifier: Modifier = Modifier,
text: String,
onClick: () -> Unit
) {
TextButton(
modifier = modifier,
onClick = onClick
) {
Text(text)
}
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/DialogButton.kt | 3324673483 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
@Composable
fun SelectableItem(
text: String,
isSelected: Boolean = false,
onClick: () -> Unit = {}
) {
Card(
shape = RoundedCornerShape(30.dp),
modifier = Modifier
.fillMaxWidth()
.clip(
RoundedCornerShape(30.dp)
)
.clickable {
onClick.invoke()
},
colors = CardDefaults.cardColors(
containerColor = Color.Transparent
)
) {
Text(
text = text,
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
fontWeight = if (isSelected) FontWeight.ExtraBold else FontWeight.Normal,
color = MaterialTheme.colorScheme.onSurface,
)
}
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/SelectableItem.kt | 699148252 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalThemeMode
import app.xlei.vipexam.preference.ThemeModePreference
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun ThemeModeDialog(
onDismiss: () -> Unit,
) {
val themeMode = LocalThemeMode.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.select_theme),
onDismissRequest = {
onDismiss.invoke()
},
options = listOf(
ListPreferenceOption(
name = stringResource(R.string.theme_auto),
value = ThemeModePreference.Auto.value,
isSelected = themeMode == ThemeModePreference.Auto
),
ListPreferenceOption(
name = stringResource(R.string.theme_light),
value = ThemeModePreference.Light.value,
isSelected = themeMode == ThemeModePreference.Light
),
ListPreferenceOption(
name = stringResource(R.string.theme_dark),
value = ThemeModePreference.Dark.value,
isSelected = themeMode == ThemeModePreference.Dark
),
ListPreferenceOption(
name = stringResource(R.string.theme_black),
value = ThemeModePreference.Black.value,
isSelected = themeMode == ThemeModePreference.Black
)
),
onOptionSelected = { option ->
context.dataStore.put(DataStoreKeys.ThemeMode, option.value)
}
)
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ThemeModeDialog.kt | 1037749974 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun PreferenceItem(
title: String,
summary: String,
modifier: Modifier = Modifier,
onClick: () -> Unit = {}
) {
val interactionSource = remember { MutableInteractionSource() }
Row(
modifier = modifier
.fillMaxWidth()
.clickable(
interactionSource = interactionSource,
indication = null
) {
onClick.invoke()
}
) {
Column {
Text(title)
Spacer(Modifier.height(4.dp))
Text(
text = summary,
fontSize = 12.sp,
lineHeight = 18.sp
)
}
}
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/PreferenceItem.kt | 1680554183 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalOrganization
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import kotlinx.coroutines.launch
@Composable
fun OrganizationDialog(
onDismissRequest: () -> Unit,
) {
val coroutine = rememberCoroutineScope()
val context = LocalContext.current
val org = LocalOrganization.current
var organization by remember {
mutableStateOf(org.value)
}
AlertDialog(
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(onClick = {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.Organization,
organization
)
onDismissRequest.invoke()
}
}) {
Text(text = stringResource(id = R.string.okay))
}
},
title = {
Text(text = stringResource(id = R.string.edit_organiztion))
},
text = {
OutlinedTextField(
value = organization,
onValueChange = { organization = it },
shape = RoundedCornerShape(8.dp),
)
}
)
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/OrgnizationDialog.kt | 2543427119 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LanguagePreference
import app.xlei.vipexam.preference.LocalLanguage
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun LanguagePreferenceDialog(
onDismiss: () -> Unit
) {
val language = LocalLanguage.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.app_language),
onDismissRequest = {
onDismiss.invoke()
},
options = LanguagePreference.values.map {
ListPreferenceOption(
name = it.toDesc(),
value = it.value,
isSelected = it == language
)
},
onOptionSelected = { option ->
LanguagePreference.values.first {
it.value == option.value
}.apply {
context.dataStore.put(
DataStoreKeys.Language,
option.value
)
LanguagePreference.setLocale(this@apply)
}
}
)
}
| vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/LanaguagePreferenceDialog.kt | 3051392793 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalLongPressAction
import app.xlei.vipexam.preference.LongPressAction
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun LongPressActionDialog(
onDismiss: () -> Unit
) {
val longPressAction = LocalLongPressAction.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.long_press_action),
onDismissRequest = {
onDismiss.invoke()
},
options = listOf(
ListPreferenceOption(
name = stringResource(R.string.show_question),
value = LongPressAction.ShowQuestion.value,
isSelected = longPressAction.isShowQuestion()
),
ListPreferenceOption(
name = stringResource(R.string.show_translation),
value = LongPressAction.ShowTranslation.value,
isSelected = longPressAction.isShowTranslation()
),
ListPreferenceOption(
name = stringResource(R.string.none),
value = LongPressAction.None.value,
isSelected = longPressAction == LongPressAction.None
),
),
onOptionSelected = { option ->
context.dataStore.put(
DataStoreKeys.LongPressAction,
option.value
)
}
)
}
| vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/LongPressActionDialog.kt | 3347538931 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import kotlinx.coroutines.launch
@Composable
fun ListPreferenceDialog(
onDismissRequest: () -> Unit,
options: List<ListPreferenceOption>,
currentValue: Int? = null,
title: String? = null,
onOptionSelected: suspend (ListPreferenceOption) -> Unit = {}
) {
val coroutine = rememberCoroutineScope()
AlertDialog(
onDismissRequest = onDismissRequest,
title = {
if (title != null)
Text(title)
},
text = {
LazyColumn {
items(options) {
SelectableItem(
text = if (it.value == currentValue) "${it.name} ✓" else it.name,
onClick = {
coroutine.launch {
onOptionSelected.invoke(it).apply {
onDismissRequest.invoke()
}
}
},
isSelected = it.isSelected
)
}
}
},
confirmButton = {
TextButton(
onClick = {
onDismissRequest.invoke()
}
) {
Text(
stringResource(
R.string.cancel
)
)
}
},
)
}
data class ListPreferenceOption(
val name: String,
val value: Int,
val isSelected: Boolean = false
) | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ListPreferenceDialog.kt | 2970079373 |
package app.xlei.vipexam.feature.settings.components
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import app.xlei.vipexam.core.network.module.EudicRemoteDatasource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalEudicApiKey
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import compose.icons.FeatherIcons
import compose.icons.feathericons.Check
import compose.icons.feathericons.CheckCircle
import compose.icons.feathericons.X
import kotlinx.coroutines.launch
@Composable
fun EudicApiKeyDialog(
onDismissRequest: () -> Unit,
) {
val coroutine = rememberCoroutineScope()
val context = LocalContext.current
val apiKey = LocalEudicApiKey.current
var eudicApiKey by remember {
mutableStateOf(apiKey.value)
}
var available by remember {
mutableStateOf(false to false)
}
AlertDialog(
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(onClick = {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.EudicApiKey,
eudicApiKey
)
onDismissRequest.invoke()
}
}) {
Text(text = stringResource(id = R.string.okay))
}
},
title = {
Text(text = stringResource(id = R.string.edit_eudic_apikey))
},
text = {
Column {
OutlinedTextField(
value = eudicApiKey,
onValueChange = { eudicApiKey = it },
shape = RoundedCornerShape(8.dp),
)
Row(
modifier = Modifier.padding(top = 4.dp)
) {
Icon(imageVector = Icons.Default.Info, contentDescription = null)
Text(
text = stringResource(id = R.string.get_your_eudic_apikey),
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.clickable {
val intent = Intent(
Intent.ACTION_VIEW,
"https://my.eudic.net/OpenAPI/Authorization".toUri()
)
val packageManager = context.packageManager
context.startActivity(
intent.setPackage(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.resolveActivity(
intent,
PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())
)
} else {
packageManager.resolveActivity(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
}!!.activityInfo.packageName
)
)
}
.padding(start = 4.dp)
)
}
Row(
modifier = Modifier.padding(top = 4.dp)
) {
Icon(imageVector = FeatherIcons.CheckCircle, contentDescription = null)
Text(
text = stringResource(id = R.string.check_availability),
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.clickable {
coroutine.launch {
EudicRemoteDatasource.api = eudicApiKey
EudicRemoteDatasource
.check()
.onSuccess {
available = true to true
}
.onFailure {
available = true to false
}
}
}
.padding(start = 4.dp)
)
if (available.first)
when (available.second) {
true -> {
Icon(imageVector = FeatherIcons.Check, contentDescription = null)
}
false -> {
Icon(imageVector = FeatherIcons.X, contentDescription = null)
}
}
}
}
}
)
}
| vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/EudicApiKeyDialog.kt | 3860398372 |
package app.xlei.vipexam.feature.settings.components
| vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ListPreference.kt | 2444631351 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
@Composable
fun StyledIconButton(
modifier: Modifier = Modifier,
imageVector: ImageVector,
contentDescription: String? = null,
onClick: () -> Unit = {}
) {
IconButton(
onClick = {
onClick.invoke()
}
) {
Icon(
modifier = modifier,
imageVector = imageVector,
contentDescription = contentDescription
)
}
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/StyledIconButton.kt | 782613053 |
package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import kotlinx.coroutines.launch
@Composable
fun SwitchPreference(
title: String,
summary: String,
checked: Boolean,
preferencesKey: DataStoreKeys<Boolean>,
modifier: Modifier = Modifier,
) {
val interactionSource = remember { MutableInteractionSource() }
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
Row(
modifier = modifier
.fillMaxWidth()
.clickable(
interactionSource = interactionSource,
indication = null
) {
coroutine.launch {
context.dataStore.put(
preferencesKey,
!checked
)
}
},
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text(title)
Spacer(Modifier.height(4.dp))
Text(
text = summary,
fontSize = 12.sp,
lineHeight = 18.sp
)
}
Spacer(modifier = Modifier.weight(1f))
Column {
Switch(
checked = checked,
onCheckedChange = {
coroutine.launch {
context.dataStore.put(
preferencesKey,
!checked
)
}
},
colors = SwitchDefaults.colors(
checkedThumbColor = MaterialTheme.colorScheme.surfaceColorAtElevation(10.dp)
)
)
}
}
} | vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/SwitchPreference.kt | 1205091200 |
package app.xlei.vipexam.feature.wordlist
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("app.xlei.vipexam.feature.wordlist.test", appContext.packageName)
}
} | vipexam/feature/wordlist/src/androidTest/java/app/xlei/vipexam/feature/wordlist/ExampleInstrumentedTest.kt | 746190434 |
package app.xlei.vipexam.feature.wordlist
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)
}
} | vipexam/feature/wordlist/src/test/java/app/xlei/vipexam/feature/wordlist/ExampleUnitTest.kt | 2592941980 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.