path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/deleteQCollect/DeleteQCollectResponse.kt
3309695410
package app.xlei.vipexam.core.network.module.deleteQCollect import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class DeleteQCollectResponse( @SerialName("code") val code: String, @SerialName("msg") val msg: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/Resource.kt
1846246178
package app.xlei.vipexam.core.network.module data class Resource( val tid: Int, val examid: String, val examname: String, val examtypecode: String, val examstyle: String, val examdate: String, val templatecode: String, val tmplExamScore: Int, val temlExamtimeLimit: Int, val fullName: String, val examtypeII: Any?, val collectDate: Any?, val examtyleStr: String, val examTypeEName: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/login/User.kt
1772585537
package app.xlei.vipexam.core.network.module.login import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class User( @SerialName("account") val account: String = "", @SerialName("collegename") val collegename: String = "", @SerialName("credentialsSalt") val credentialsSalt: String = "", @SerialName("email") val email: String? = null, @SerialName("headimg") val headimg: String? = null, @SerialName("issuper") val issuper: Boolean = false, @SerialName("lastlogintime") val lastlogintime: String? = null, @SerialName("locked") val locked: String = "", @SerialName("managerid") val managerid: Int = 0, @SerialName("password") val password: String? = null, @SerialName("phone") val phone: String = "", @SerialName("regdate") val regdate: String = "", @SerialName("role") val role: Int = 0, @SerialName("sex") val sex: String? = null, @SerialName("token") val token: String = "", @SerialName("username") val username: String? = null )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/login/LoginResponse.kt
4188861840
package app.xlei.vipexam.core.network.module.login import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class LoginResponse( @SerialName("code") val code: String = "", @SerialName("msg") val msg: String = "", @SerialName("token") var token: String = "", @SerialName("user") val user: User = User() )
vipexam/core/template/src/androidTest/java/app/xlei/vipexam/template/ExampleInstrumentedTest.kt
2265665574
package app.xlei.vipexam.template 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.template.test", appContext.packageName) } }
vipexam/core/template/src/test/java/app/xlei/vipexam/template/ExampleUnitTest.kt
3254058872
package app.xlei.vipexam.template 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/core/template/src/main/java/app/xlei/vipexam/template/TemplateBuilder.kt
2459416575
package app.xlei.vipexam.template import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.Card 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.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.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import app.xlei.vipexam.core.ui.VipexamArticleContainer import app.xlei.vipexam.preference.LocalShowAnswer import coil.compose.AsyncImage /** * Template builder * 问题模板DSL * @constructor Create empty Template builder * @sample [TemplateBuilderSample] */ class TemplateBuilder { inner class ArticleBuilder { lateinit var title: String lateinit var content: String lateinit var contentPic: String fun Title(title: String) = this.apply { this.title = title } fun Content(content: String) = this.apply { this.content = content } fun ContentPic(contentPic: String) = this.apply { this.contentPic = contentPic } @Composable fun Render(index: Int? = null) { Column( modifier = Modifier .fillMaxWidth() .padding(top = 8.dp, start = 16.dp, end = 16.dp) .clip(RoundedCornerShape(16.dp)) .background(MaterialTheme.colorScheme.primaryContainer) ) { Row { Spacer(modifier = Modifier.weight(1f)) if (::title.isInitialized) { Text( text = title, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.End, modifier = Modifier.padding(start = 4.dp) ) } Spacer(modifier = Modifier.weight(1f)) } if (::content.isInitialized) { Text( text = (if (index != null && !::title.isInitialized) "$index. " else "") + content ) } if (::contentPic.isInitialized) { contentPic.split(",").forEach { Row { Spacer(Modifier.weight(2f)) AsyncImage( model = "https://rang.vipexam.org/images/$it.jpg", contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .padding(top = 12.dp) .align(Alignment.CenterVertically) .weight(6f) .fillMaxWidth() ) Spacer(Modifier.weight(2f)) } } } } } } val article by lazy { ArticleBuilder() } val question by lazy { QuestionBuilder() } var questions = emptyList<QuestionBuilder>() fun Article(block: ArticleBuilder.() -> Unit) = this.article.apply(block) fun Question(block: QuestionBuilder.() -> Unit) = this.question.apply(block) fun Questions(count: Int, block: QuestionBuilder.(index: Int) -> Unit) = repeat(count) { this.questions += QuestionBuilder() }.also { this.questions.forEachIndexed { index, questionBuilder -> it.apply { block(questionBuilder, index) } } } inner class QuestionBuilder { private lateinit var question: String private lateinit var optionA: String private lateinit var optionB: String private lateinit var optionC: String private lateinit var optionD: String private lateinit var options: List<String> private lateinit var answer: String private lateinit var description: String private lateinit var questionPic: String private lateinit var answerPic: String private lateinit var descriptionPic: String var choice = mutableStateOf("") fun Question(question: String) = this.apply { [email protected] = question.removeSuffix("[*]") } fun QuestionPic(pic: String) = this.apply { this.questionPic = pic } fun OptionA(option: String) = this.apply { optionA = option } fun OptionB(option: String) = this.apply { optionB = option } fun OptionC(option: String) = this.apply { optionC = option } fun OptionD(option: String) = this.apply { optionD = option } fun Options(options: List<String>) = this.apply { [email protected] = options } fun Answer(answer: String) = this.apply { [email protected] = answer.removeSuffix("[*]") } fun AnswerPic(pic: String) = this.apply { this.answerPic = pic } fun Description(desc: String) = this.apply { this.description = desc.removeSuffix("[*]") } fun DescriptionPic(descPic: String) = this.apply { this.descriptionPic = descPic } @OptIn(ExperimentalMaterial3Api::class) @Composable fun Render(index: Int? = null) { var showOptions by remember { mutableStateOf(false) } val showAnswer = LocalShowAnswer.current.isShowAnswer() Column { VipexamArticleContainer( onDragContent = (if (::question.isInitialized) question else "" + "\n\n") + (if (::answer.isInitialized && showAnswer) run { answer + "\n" + if (::description.isInitialized) description else "" } else "") ) { Column { Column( modifier = Modifier .padding(top = 8.dp, start = 16.dp, end = 16.dp) .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(MaterialTheme.colorScheme.primaryContainer) ) { if (::question.isInitialized) Text( text = (if (index != null) "$index " else "") + question, color = MaterialTheme.colorScheme.onPrimaryContainer, modifier = Modifier .padding(start = 4.dp, end = 4.dp) ) if (::questionPic.isInitialized) { questionPic.split(",").forEach { Row { Spacer(Modifier.weight(2f)) AsyncImage( model = "https://rang.vipexam.org/images/$it.jpg", contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .padding(top = 12.dp) .align(Alignment.CenterVertically) .weight(6f) .fillMaxWidth() ) Spacer(Modifier.weight(2f)) } } } choice.takeIf { it.value != "" }?.let { SuggestionChip(onClick = { }, label = { Text(choice.value) }) } if (::optionA.isInitialized && optionA != "") Column( modifier = Modifier .fillMaxWidth() .padding(start = 12.dp) .clickable { choice.value = "A" } ) { Text(text = "A. $optionA") } if (::optionB.isInitialized && optionB != "") Column( modifier = Modifier .fillMaxWidth() .padding(start = 12.dp) .clickable { choice.value = "B" } ) { Text("B. $optionB") } if (::optionC.isInitialized && optionC != "") Column( modifier = Modifier .fillMaxWidth() .padding(start = 12.dp) .clickable { choice.value = "C" } ) { Text("C. $optionC") } if (::optionD.isInitialized && optionD != "") Column( modifier = Modifier .fillMaxWidth() .padding(start = 12.dp) .clickable { choice.value = "D" } ) { Text("D. $optionD") } if (::options.isInitialized) options.forEach { option -> Card( modifier = Modifier .clickable { choice.value = option } ) { Text(option) } } } if (showAnswer && ::answer.isInitialized) { Text(text = answer, modifier = Modifier.padding(start = 24.dp)) if (::description.isInitialized) { Text(text = description, modifier = Modifier.padding(start = 24.dp)) if (::descriptionPic.isInitialized) { val pics = descriptionPic.split(',') pics.forEach { Row { Spacer(Modifier.weight(2f)) AsyncImage( model = "https://rang.vipexam.org/images/$it.jpg", contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .padding(top = 24.dp) .align(Alignment.CenterVertically) .weight(6f) .fillMaxWidth() ) Spacer(Modifier.weight(2f)) } } } } if (::answerPic.isInitialized) { val pics = answerPic.split(',') pics.forEach { Row { Spacer(Modifier.weight(2f)) AsyncImage( model = "https://rang.vipexam.org/images/$it.jpg", contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier .padding(top = 24.dp) .align(Alignment.CenterVertically) .weight(6f) .fillMaxWidth() ) Spacer(Modifier.weight(2f)) } } } } } } if (showOptions) ModalBottomSheet(onDismissRequest = { showOptions = false }) { if (::optionA.isInitialized && optionA != "") Button(onClick = { choice.value = optionA showOptions = false }) { Text("A. $optionA") } if (::optionB.isInitialized && optionB != "") Button(onClick = { choice.value = optionB }) { Text("B. $optionB") } if (::optionC.isInitialized && optionC != "") Button(onClick = { choice.value = optionC }) { Text("C. $optionC") } if (::optionD.isInitialized && optionD != "") Button(onClick = { choice.value = optionD }) { Text("D. $optionD") } } } } } @Composable fun Render( modifier: Modifier, isSubQuestion: Boolean, index: Int? = null ) { Column( modifier = modifier ) { if (isSubQuestion) { Column { article.Render(index) question.Render() questions.forEachIndexed { index, question -> question.Render(index + 1) } } } else { LazyColumn { item { article.Render(index) } item { question.Render() } questions.forEachIndexed { index, question -> item { question.Render(index + 1) } } } } } } } @Composable fun Template( modifier: Modifier = Modifier, isSubQuestion: Boolean = false, index: Int? = null, block: TemplateBuilder.() -> Unit ) = TemplateBuilder().apply(block).Render(modifier, isSubQuestion, index) @Composable private fun TemplateBuilderSample() { Template { Article { Title("title") Content("content") } Questions(5) { index -> Question(index.toString()) OptionA("A") OptionB("B") OptionC("C") OptionD("D") Answer("answer") } } }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/templateRender.kt
3284307764
package app.xlei.vipexam.template import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Text 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.TextStyle import androidx.compose.ui.text.style.TextDecoration import app.xlei.vipexam.core.network.module.getExamResponse.Muban import app.xlei.vipexam.template.cloze.ClozeView import app.xlei.vipexam.template.read.ReadView import app.xlei.vipexam.template.readCloze.ReadClozeView import app.xlei.vipexam.template.translate.TranslateView @Composable fun Render( submitMyAnswer: (String, String) -> Unit, question: String, muban: Muban, ) { when (question) { "keread", "ketread" -> ReadView(muban = muban, submitMyAnswer = submitMyAnswer) "keclozea", "ketclose" -> ClozeView(muban = muban, submitMyAnswer = submitMyAnswer) "kereadcloze" -> ReadClozeView(muban = muban, submitMyAnswer = submitMyAnswer) "kereadf" -> TranslateView(muban = muban) //"kewritinga" -> WritingView(muban = muban) "kewritinga", "kewritingb" -> Template { Questions(muban.shiti.size) { index -> Question(muban.shiti[index].primQuestion) Answer(muban.shiti[index].refAnswer) } } "kzjsjzhchoose", "crmsdschoosecn", "kpchoose", "kpmchoose" -> { Template { Questions(muban.shiti.size) { muban.shiti[it].let { shiti -> Question(shiti.primQuestion) if (shiti.primQuestion.contains("[*]")) QuestionPic(shiti.primPic) OptionA(shiti.first) OptionB(shiti.second) OptionC(shiti.third) OptionD(shiti.fourth) Answer(shiti.refAnswer) if (shiti.refAnswer.contains("[*]")) AnswerPic(shiti.answerPic) Description(shiti.discription) if (shiti.discription.contains("[*]")) DescriptionPic(shiti.discPic) } } } } "kzjsjzhbig", "crmsdxzuti", "crmsdxprogx" -> { Template { Questions(muban.shiti.size) { muban.shiti[it].let { shiti -> Question(shiti.primQuestion + "\n" + shiti.children.mapIndexed { index, child -> "${index + 1}" + child.secondQuestion }.joinToString("\n")) if (shiti.primQuestion.contains("[*]")) QuestionPic(shiti.primPic) Answer(shiti.refAnswer + shiti.children.joinToString("\n") { it.refAnswer }) if (shiti.refAnswer.contains("[*]")) AnswerPic(shiti.answerPic) Description(shiti.discription) if (shiti.discription.contains("[*]")) DescriptionPic(shiti.discPic) } } } } "crmsdschoosecnz2", "crmsdschoosecnz3", "crmsdschooseenz5", "kpdataaNAlysis" -> { LazyColumn { muban.shiti.forEachIndexed { index, shiti -> item { Template( isSubQuestion = true, index = index + 1 ) { Article { Content(shiti.primQuestion.removeSuffix("[*]")) if (shiti.primQuestion.contains("[*]")) ContentPic(shiti.primPic) } Questions(shiti.children.size) { shiti.children[it].let { child -> if (child.secondQuestion != "") Question(child.secondQuestion) OptionA(child.first) OptionB(child.second) OptionC(child.third) OptionD(child.fourth) Answer(child.refAnswer) if (child.refAnswer.contains("[*]")) AnswerPic(child.answerPic) Description(child.discription) if (child.discription.contains("[*]")) DescriptionPic(child.discPic) } } } } } } } else -> { Box( modifier = Modifier .fillMaxSize() ) { Text( text = stringResource(id = R.string.not_supported), style = TextStyle(textDecoration = TextDecoration.Underline), modifier = Modifier .align(Alignment.Center) ) } } } }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/cloze/ClozeViewModel.kt
2225165122
package app.xlei.vipexam.template.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.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() 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), ) ) } _uiState.update { it.copy( clozes = clozes ) } } private fun getOptions(shiti: Shiti): List<ClozeUiState.Option> { val options = mutableListOf<ClozeUiState.Option>() shiti.children.forEach { options.add( ClozeUiState.Option( it.secondQuestion, listOf( ClozeUiState.Word( index = "A", word = it.first ), ClozeUiState.Word( index = "B", word = it.second ), ClozeUiState.Word( index = "C", word = it.third ), ClozeUiState.Word( index = "D", word = it.fourth ), ) ) ) } return options } @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 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: String ) { _uiState.value.clozes[selectedClozeIndex].blanks[selectedQuestionIndex].choice.value = option } fun addToWordList(word: String) { viewModelScope.launch { repository.add( Word( word = word ) ) } } }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/cloze/Cloze.kt
1393167125
package app.xlei.vipexam.template.cloze import android.widget.Toast import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable 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.LocalContext 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 app.xlei.vipexam.template.R @Composable fun ClozeView( submitMyAnswer: (String, String) -> Unit, viewModel: ClozeViewModel = hiltViewModel(), muban: Muban, ) { viewModel.setMuban(muban) viewModel.SetClozes() val showAnswer = LocalShowAnswer.current.isShowAnswer() val vibrate = LocalVibrate.current.isVibrate() 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, word -> submitMyAnswer( muban.shiti[selectedClozeIndex].children[selectedQuestionIndex].questionCode, run { val shiti = muban.shiti[selectedClozeIndex].children[selectedQuestionIndex] when { shiti.first == word -> "A" shiti.second == word -> "B" shiti.third == word -> "C" shiti.fourth == word -> "D" else -> "" } } ) viewModel.setOption(selectedClozeIndex, selectedQuestionIndex, word) viewModel.toggleBottomSheet() if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress) }, toggleBottomSheet = { viewModel.toggleBottomSheet() }, showAnswer = showAnswer, addToWordList = viewModel::addToWordList, ) } @OptIn( ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class, ExperimentalFoundationApi::class ) @Composable private fun cloze( clozes: List<ClozeUiState.Cloze>, showBottomSheet: Boolean, onBlankClick: (Int) -> Unit, onOptionClicked: (Int, String) -> Unit, toggleBottomSheet: () -> Unit, showAnswer: Boolean, addToWordList: (String) -> Unit, ) { val context = LocalContext.current val scrollState = rememberLazyListState() var selectedClozeIndex by rememberSaveable { mutableStateOf(0) } var selectedOption by rememberSaveable { mutableStateOf(0) } Column { LazyColumn( state = scrollState, modifier = Modifier ) { items(clozes.size) { clozeIndex -> VipexamArticleContainer { Column( modifier = Modifier .padding(top = 16.dp, start = 16.dp, end = 16.dp) .clip(RoundedCornerShape(16.dp)) .background(MaterialTheme.colorScheme.primaryContainer) ) { ClickableText( text = clozes[clozeIndex].article.article, style = LocalTextStyle.current.copy( color = MaterialTheme.colorScheme.onPrimaryContainer ), onClick = { println(clozes[clozeIndex].article.article) clozes[clozeIndex].article.tags.forEachIndexed { index, tag -> clozes[clozeIndex].article.article.getStringAnnotations( tag = tag, start = it, end = it ).firstOrNull()?.let { selectedClozeIndex = clozeIndex selectedOption = index onBlankClick(index) } } }, modifier = Modifier .padding(start = 4.dp, end = 4.dp) ) } } VipexamArticleContainer ( onDragContent = clozes[clozeIndex].article.article.text + "\n\n" + clozes[clozeIndex].options.mapIndexed { index, option -> "${index+1}\n${option.words.joinToString { it.index + ". " + it.word }}" }.joinToString("\n\n") ){ FlowRow( horizontalArrangement = Arrangement.Start, maxItemsInEachRow = 2, ) { clozes[clozeIndex].blanks.forEachIndexed { index, blank -> Column( modifier = Modifier .weight(1f) ) { SuggestionChip( onClick = { selectedClozeIndex = clozeIndex selectedOption = index onBlankClick(index) }, label = { Text( text = blank.index + blank.choice.value ) } ) } } } } if (showAnswer) clozes[clozeIndex].blanks.forEach { blank -> VipexamArticleContainer { 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, ) { Text( text = clozes[selectedClozeIndex].article.article.toString().split(".") .first { it.contains(clozes[selectedClozeIndex].options[selectedOption].index) } + ".", modifier = Modifier.padding(24.dp) ) Text( text = clozes[selectedClozeIndex].options[selectedOption].index, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(start = 24.dp) ) FlowRow( horizontalArrangement = Arrangement.Start, maxItemsInEachRow = 2, modifier = Modifier .padding(24.dp) ) { clozes[selectedClozeIndex].options[selectedOption].words.forEach { Column( modifier = Modifier .weight(1f) .combinedClickable( onClick = {}, onLongClick = { addToWordList(it.word) Toast .makeText( context, context.getText(R.string.add_to_word_list_success), Toast.LENGTH_SHORT ) .show() } ) ) { SuggestionChip( onClick = { onOptionClicked(selectedClozeIndex, it.word) }, label = { Text("[${it.index}] ${it.word}") }, ) } } } } } } }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/cloze/ClozeUiState.kt
3882760047
package app.xlei.vipexam.template.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 words: List<Word>, ) data class Word( val index: String, val word: String, ) }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/readCloze/ReadClozeViewModel.kt
3287351753
package app.xlei.vipexam.template.readCloze 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 ReadClozeViewModel @Inject constructor( readClozeUiState: ReadClozeUiState, private val repository: Repository<Word>, ) : ViewModel() { private val _uiState = MutableStateFlow(readClozeUiState) val uiState: StateFlow<ReadClozeUiState> = _uiState.asStateFlow() fun setMuban(muban: Muban) { _uiState.update { it.copy( muban = muban ) } } @Composable fun SetArticles() { val articles = mutableListOf<ReadClozeUiState.Article>() _uiState.collectAsState().value.muban!!.shiti.forEach { articles.add( ReadClozeUiState.Article( content = 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<ReadClozeUiState.Option> { val result = mutableListOf<ReadClozeUiState.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( ReadClozeUiState.Option( index = index + 1, option = match.groupValues[1] ) ) } return result } @Composable private fun getQuestions(children: List<Children>): MutableList<ReadClozeUiState.Question> { val questions = mutableListOf<ReadClozeUiState.Question>() children.forEachIndexed { index, it -> questions.add( ReadClozeUiState.Question( index = "${index + 1}", question = it.secondQuestion, choice = rememberSaveable { mutableStateOf("") }, refAnswer = it.refAnswer, description = it.discription ) ) } return questions } }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/readCloze/ReadClozeUiState.kt
1566778151
package app.xlei.vipexam.template.readCloze import androidx.compose.runtime.MutableState import app.xlei.vipexam.core.network.module.getExamResponse.Muban data class ReadClozeUiState( val muban: Muban? = null, var showBottomSheet: Boolean = false, var showOptionsSheet: Boolean = false, val articles: List<Article> ) { data class Article( 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/core/template/src/main/java/app/xlei/vipexam/template/readCloze/ReadCloze.kt
3571601354
package app.xlei.vipexam.template.readCloze 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.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 ReadClozeView( submitMyAnswer: (String, String) -> Unit, viewModel: ReadClozeViewModel = hiltViewModel(), muban: Muban, ) { viewModel.setMuban(muban) viewModel.SetArticles() val uiState by viewModel.uiState.collectAsState() val vibrate = LocalVibrate.current.isVibrate() val haptics = LocalHapticFeedback.current var selectedQuestionIndex by rememberSaveable { mutableIntStateOf(0) } ReadCloze( 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) }, ) } @OptIn( ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class ) @Composable private fun ReadCloze( showBottomSheet: Boolean, showOptionsSheet: Boolean, articles: List<ReadClozeUiState.Article>, toggleBottomSheet: () -> Unit, toggleOptionsSheet: () -> Unit, onArticleLongClicked: () -> Unit, onQuestionClicked: (Int) -> Unit, onOptionClicked: (Int, String) -> Unit, ) { val showAnswer = LocalShowAnswer.current.isShowAnswer() 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.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].content, color = MaterialTheme.colorScheme.onPrimaryContainer, modifier = Modifier .padding(16.dp) ) } } } items(article.questions.size) { VipexamArticleContainer { 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 -> VipexamArticleContainer { 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/core/template/src/main/java/app/xlei/vipexam/template/translate/TranslateUiState.kt
2143270813
package app.xlei.vipexam.template.translate import androidx.compose.ui.text.AnnotatedString import app.xlei.vipexam.core.network.module.getExamResponse.Muban data class TranslateUiState( val muban: Muban? = null, val translations: List<Translation>, ) { data class Translation( val content: AnnotatedString, val sentences: List<Sentence> ) data class Sentence( val index: Int, val sentence: String, val refAnswer: String, ) }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/translate/TranslateViewModel.kt
1726237258
package app.xlei.vipexam.template.translate import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.withStyle 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( content = getContent(it.primQuestion), sentences = getUnderlinedSentences(it.primQuestion) .mapIndexed { index, sentence -> TranslateUiState.Sentence( index = index + 1, sentence = sentence, refAnswer = it.children[index].refAnswer ) } ) ) } _uiState.update { it.copy( translations = translations ) } } private fun getContent(content: String): AnnotatedString { val pattern = Regex("""<u>(.*?)<\/u>""") val matches = pattern.findAll(content) return buildAnnotatedString { var currentPosition = 0 matches.forEach { match -> val startIndex = match.range.first val endIndex = match.range.last + 1 append(content.substring(currentPosition, startIndex)) withStyle(style = SpanStyle(textDecoration = TextDecoration.Underline)) { append( content.substring(startIndex, endIndex).removePrefix("<u>") .removeSuffix("</u>") ) } currentPosition = endIndex } } } private fun getUnderlinedSentences(content: String) = Regex("""<u>(.*?)<\/u>""") .findAll(content) .map { it.value.removePrefix("<u>").removeSuffix("</u>") } .toList() }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/translate/Translate.kt
170340326
package app.xlei.vipexam.template.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, ) { viewModel.setMuban(muban) viewModel.setTranslations() val uiState by viewModel.uiState.collectAsState() Translate( translations = uiState.translations, ) } @Composable private fun Translate( translations: List<TranslateUiState.Translation>, ) { val showAnswer = LocalShowAnswer.current.isShowAnswer() val scrollState = rememberLazyListState() LazyColumn( state = scrollState ) { items(translations.size) { VipexamArticleContainer( onDragContent = translations[it].content.text ) { Column( modifier = Modifier .padding(16.dp) .clip(RoundedCornerShape(16.dp)) .background(MaterialTheme.colorScheme.primaryContainer) ) { Text( text = translations[it].content, color = MaterialTheme.colorScheme.onPrimaryContainer, modifier = Modifier.padding(16.dp) ) } } translations[it].sentences.forEach { sentence -> VipexamArticleContainer( onDragContent = sentence.sentence + "\n\n" + sentence.refAnswer ) { Column( modifier = Modifier .padding(16.dp) .clip(RoundedCornerShape(16.dp)) .background(MaterialTheme.colorScheme.primaryContainer) ) { Text( text = "${sentence.index}. ${sentence.sentence}", color = MaterialTheme.colorScheme.onPrimaryContainer, modifier = Modifier.padding(16.dp) ) } if (showAnswer) Text( text = sentence.refAnswer, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(16.dp) ) } } } } }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/read/ReadUiState.kt
552372447
package app.xlei.vipexam.template.read import androidx.compose.runtime.MutableState import app.xlei.vipexam.core.network.module.getExamResponse.Muban data class ReadUiState( 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/core/template/src/main/java/app/xlei/vipexam/template/read/ReadViewModel.kt
2637641769
package app.xlei.vipexam.template.read 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.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 ReadViewModel @Inject constructor( readUiState: ReadUiState, ) : ViewModel() { private val _uiState = MutableStateFlow(readUiState) val uiState: StateFlow<ReadUiState> = _uiState.asStateFlow() fun setMuban(muban: Muban) { _uiState.update { it.copy( muban = muban ) } } @Composable fun SetArticles() { val articles = mutableListOf<ReadUiState.Article>() _uiState.collectAsState().value.muban!!.shiti.forEachIndexed { index, it -> articles.add( ReadUiState.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<ReadUiState.Question> { val questions = mutableListOf<ReadUiState.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( ReadUiState.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<ReadUiState.Option> { val options = mutableListOf<ReadUiState.Option>() options.add( ReadUiState.Option( index = "A", option = children.first, ) ) options.add( ReadUiState.Option( index = "B", option = children.second, ) ) options.add( ReadUiState.Option( index = "C", option = children.third, ) ) options.add( ReadUiState.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/core/template/src/main/java/app/xlei/vipexam/template/read/Read.kt
231930464
package app.xlei.vipexam.template.read 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 ReadView( submitMyAnswer: (String, String) -> Unit, muban: Muban, viewModel: ReadViewModel = hiltViewModel(), ) { viewModel.setMuban(muban) viewModel.SetArticles() val uiState by viewModel.uiState.collectAsState() val haptics = LocalHapticFeedback.current var selectedQuestionIndex by rememberSaveable { mutableIntStateOf(0) } Read( 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 Read( articles: List<ReadUiState.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 -> Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) .clip(RoundedCornerShape(16.dp)) .background(MaterialTheme.colorScheme.primaryContainer) ) { VipexamArticleContainer( onClick = { 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 -> option.option.takeIf { it != "" }?.let { 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 { VipexamArticleContainer { 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/core/template/src/main/java/app/xlei/vipexam/template/templateModule.kt
168993466
package app.xlei.vipexam.template import app.xlei.vipexam.template.cloze.ClozeUiState import app.xlei.vipexam.template.read.ReadUiState import app.xlei.vipexam.template.readCloze.ReadClozeUiState import app.xlei.vipexam.template.translate.TranslateUiState import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) class templateModule { @Provides fun providesClozeUiState() = ClozeUiState(clozes = emptyList()) @Provides fun providesReadUiState() = ReadUiState(articles = emptyList()) @Provides fun providesReadClozeUiState() = ReadClozeUiState(articles = emptyList()) @Provides fun providesTranslateUiState() = TranslateUiState(translations = emptyList()) }
vipexam/core/template/src/main/java/app/xlei/vipexam/template/writing/writting.kt
4155040248
package app.xlei.vipexam.template.writing import androidx.compose.foundation.background 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.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.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 app.xlei.vipexam.ui.question.writing.WritingUiState import app.xlei.vipexam.ui.question.writing.WritingViewModel import coil.compose.AsyncImage @Composable fun WritingView( viewModel: WritingViewModel = hiltViewModel(), muban: Muban, ) { viewModel.setMuban(muban) viewModel.setWritings() val uiState by viewModel.uiState.collectAsState() writing( writings = uiState.writings, ) } @Composable private fun writing( writings: List<WritingUiState.Writing>, ) { val showAnswer = LocalShowAnswer.current.isShowAnswer() 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/core/template/src/main/java/app/xlei/vipexam/template/writing/WritingUiState.kt
2344998108
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/core/template/src/main/java/app/xlei/vipexam/template/writing/WritingViewModel.kt
3735754709
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/core/preference/src/androidTest/java/app/xlei/vipexam/preference/ExampleInstrumentedTest.kt
4008356912
package app.xlei.vipexam.preference 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.preference.test", appContext.packageName) } }
vipexam/core/preference/src/test/java/app/xlei/vipexam/preference/ExampleUnitTest.kt
2990892288
package app.xlei.vipexam.preference 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/core/preference/src/main/java/app/xlei/vipexam/preference/Language.kt
266833837
package app.xlei.vipexam.preference import android.content.Context import androidx.appcompat.app.AppCompatDelegate import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import androidx.core.os.LocaleListCompat import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import java.util.Locale val Context.languages: Int get() = this.dataStore.get(DataStoreKeys.Language) ?: 0 sealed class LanguagePreference(val value: Int) : Preference() { data object UseDeviceLanguages : LanguagePreference(0) data object ChineseSimplified : LanguagePreference(1) data object English : LanguagePreference(2) override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.Language, value ) } } private fun toLocale(): Locale? = when (this) { UseDeviceLanguages -> null ChineseSimplified -> Locale.forLanguageTag("zh-Hans") English -> Locale("en") } private fun toLocaleList(): LocaleListCompat = toLocale()?.let { LocaleListCompat.create(it) } ?: LocaleListCompat.getEmptyLocaleList() @Composable fun toDesc() = stringResource( id = when (this) { UseDeviceLanguages -> R.string.use_device_languages ChineseSimplified -> R.string.chinese_simplified English -> R.string.english } ) companion object { val default = UseDeviceLanguages val values = listOf( UseDeviceLanguages, ChineseSimplified, English, ) fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.Language.key]) { 0 -> UseDeviceLanguages 1 -> ChineseSimplified 2 -> English else -> default } fun fromValue(value: Int): LanguagePreference = when (value) { 0 -> UseDeviceLanguages 1 -> ChineseSimplified 2 -> English else -> default } fun setLocale(preference: LanguagePreference) { AppCompatDelegate.setApplicationLocales(preference.toLocaleList()) } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/Settings.kt
1243090257
package app.xlei.vipexam.preference import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.collectAsState import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import kotlinx.coroutines.flow.map val LocalThemeMode = compositionLocalOf<ThemeModePreference> { ThemeModePreference.default } val LocalVibrate = compositionLocalOf<VibratePreference> { VibratePreference.default } val LocalShowAnswer = compositionLocalOf<ShowAnswerPreference> { ShowAnswerPreference.default } val LocalLongPressAction = compositionLocalOf<LongPressAction> { LongPressAction.default } val LocalShowAnswerOption = compositionLocalOf<ShowAnswerOptionPreference> { ShowAnswerOptionPreference.default } val LocalOrganization = compositionLocalOf<Organization> { Organization.default } val LocalLanguage = compositionLocalOf<LanguagePreference> { LanguagePreference.default } val LocalEudicApiKey = compositionLocalOf<EudicApiKey> { EudicApiKey.default } val LocalPinnedExams = compositionLocalOf<PinnedExams> { PinnedExams.default } data class Settings( val themeMode: ThemeModePreference = ThemeModePreference.default, val vibrate: VibratePreference = VibratePreference.default, val showAnswer: ShowAnswerPreference = ShowAnswerPreference.default, val longPressAction: LongPressAction = LongPressAction.default, val showAnswerOptionPreference: ShowAnswerOptionPreference = ShowAnswerOptionPreference.default, val organization: Organization = Organization.default, val language: LanguagePreference = LanguagePreference.default, val localEudicApiKey: EudicApiKey = EudicApiKey.default, val pinnedExams: PinnedExams = PinnedExams.default ) @Composable fun SettingsProvider( content: @Composable () -> Unit ) { val context = LocalContext.current val settings by remember { context.dataStore.data.map { it.toSettings() } }.collectAsState(initial = Settings()) CompositionLocalProvider( LocalThemeMode provides settings.themeMode, LocalVibrate provides settings.vibrate, LocalShowAnswer provides settings.showAnswer, LocalLongPressAction provides settings.longPressAction, LocalShowAnswerOption provides settings.showAnswerOptionPreference, LocalOrganization provides settings.organization, LocalLanguage provides settings.language, LocalEudicApiKey provides settings.localEudicApiKey, LocalPinnedExams provides settings.pinnedExams, ) { content() } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/ShowAnswerOption.kt
1109915769
package app.xlei.vipexam.preference import android.content.Context import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class ShowAnswerOptionPreference(val value: Int) : Preference() { data object Once : ShowAnswerOptionPreference(0) data object Always : ShowAnswerOptionPreference(1) override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.ShowAnswerOption, value ) } } companion object { val default = Once fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.ShowAnswerOption.key]) { 0 -> Once 1 -> Always else -> default } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/DataStore.kt
3653236433
package app.xlei.vipexam.preference import android.content.Context import android.util.Log import androidx.datastore.core.DataStore import androidx.datastore.core.IOException import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext val Context.dataStore by preferencesDataStore( name = "settings", ) suspend fun <T> DataStore<Preferences>.put(dataStoreKeys: DataStoreKeys<T>, value: T) { this.edit { withContext(Dispatchers.IO) { it[dataStoreKeys.key] = value } } } fun <T> DataStore<Preferences>.putBlocking(dataStoreKeys: DataStoreKeys<T>, value: T) { runBlocking { [email protected] { it[dataStoreKeys.key] = value } } } @Suppress("UNCHECKED_CAST") fun <T> DataStore<Preferences>.get(dataStoreKeys: DataStoreKeys<T>): T? { return runBlocking { [email protected] { exception -> if (exception is IOException) { Log.e("RLog", "Get data store error $exception") exception.printStackTrace() emit(emptyPreferences()) } else { throw exception } }.map { it[dataStoreKeys.key] }.first() as T } } sealed class DataStoreKeys<T> { abstract val key: Preferences.Key<T> data object ThemeMode : DataStoreKeys<Int>() { override val key: Preferences.Key<Int> get() = intPreferencesKey("themeMode") } data object Vibrate : DataStoreKeys<Boolean>() { override val key: Preferences.Key<Boolean> get() = booleanPreferencesKey("vibrate") } data object ShowAnswer : DataStoreKeys<Boolean>() { override val key: Preferences.Key<Boolean> get() = booleanPreferencesKey("showAnswer") } data object LongPressAction : DataStoreKeys<Int>() { override val key: Preferences.Key<Int> get() = intPreferencesKey("longPressAction") } data object ShowAnswerOption : DataStoreKeys<Int>() { override val key: Preferences.Key<Int> get() = intPreferencesKey("showAnswerOption") } data object Organization : DataStoreKeys<String>() { override val key: Preferences.Key<String> get() = stringPreferencesKey("organization") } data object Language : DataStoreKeys<Int>() { override val key: Preferences.Key<Int> get() = intPreferencesKey("language") } data object EudicApiKey : DataStoreKeys<String>() { override val key: Preferences.Key<String> get() = stringPreferencesKey("LocalEudicApiKey") } data object PinnedExams : DataStoreKeys<String>() { override val key: Preferences.Key<String> get() = stringPreferencesKey("PinnedExams") } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/ThemeModePreference.kt
529446525
package app.xlei.vipexam.preference import android.content.Context import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class ThemeModePreference(val value: Int) : Preference() { data object Auto : ThemeModePreference(0) data object Light : ThemeModePreference(1) data object Dark : ThemeModePreference(2) data object Black : ThemeModePreference(3) override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.ThemeMode, value ) } } @Composable @ReadOnlyComposable fun isDarkTheme() = when (this) { Auto -> isSystemInDarkTheme() Light -> false Dark -> true Black -> true } companion object { val default = Auto val values = listOf(Auto, Light, Dark, Black) fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.ThemeMode.key]) { 0 -> Auto 1 -> Light 2 -> Dark 3 -> Black else -> default } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/ShowAnswerPreference.kt
3864665230
package app.xlei.vipexam.preference import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class ShowAnswerPreference(val value: Boolean) : Preference() { data object On : ShowAnswerPreference(true) data object Off : ShowAnswerPreference(false) @Composable @ReadOnlyComposable fun isShowAnswer() = when (this) { On -> true Off -> false } override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.ShowAnswer, value ) } } companion object { val default = Off fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.ShowAnswer.key]) { true -> On false -> Off else -> default } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/EudicApiKey.kt
2137667307
package app.xlei.vipexam.preference import android.content.Context import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class EudicApiKey(val value: String) : Preference() { data object Empty : EudicApiKey("") data class Some(val apiKey: String?) : EudicApiKey(apiKey ?: "") override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.EudicApiKey, value ) } } companion object { val default = Empty fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.EudicApiKey.key]) { "" -> Empty else -> Some(preferences[DataStoreKeys.EudicApiKey.key]) } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/PinnedExams.kt
2986556453
package app.xlei.vipexam.preference import android.content.Context import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class PinnedExams(val value: String) : Preference() { data object None : PinnedExams("") data class Some(val exam: String?) : PinnedExams(value = exam ?: "") override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.Organization, value ) } } companion object { val default = None fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.PinnedExams.key]) { "" -> None else -> Some(preferences[DataStoreKeys.PinnedExams.key]) } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/Preference.kt
355330905
package app.xlei.vipexam.preference import android.content.Context import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope sealed class Preference { abstract fun put(context: Context, scope: CoroutineScope) } fun Preferences.toSettings(): Settings { return Settings( themeMode = ThemeModePreference.fromPreferences(this), vibrate = VibratePreference.fromPreferences(this), showAnswer = ShowAnswerPreference.fromPreferences(this), longPressAction = LongPressAction.fromPreferences(this), showAnswerOptionPreference = ShowAnswerOptionPreference.fromPreferences(this), organization = Organization.fromPreferences(this), language = LanguagePreference.fromPreferences(this), localEudicApiKey = EudicApiKey.fromPreferences(this), pinnedExams = PinnedExams.fromPreferences(this), ) }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/LongPressAction.kt
3860202440
package app.xlei.vipexam.preference import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class LongPressAction(val value: Int) : Preference() { data object None : LongPressAction(0) data object ShowQuestion : LongPressAction(1) data object ShowTranslation : LongPressAction(2) override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.LongPressAction, value ) } } @Composable @ReadOnlyComposable fun isShowQuestion() = this is ShowQuestion @Composable @ReadOnlyComposable fun isShowTranslation() = this is ShowTranslation companion object { val default = None fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.LongPressAction.key]) { 0 -> None 1 -> ShowQuestion 2 -> ShowTranslation else -> default } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/VibratePreference.kt
1802512123
package app.xlei.vipexam.preference import android.content.Context import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class VibratePreference(val value: Boolean) : Preference() { data object On : VibratePreference(true) data object Off : VibratePreference(false) override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.Vibrate, value ) } } fun isVibrate() = when (this) { On -> true Off -> false } companion object { val default = On fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.Vibrate.key]) { true -> On false -> Off else -> default } } }
vipexam/core/preference/src/main/java/app/xlei/vipexam/preference/Organization.kt
1830560372
package app.xlei.vipexam.preference import android.content.Context import androidx.datastore.preferences.core.Preferences import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch sealed class Organization(val value: String) : Preference() { data object Default : Organization("吉林大学") data class Custom(val organization: String?) : Organization(value = organization ?: "") override fun put(context: Context, scope: CoroutineScope) { scope.launch { context.dataStore.put( DataStoreKeys.Organization, value ) } } companion object { val default = Default fun fromPreferences(preferences: Preferences) = when (preferences[DataStoreKeys.Organization.key]) { "吉林大学" -> Default else -> Custom(preferences[DataStoreKeys.Organization.key]) } } }
vipexam/core/data/src/androidTest/java/app/xlei/vipexam/core/data/ExampleInstrumentedTest.kt
3958186011
package app.xlei.vipexam.core.data 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.core.data.test", appContext.packageName) } }
vipexam/core/data/src/androidTest/java/app/xlei/data/ExampleInstrumentedTest.kt
4063835108
package app.xlei.data 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.data.test", appContext.packageName) } }
vipexam/core/data/src/test/java/app/xlei/vipexam/core/data/ExampleUnitTest.kt
2793821503
package app.xlei.vipexam.core.data 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/core/data/src/test/java/app/xlei/data/ExampleUnitTest.kt
4086928371
package app.xlei.data 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/core/data/src/main/java/app/xlei/vipexam/core/data/repository/WordRepository.kt
180098271
package app.xlei.vipexam.core.data.repository import android.util.Log import app.xlei.vipexam.core.database.dao.WordDao import app.xlei.vipexam.core.database.module.Word import javax.inject.Inject private const val TAG = "WORDREPOSITORY" class WordRepository @Inject constructor( private val wordDao: WordDao ) : Repository<Word> { override fun getAll() = run { wordDao.getAllWords() } override suspend fun add(item: Word) = run { Log.d(TAG, "add word ${item.word}") wordDao.insert(item) } override suspend fun remove(item: Word) = wordDao.delete(item) }
vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/repository/ExamHistoryRepository.kt
342383433
package app.xlei.vipexam.core.data.repository import app.xlei.vipexam.core.database.module.ExamHistory import kotlinx.coroutines.flow.Flow interface ExamHistoryRepository { fun getAllExamHistory(): Flow<List<ExamHistory>> suspend fun removeAllHistory() suspend fun getExamHistoryByExamId(examId: String): ExamHistory? suspend fun getLastOpened(): Flow<ExamHistory?> suspend fun removeHistory(examHistory: ExamHistory) suspend fun insertHistory(examName: String, examId: String) }
vipexam/core/data/src/main/java/app/xlei/vipexam/core/data/repository/ExamHistoryRepositoryImpl.kt
1960969947
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/Repository.kt
2456479529
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/UserRepository.kt
3313168887
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/BookmarkRepository.kt
3019125740
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/BookmarkRepositoryImpl.kt
1277563676
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/di/DataModule.kt
2536991352
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/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 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/NetworkMonitor.kt
3036587108
/* * 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/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.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/MomoLookUpPagingSource.kt
1313840605
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/constant/ShowAnswerOption.kt
2870312791
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/ThemeMode.kt
1228675298
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/ExamType.kt
978997221
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/LongPressAction.kt
2240429556
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/Constants.kt
330427130
package app.xlei.vipexam.core.data.constant object Constants { const val ORGANIZATION = "吉林大学" }
vipexam/core/domain/src/androidTest/java/app/xlei/vipexam/core/domain/ExampleInstrumentedTest.kt
1650166239
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/test/java/app/xlei/vipexam/core/domain/ExampleUnitTest.kt
1898231474
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/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.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/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 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/RemoveUserUseCase.kt
4073596696
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/DomainModule.kt
2191003011
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/app/src/androidTest/java/app/xlei/vipexam/ExampleInstrumentedTest.kt
1161289513
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/test/java/app/xlei/vipexam/ExampleUnitTest.kt
2395923767
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/main/java/app/xlei/vipexam/ui/appbar/AppBarViewModel.kt
1604255051
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/VipExamAppBar.kt
2220986911
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/AppBarTitle.kt
1993815544
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/expanded/ExamScreenSupportingPane.kt
2456424370
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/ExamScreenSupportingPaneViewModel.kt
1396331604
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/ExamListScreenSupportingPane.kt
490554806
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/VipexamUiState.kt
462658427
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/page/ExamListPage.kt
72554002
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/ExamTypeListPage.kt
4167111728
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/ExamListViewModel.kt
500961858
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/ExamPage.kt
472295559
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/LoginPage.kt
3077017272
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/VipExamMainScreenViewModel.kt
1479435027
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/VipExamApp.kt
3610352835
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/navigation/VipExamNavHost.kt
2215894241
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/VipExamNavigation.kt
3366444535
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/HomeScreenNavigation.kt
3998086491
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/Screen.kt
3954793145
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/question/zread/ZreadUiState.kt
3908994442
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/ZreadViewModel.kt
3155564731
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/Zread.kt
2132223536
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/listening/ListeningViewModel.kt
1680922405
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/Listening.kt
1054445354
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/ListeningUiState.kt
1458912462
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/cloze/ClozeViewModel.kt
353729913
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/cloze.kt
2872986865
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/ClozeUiState.kt
3390355640
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/translate/TranslateUiState.kt
3352570348
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/TranslateViewModel.kt
2831446222
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/Translate.kt
724310282
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/QuestionsViewModel.kt
410083253
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/QuestionsModule.kt
2169955259
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/QuestionsUiState.kt
3238309759
package app.xlei.vipexam.ui.question import app.xlei.vipexam.core.network.module.getExamResponse.Muban data class QuestionsUiState( val mubanList: List<Muban>?=null )