content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package app.xlei.vipexam.core.ui
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/ui/src/test/java/app/xlei/vipexam/core/ui/ExampleUnitTest.kt | 1016663293 |
package app.xlei.vipexam.core.ui
import android.content.ClipboardManager
import android.content.ComponentName
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.os.Build
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.platform.TextToolbar
import androidx.compose.ui.platform.TextToolbarStatus
/**
* Empty text toolbar
*
* @property onHide
* @property onSelect
* in [app.xlei.vipexam.feature.wordlist.components.TranslationSheet], [VipexamTextToolbar] don't
* work, we use this.
*/
class EmptyTextToolbar(
private val onHide: (() -> Unit)? = null,
private val onSelect: () -> Unit,
) : TextToolbar {
override val status: TextToolbarStatus = TextToolbarStatus.Hidden
override fun hide() {
onHide?.invoke()
}
override fun showMenu(
rect: Rect,
onCopyRequested: (() -> Unit)?,
onPasteRequested: (() -> Unit)?,
onCutRequested: (() -> Unit)?,
onSelectAllRequested: (() -> Unit)?,
) {
onSelect.invoke()
onCopyRequested?.invoke()
}
}
class VipexamTextToolbar(
private val onHide: (() -> Unit)? = null,
private val view: View,
onTranslate: () -> Unit,
) : TextToolbar {
private var actionMode: ActionMode? = null
private val textActionModeCallback: VipexamTextActionModeCallback =
VipexamTextActionModeCallback(
context = view.context,
onActionModeDestroy = {
actionMode = null
},
onTranslate = onTranslate
)
override var status: TextToolbarStatus = TextToolbarStatus.Hidden
private set
override fun hide() {
status = TextToolbarStatus.Hidden
actionMode?.finish()
actionMode = null
onHide?.invoke()
}
override fun showMenu(
rect: Rect,
onCopyRequested: (() -> Unit)?,
onPasteRequested: (() -> Unit)?,
onCutRequested: (() -> Unit)?,
onSelectAllRequested: (() -> Unit)?,
) {
textActionModeCallback.rect = rect
textActionModeCallback.onCopyRequested = onCopyRequested
textActionModeCallback.onCutRequested = onCutRequested
textActionModeCallback.onPasteRequested = onPasteRequested
textActionModeCallback.onSelectAllRequested = onSelectAllRequested
if (actionMode == null) {
status = TextToolbarStatus.Shown
actionMode =
view.startActionMode(
FloatingTextActionModeCallback(textActionModeCallback),
ActionMode.TYPE_FLOATING,
)
} else {
actionMode?.invalidate()
}
}
}
class VipexamTextActionModeCallback(
val context: Context,
val onActionModeDestroy: (() -> Unit)? = null,
var rect: Rect = Rect.Zero,
var onCopyRequested: (() -> Unit)? = null,
var onPasteRequested: (() -> Unit)? = null,
var onCutRequested: (() -> Unit)? = null,
var onSelectAllRequested: (() -> Unit)? = null,
val onTranslate: () -> Unit,
) : ActionMode.Callback {
private val displayNameComparator by lazy {
ResolveInfo.DisplayNameComparator(packageManager)
}
private val packageManager by lazy {
context.packageManager
}
private val clipboardManager by lazy {
context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
}
private val textProcessors = mutableListOf<ComponentName>()
override fun onCreateActionMode(
mode: ActionMode?,
menu: Menu?,
): Boolean {
requireNotNull(menu)
requireNotNull(mode)
onCopyRequested?.let {
menu.add(
0,
0,
0,
R.string.translate
)
addTextProcessors(menu)
}
return true
}
override fun onPrepareActionMode(
mode: ActionMode?,
menu: Menu?,
): Boolean {
if (mode == null || menu == null) return false
updateMenuItems(menu)
return true
}
override fun onActionItemClicked(
mode: ActionMode?,
item: MenuItem?,
): Boolean {
when (val itemId = item!!.itemId) {
0 -> {
onCopyRequested?.invoke()
onTranslate.invoke()
}
else -> {
if (itemId < 100) return false
onCopyRequested?.invoke()
val clip = clipboardManager.primaryClip
if (clip != null && clip.itemCount > 0) {
textProcessors.getOrNull(itemId - 100)?.let { cn ->
context.startActivity(
Intent(Intent.ACTION_PROCESS_TEXT).apply {
type = "text/plain"
component = cn
putExtra(Intent.EXTRA_PROCESS_TEXT, clip.getItemAt(0).text)
}
)
}
}
}
}
mode?.finish()
return true
}
override fun onDestroyActionMode(mode: ActionMode?) {
onActionModeDestroy?.invoke()
}
private fun addTextProcessors(menu: Menu) {
textProcessors.clear()
val intentActionProcessText = Intent(Intent.ACTION_PROCESS_TEXT).apply {
type = "text/plain"
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.queryIntentActivities(
intentActionProcessText,
PackageManager.ResolveInfoFlags.of(0L)
)
} else {
packageManager.queryIntentActivities(intentActionProcessText, 0)
}
.sortedWith(displayNameComparator)
.forEachIndexed { index, info ->
val label = info.loadLabel(packageManager)
val id = 100 + index
if (menu.findItem(id) == null) {
// groupId, itemId, order, title
menu.add(1, id, id, label)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW)
}
textProcessors.add(
ComponentName(
info.activityInfo.applicationInfo.packageName,
info.activityInfo.name,
),
)
}
}
private fun updateMenuItems(menu: Menu) {
onCopyRequested?.let {
addTextProcessors(menu)
}
}
}
internal class FloatingTextActionModeCallback(
private val callback: VipexamTextActionModeCallback,
) : ActionMode.Callback2() {
override fun onActionItemClicked(
mode: ActionMode?,
item: MenuItem?,
): Boolean {
return callback.onActionItemClicked(mode, item)
}
override fun onCreateActionMode(
mode: ActionMode?,
menu: Menu?,
): Boolean {
return callback.onCreateActionMode(mode, menu)
}
override fun onPrepareActionMode(
mode: ActionMode?,
menu: Menu?,
): Boolean {
return callback.onPrepareActionMode(mode, menu)
}
override fun onDestroyActionMode(mode: ActionMode?) {
callback.onDestroyActionMode(mode)
}
override fun onGetContentRect(
mode: ActionMode?,
view: View?,
outRect: android.graphics.Rect?,
) {
val rect = callback.rect
outRect?.set(
rect.left.toInt(),
rect.top.toInt(),
rect.right.toInt(),
rect.bottom.toInt(),
)
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/EmptyTextToolbar.kt | 1776917720 |
package app.xlei.vipexam.core.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun ErrorMessage(
message: String,
modifier: Modifier = Modifier,
onClickRetry: () -> Unit
) {
Row(
modifier = modifier.padding(10.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = message,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.weight(1f),
maxLines = 2
)
OutlinedButton(onClick = onClickRetry) {
Text(text = "retry")
}
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/ErrorMessage.kt | 1666416582 |
package app.xlei.vipexam.core.ui.util
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
@Composable
fun LazyListState.isScrollingUp(): Boolean {
var previousIndex by remember(this) { mutableIntStateOf(firstVisibleItemIndex) }
var previousScrollOffset by remember(this) { mutableIntStateOf(firstVisibleItemScrollOffset) }
return remember(this) {
derivedStateOf {
if (previousIndex != firstVisibleItemIndex) {
previousIndex > firstVisibleItemIndex
} else {
previousScrollOffset >= firstVisibleItemScrollOffset
}.also {
previousIndex = firstVisibleItemIndex
previousScrollOffset = firstVisibleItemScrollOffset
}
}
}.value
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/util/scrollutil.kt | 659661404 |
package app.xlei.vipexam.core.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@Composable
fun OnLoading(onLoadingTextId: Int = R.string.loading){
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = onLoadingTextId),
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
CircularProgressIndicator(Modifier.padding(top = 10.dp))
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/OnLoading.kt | 376698902 |
package app.xlei.vipexam.core.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
@Composable
fun PageLoader(modifier: Modifier = Modifier) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = R.string.loading),
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/PageLoader.kt | 2388408973 |
package app.xlei.vipexam.core.ui
import android.view.SoundEffectConstants
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun Banner(
modifier: Modifier = Modifier,
title: String,
desc: String? = null,
backgroundColor: Color = MaterialTheme.colorScheme.primaryContainer,
icon: ImageVector? = null,
action: (@Composable () -> Unit)? = null,
onClick: () -> Unit = {},
) {
val view = LocalView.current
Surface(
modifier = modifier
.fillMaxWidth()
.height(if (!desc.isNullOrBlank()) 88.dp else Dp.Unspecified),
color = Color.Unspecified,
) {
Row(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp)
.clip(RoundedCornerShape(32.dp))
.background(backgroundColor alwaysLight true)
.clickable {
view.playSoundEffect(SoundEffectConstants.CLICK)
onClick()
}
.padding(16.dp, 20.dp),
verticalAlignment = Alignment.CenterVertically
) {
icon?.let { icon ->
Crossfade(targetState = icon, label = "") {
Icon(
imageVector = it,
contentDescription = null,
modifier = Modifier.padding(end = 16.dp),
tint = MaterialTheme.colorScheme.onSurface alwaysLight true,
)
}
}
Column(
modifier = Modifier
.weight(1f)
.fillMaxHeight(),
verticalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = title,
maxLines = if (desc == null) 2 else 1,
style = MaterialTheme.typography.titleLarge.copy(fontSize = 20.sp),
color = MaterialTheme.colorScheme.onSurface alwaysLight true,
overflow = TextOverflow.Ellipsis,
)
desc?.let {
Text(
text = it,
style = MaterialTheme.typography.bodySmall,
color = (MaterialTheme.colorScheme.onSurface alwaysLight true).copy(alpha = 0.7f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
action?.let {
Box(Modifier.padding(start = 16.dp)) {
CompositionLocalProvider(
LocalContentColor provides (MaterialTheme.colorScheme.onSurface alwaysLight true)
) { it() }
}
}
}
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/Banner.kt | 280410704 |
package app.xlei.vipexam.core.ui
import android.content.ClipData
import android.view.View
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.draganddrop.dragAndDropSource
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
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.draganddrop.DragAndDropTransferData
import androidx.compose.ui.platform.LocalTextToolbar
import androidx.compose.ui.platform.LocalView
import app.xlei.vipexam.preference.LocalLongPressAction
import app.xlei.vipexam.preference.LongPressAction
/**
* Vipexam article container
*
* @param onArticleLongClick 内容点击事件
* @param onDragContent 可以拖动的内容
* @param content 内容
* @receiver
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun VipexamArticleContainer(
onClick: (() -> Unit)? = {},
onArticleLongClick: (() -> Unit)? = {},
onDragContent: String? = null,
content: @Composable () -> Unit
){
var showTranslateDialog by rememberSaveable { mutableStateOf(false) }
val longPressAction = LocalLongPressAction.current
when (longPressAction) {
LongPressAction.ShowTranslation ->
CompositionLocalProvider(
value = LocalTextToolbar provides VipexamTextToolbar(
view = LocalView.current
) {
showTranslateDialog = true
}
) {
SelectionContainer(
modifier = Modifier.clickable {
onClick?.invoke()
}
) {
content()
}
}
LongPressAction.ShowQuestion ->
Column(
modifier = Modifier
.combinedClickable(
onClick = { onClick?.invoke() },
onLongClick = onArticleLongClick
)
) {
content()
}
LongPressAction.None -> Column(
modifier = Modifier
.dragAndDropSource {
detectTapGestures(
onPress = { onClick?.invoke() },
onLongPress = {
startTransfer(
DragAndDropTransferData(
clipData = ClipData.newPlainText("", onDragContent),
flags = View.DRAG_FLAG_GLOBAL,
)
)
},
)
}
){
content()
}
}
if (longPressAction.isShowTranslation() && showTranslateDialog)
TranslateDialog(
onDismissRequest = {
showTranslateDialog = false
}
) {
AddToWordListButton(onClick = {
showTranslateDialog = false
})
}
}
| vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/VipexamArticleContainer.kt | 1750085964 |
package app.xlei.vipexam.core.ui.vm
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 dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class AddToWordListButtonViewModel @Inject constructor(
private val wordRepository: Repository<Word>
) : ViewModel() {
fun addToWordList(word: String) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
wordRepository.add(
Word(
word = word
)
)
}
}
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/vm/AddToWordListButtonViewModel.kt | 3669884021 |
package app.xlei.vipexam.core.ui
import android.content.ClipboardManager
import android.content.Context
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.ui.vm.AddToWordListButtonViewModel
/**
* Add to word list button
*
* @param onClick 点击行为
* @param viewModel 添加到单词表vm
* @receiver
*/
@Composable
fun AddToWordListButton(
onClick: (() -> Unit) = {},
viewModel: AddToWordListButtonViewModel = hiltViewModel()
){
val context = LocalContext.current
val clipBoardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
TextButton(
onClick = {
viewModel.addToWordList(
clipBoardManager.primaryClip?.getItemAt(0)?.text?.toString()!!
)
onClick.invoke()
}
) {
Text(stringResource(id = R.string.add_to_word_list))
}
}
| vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/AddToWordListButton.kt | 2472867175 |
package app.xlei.vipexam.core.ui
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.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
@Composable
fun OnError(
textId: Int = R.string.internet_error,
error: String? = null,
){
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = textId),
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
error?.let {
Text(
text = it,
color = MaterialTheme.colorScheme.secondary,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.labelSmall
)
}
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/OnError.kt | 210277787 |
package app.xlei.vipexam.core.ui
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun LoadingNextPageItem(modifier: Modifier) {
CircularProgressIndicator(
modifier = modifier
.fillMaxWidth()
.padding(10.dp)
.wrapContentWidth(Alignment.CenterHorizontally)
)
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/LoadingNextPageItem.kt | 600524274 |
package app.xlei.vipexam.core.ui
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
@Composable
fun LoginAlert(
onDismissRequest: () -> Unit,
){
AlertDialog(
onDismissRequest = onDismissRequest,
confirmButton = { TextButton(onClick = { onDismissRequest.invoke() }) {
Text(text = stringResource(id = R.string.ok))
} },
title = {
Text(text = stringResource(id = R.string.login_to_continue))
}
)
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/LoginAlert.kt | 90776413 |
package app.xlei.vipexam.core.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.Stable
import androidx.compose.ui.graphics.Color
import app.xlei.vipexam.preference.LocalThemeMode
@Stable
@Composable
@ReadOnlyComposable
infix fun Color.alwaysLight(isAlways: Boolean): Color {
val colorScheme = MaterialTheme.colorScheme
return if (isAlways && LocalThemeMode.current.isDarkTheme()) {
when (this) {
colorScheme.primary -> colorScheme.onPrimary
colorScheme.secondary -> colorScheme.onSecondary
colorScheme.tertiary -> colorScheme.onTertiary
colorScheme.background -> colorScheme.onBackground
colorScheme.error -> colorScheme.onError
colorScheme.surface -> colorScheme.onSurface
colorScheme.surfaceVariant -> colorScheme.onSurfaceVariant
colorScheme.primaryContainer -> colorScheme.onPrimaryContainer
colorScheme.secondaryContainer -> colorScheme.onSecondaryContainer
colorScheme.tertiaryContainer -> colorScheme.onTertiaryContainer
colorScheme.errorContainer -> colorScheme.onErrorContainer
colorScheme.inverseSurface -> colorScheme.inverseOnSurface
colorScheme.onPrimary -> colorScheme.primary
colorScheme.onSecondary -> colorScheme.secondary
colorScheme.onTertiary -> colorScheme.tertiary
colorScheme.onBackground -> colorScheme.background
colorScheme.onError -> colorScheme.error
colorScheme.onSurface -> colorScheme.surface
colorScheme.onSurfaceVariant -> colorScheme.surfaceVariant
colorScheme.onPrimaryContainer -> colorScheme.primaryContainer
colorScheme.onSecondaryContainer -> colorScheme.secondaryContainer
colorScheme.onTertiaryContainer -> colorScheme.tertiaryContainer
colorScheme.onErrorContainer -> colorScheme.errorContainer
colorScheme.inverseOnSurface -> colorScheme.inverseSurface
else -> Color.Unspecified
}
} else {
this
}
}
@Stable
@Composable
@ReadOnlyComposable
infix fun Color.alwaysDark(isAlways: Boolean): Color {
val colorScheme = MaterialTheme.colorScheme
return if (isAlways && !LocalThemeMode.current.isDarkTheme()) {
when (this) {
colorScheme.primary -> colorScheme.onPrimary
colorScheme.secondary -> colorScheme.onSecondary
colorScheme.tertiary -> colorScheme.onTertiary
colorScheme.background -> colorScheme.onBackground
colorScheme.error -> colorScheme.onError
colorScheme.surface -> colorScheme.onSurface
colorScheme.surfaceVariant -> colorScheme.onSurfaceVariant
colorScheme.primaryContainer -> colorScheme.onPrimaryContainer
colorScheme.secondaryContainer -> colorScheme.onSecondaryContainer
colorScheme.tertiaryContainer -> colorScheme.onTertiaryContainer
colorScheme.errorContainer -> colorScheme.onErrorContainer
colorScheme.inverseSurface -> colorScheme.inverseOnSurface
colorScheme.onPrimary -> colorScheme.primary
colorScheme.onSecondary -> colorScheme.secondary
colorScheme.onTertiary -> colorScheme.tertiary
colorScheme.onBackground -> colorScheme.background
colorScheme.onError -> colorScheme.error
colorScheme.onSurface -> colorScheme.surface
colorScheme.onSurfaceVariant -> colorScheme.surfaceVariant
colorScheme.onPrimaryContainer -> colorScheme.primaryContainer
colorScheme.onSecondaryContainer -> colorScheme.secondaryContainer
colorScheme.onTertiaryContainer -> colorScheme.tertiaryContainer
colorScheme.onErrorContainer -> colorScheme.errorContainer
colorScheme.inverseOnSurface -> colorScheme.inverseSurface
else -> Color.Unspecified
}
} else {
this
}
}
fun String.checkColorHex(): String? {
var s = this.trim()
if (s.length > 6) {
s = s.substring(s.length - 6)
}
return "[0-9a-fA-F]{6}".toRegex().find(s)?.value
}
@Stable
fun String.safeHexToColor(): Color =
try {
Color(java.lang.Long.parseLong(this, 16))
} catch (e: Exception) {
Color.Transparent
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/palette.kt | 2748357709 |
package app.xlei.vipexam.core.ui
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.widget.Toast
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.xlei.vipexam.core.network.module.TranslationResponse
import compose.icons.FeatherIcons
import compose.icons.feathericons.Loader
import kotlinx.coroutines.launch
@Composable
fun TranslateDialog(
onDismissRequest: () -> Unit,
dismissButton: @Composable () -> Unit = {
TextButton(onClick = onDismissRequest) {
Text(text = stringResource(R.string.cancel))
}
},
confirmButton: @Composable () -> Unit = {
TextButton(onClick = onDismissRequest) {
Text(text = stringResource(id = R.string.ok))
}
},
) {
val coroutine = rememberCoroutineScope()
val context = LocalContext.current
val clipboardManager = context.getSystemService(
Context.CLIPBOARD_SERVICE
) as ClipboardManager
val localConfiguration = LocalConfiguration.current
AlertDialog(
onDismissRequest = onDismissRequest,
title = {
clipboardManager.primaryClip?.getItemAt(0)?.text?.toString()?.let {
LazyColumn (
modifier = Modifier
.heightIn(max = (localConfiguration.screenHeightDp/2).dp)
){
item {
Text(
text = it
)
}
}
}
},
text = {
var translation by remember {
mutableStateOf(
TranslationResponse(
code = 200,
id = "",
data = "",
emptyList()
)
)
}
DisposableEffect(Unit) {
coroutine.launch {
val res = app.xlei.vipexam.core.network.module.NetWorkRepository.translateToZH(
text = clipboardManager.primaryClip?.getItemAt(0)?.text?.toString()!!
)
res.onSuccess {
translation = it
}.onFailure {
onDismissRequest.invoke()
Toast.makeText(context, it.toString(), Toast.LENGTH_SHORT).show()
}
}
onDispose {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
clipboardManager.clearPrimaryClip()
} else {
clipboardManager.setPrimaryClip(
ClipData.newPlainText("", "")
)
}
}
}
LazyColumn {
item {
Text(
text = translation.data,
fontSize = if (translation.alternatives.isNotEmpty()) 24.sp else TextUnit.Unspecified,
)
}
item {
LazyRow {
when {
translation.alternatives.isEmpty() && translation.data == "" -> {
item {
Icon(
imageVector = FeatherIcons.Loader,
contentDescription = null,
)
}
}
else -> {
items(translation.alternatives.size) {
Text(
text = translation.alternatives[it],
modifier = Modifier.padding(end = 12.dp)
)
}
}
}
}
}
}
},
dismissButton = dismissButton,
confirmButton = confirmButton
)
}
| vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/TranslationDialog.kt | 2319367502 |
package app.xlei.vipexam.core.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
@Composable
fun DateText(time: Long?=null){
time?.let {
Text(
text = getFormattedDate(it),
style = MaterialTheme.typography.bodySmall
)
}
}
@Composable
fun getFormattedDate(time: Long): String {
val dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault())
val now = LocalDateTime.now()
val today = LocalDate.now()
val date = dateTime.toLocalDate()
val duration = Duration.between(dateTime, now)
return when {
duration.toMinutes() < 1 -> stringResource(id = R.string.just_now)
duration.toHours() < 1 -> "${duration.toMinutes()}" + stringResource(id = R.string.minute_before)
duration.toDays() < 1 -> "${duration.toHours()}" + stringResource(id = R.string.hour_before)
date.year == today.year -> dateTime.format(DateTimeFormatter.ofPattern("MM-dd"))
else -> dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
}
} | vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/DateText.kt | 1712580068 |
package app.xlei.vipexam.core.database
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.database.test", appContext.packageName)
}
} | vipexam/core/database/src/androidTest/java/app/xlei/vipexam/core/database/ExampleInstrumentedTest.kt | 3542410033 |
package app.xlei.vipexam.core.database
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/database/src/test/java/app/xlei/vipexam/core/database/ExampleUnitTest.kt | 2337610697 |
package app.xlei.vipexam.core.database.di
import app.xlei.vipexam.core.database.VipexamDatabase
import app.xlei.vipexam.core.database.dao.BookmarkDao
import app.xlei.vipexam.core.database.dao.ExamHistoryDao
import app.xlei.vipexam.core.database.dao.UserDao
import app.xlei.vipexam.core.database.dao.WordDao
import app.xlei.vipexam.core.database.module.ExamHistory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object DaosModule {
@Provides
fun providesWordDao(
database: VipexamDatabase
): WordDao = database.wordDao()
@Provides
fun providesUserDao(
database: VipexamDatabase
): UserDao = database.userDao()
@Provides
fun providesExamHistory(
database: VipexamDatabase
): ExamHistoryDao = database.examHistoryDao()
@Provides
fun providesBookmark(
database: VipexamDatabase
): BookmarkDao = database.bookmarkDao()
} | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/di/DaosModule.kt | 469967449 |
package app.xlei.vipexam.core.database.di
import android.content.Context
import androidx.room.Room
import app.xlei.vipexam.core.database.VipexamDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun providesVipexamDatabase(
@ApplicationContext context: Context
): VipexamDatabase = Room.databaseBuilder(
context,
VipexamDatabase::class.java,
"vipexam-database"
).build()
@Singleton
@Provides
fun providesCoroutineScope(): CoroutineScope {
return CoroutineScope(SupervisorJob() + Dispatchers.IO)
}
} | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/di/DatabaseModule.kt | 1166161274 |
package app.xlei.vipexam.core.database.module
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Calendar
@Entity(tableName = "bookmarks")
data class Bookmark(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val examName: String,
val examId: String,
val question: String,
val created: Long = Calendar.getInstance().timeInMillis,
) | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/Bookmark.kt | 3465202507 |
package app.xlei.vipexam.core.database.module
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import java.util.Calendar
@Entity(
tableName = "words",
indices = [Index(value = ["word"], unique = true)]
)
data class Word(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@ColumnInfo(name = "word") val word: String,
val created: Long = Calendar.getInstance().timeInMillis,
) | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/WordEntity.kt | 127143791 |
package app.xlei.vipexam.core.database.module
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import java.util.Calendar
@Entity(
tableName = "exam_history",
indices = [Index(value = ["examId"], unique = true)]
)
data class ExamHistory (
@PrimaryKey(autoGenerate = true)
val examHistoryId: Int = 0,
val examName: String,
@ColumnInfo(name = "examId") val examId: String,
val lastOpen: Long = Calendar.getInstance().timeInMillis,
) | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/ExamHistory.kt | 524733643 |
package app.xlei.vipexam.core.database.module
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "users")
data class User(
@PrimaryKey
val account: String,
val password: String,
)
| vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/UserEntity.kt | 2782821428 |
package app.xlei.vipexam.core.database.module
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Language(
@PrimaryKey(autoGenerate = false)
val code: String = "",
@ColumnInfo val name: String = ""
) {
override fun equals(other: Any?): Boolean {
(other as? Language)?.let { otherLang ->
return otherLang.name.lowercase() == this.name.lowercase() ||
otherLang.code.lowercase() == this.code.lowercase()
}
return super.equals(other)
}
override fun hashCode() = 31 * code.hashCode() + name.hashCode()
}
| vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/LanguageEntity.kt | 1596476166 |
package app.xlei.vipexam.core.database.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import app.xlei.vipexam.core.database.module.User
import kotlinx.coroutines.flow.Flow
@Dao
interface UserDao{
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: User)
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun update(user: User)
@Delete
suspend fun delete(user: User)
@Query("SELECT * FROM users")
fun getAllUsers(): Flow<List<User>>
@Query("SELECT * FROM users WHERE account=:account")
fun getUser(account: String): User
} | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/UserDao.kt | 4107336487 |
package app.xlei.vipexam.core.database.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import app.xlei.vipexam.core.database.module.ExamHistory
import kotlinx.coroutines.flow.Flow
@Dao
interface ExamHistoryDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(historyEntity: ExamHistory)
@Query("SELECT * FROM exam_history ORDER BY lastOpen DESC")
fun getAllExamHistory(): Flow<List<ExamHistory>>
@Query("SELECT * FROM exam_history WHERE examId=:examId LIMIT 1")
fun getExamHistoryByExamId(examId: String): ExamHistory?
@Query("SELECT * FROM exam_history ORDER BY lastOpen DESC LIMIT 1")
fun getLastOpened(): Flow<ExamHistory?>
@Delete
suspend fun deleteHistory(historyEntity: ExamHistory)
@Query("DELETE FROM exam_history WHERE examId=:examId")
suspend fun deleteHistoryByExamId(examId: String)
@Query("DELETE FROM exam_history WHERE examHistoryId IN (SELECT examHistoryId FROM exam_history)")
suspend fun removeAllHistory()
} | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/ExamHistoryDao.kt | 3970294260 |
package app.xlei.vipexam.core.database.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import app.xlei.vipexam.core.database.module.Bookmark
import kotlinx.coroutines.flow.Flow
@Dao
interface BookmarkDao {
@Query("SELECT * FROM bookmarks")
fun getAllBookMarks(): Flow<List<Bookmark>>
@Insert
suspend fun insertBookmark(bookmark: Bookmark)
@Delete
suspend fun deleteBookmark(bookmark: Bookmark)
} | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/BookmarkDao.kt | 533354100 |
package app.xlei.vipexam.core.database.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import app.xlei.vipexam.core.database.module.Word
import kotlinx.coroutines.flow.Flow
@Dao
interface WordDao {
@Query("SELECT * FROM words")
fun getAllWords(): Flow<List<Word>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(word: Word)
@Delete
suspend fun delete(word: Word)
} | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/WordDao.kt | 259182272 |
package app.xlei.vipexam.core.database
import androidx.room.Database
import androidx.room.RoomDatabase
import app.xlei.vipexam.core.database.dao.BookmarkDao
import app.xlei.vipexam.core.database.dao.ExamHistoryDao
import app.xlei.vipexam.core.database.dao.UserDao
import app.xlei.vipexam.core.database.dao.WordDao
import app.xlei.vipexam.core.database.module.Bookmark
import app.xlei.vipexam.core.database.module.ExamHistory
import app.xlei.vipexam.core.database.module.User
import app.xlei.vipexam.core.database.module.Word
@Database(
entities = [
Word::class,
User::class,
ExamHistory::class,
Bookmark::class,
],
version = 1
)
abstract class VipexamDatabase : RoomDatabase() {
abstract fun wordDao(): WordDao
abstract fun userDao(): UserDao
abstract fun examHistoryDao(): ExamHistoryDao
abstract fun bookmarkDao(): BookmarkDao
} | vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/VipexamDatabase.kt | 3987373601 |
package app.xlei.vipexam.core.network
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.network.test", appContext.packageName)
}
} | vipexam/core/network/src/androidTest/java/app/xlei/vipexam/core/network/ExampleInstrumentedTest.kt | 93560170 |
package app.xlei.vipexam.core.network
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/network/src/test/java/app/xlei/vipexam/core/network/ExampleUnitTest.kt | 4250647699 |
package app.xlei.vipexam.core.network.module.addQCollect
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class AddQCollectResponse(
@SerialName("code")
val code: String,
@SerialName("msg")
val msg: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/addQCollect/AddQCollectResponse.kt | 3069709865 |
package app.xlei.vipexam.core.network.module
import android.os.Environment
import app.xlei.vipexam.core.network.module.TiJiaoTest.TiJiaoTestPayload
import app.xlei.vipexam.core.network.module.TiJiaoTest.TiJiaoTestResponse
import app.xlei.vipexam.core.network.module.addQCollect.AddQCollectResponse
import app.xlei.vipexam.core.network.module.deleteQCollect.DeleteQCollectResponse
import app.xlei.vipexam.core.network.module.getExamList.GetExamListResponse
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.network.module.login.LoginResponse
import app.xlei.vipexam.core.network.module.momoLookUp.MomoLookUpResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.headers
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsChannel
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HeadersBuilder
import io.ktor.http.HttpHeaders
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.util.cio.writeChannel
import io.ktor.utils.io.copyAndClose
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.File
object NetWorkRepository {
private lateinit var account: String
private lateinit var password: String
private lateinit var token: String
private lateinit var organization: String
private val httpClient by lazy {
_httpClient.value
}
private val _httpClient = lazy {
HttpClient(CIO) {
engine {
requestTimeout = 0
}
install(ContentNegotiation) {
json()
}
}
}
fun isAvailable() = this::account.isInitialized && this::token.isInitialized
private fun HttpRequestBuilder.vipExamHeaders(
referrer: String
): HeadersBuilder {
return headers {
append(HttpHeaders.Accept,"application/json, text/javascript, */*; q=0.01")
append(HttpHeaders.AcceptLanguage,"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
append(HttpHeaders.Connection,"keep-alive")
append(HttpHeaders.ContentType,"application/x-www-form-urlencoded; charset=UTF-8")
append(HttpHeaders.Origin,"https://vipexam.cn")
append("Sec-Fetch-Dest", "empty")
append("Sec-Fetch-Mode", "cors")
append("Sec-Fetch-Site", "same-origin")
append(HttpHeaders.UserAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0")
append("X-Requested-With", "XMLHttpRequest")
append(
"sec-ch-ua",
"\"Microsoft Edge\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\""
)
append("sec-ch-ua-mobile", "?0")
append("sec-ch-ua-platform", "\"macOS\"")
append(HttpHeaders.Referrer,referrer)
}
}
suspend fun getToken(
account: String,
password: String,
organization: String,
): Result<LoginResponse> {
this.account = account
this.password = password
this.organization = organization
return try {
httpClient.post("https://vipexam.cn/user/login.action") {
vipExamHeaders(referrer = "https://vipexam.cn/login2.html")
setBody("account=$account&password=$password")
}.body<LoginResponse>().also {
if (it.code == "1") this.token = it.token
}.run {
when (code) {
"1" -> Result.success(this)
else -> Result.failure(error(msg))
}
}.also {
println(organization)
}
} catch (e: Exception) {
Result.failure(e)
}
}
suspend fun getExam(examId: String): Result<GetExamResponse> {
return try {
Result.success(
httpClient.post("https://vipexam.cn/exam/getExamList.action") {
vipExamHeaders(referrer = "https://vipexam.cn/begin_testing2.html?id=$examId")
setBody("examID=$examId&account=$account&token=$token")
}.body()
)
}catch (e: Exception){
println(e)
Result.failure(e)
}
}
fun getQuestions(mubanList: List<Muban>): List<Pair<String, String>> {
val questions = mutableListOf<Pair<String, String>>()
for (muban in mubanList) {
questions.add(muban.ename to muban.cname)
}
return questions
}
suspend fun getExamList(
page: String,
examStyle: Int,
examTypeEName: String,
): Result<GetExamListResponse> {
return try {
Result.success(
httpClient.post("https://vipexam.cn/web/moreCourses") {
vipExamHeaders(referrer = "https://vipexam.cn/resources_kinds.html?id=$examTypeEName")
setBody("data={\"account\":\"$account\",\"token\":\"$token\",\"typeCode\":\"$examTypeEName\",\"resourceType\":\"${examStyle}\",\"courriculumType\":\"0\",\"classHourS\":\"0\",\"classHourE\":\"0\",\"yearPublishedS\":\"0\",\"yearPublishedE\":\"0\",\"page\":$page,\"limit\":20,\"collegeName\":\"$organization\"}")
}.body<GetExamListResponse>().also { println(it) }
)
} catch (e: Exception){
Result.failure(e)
}
}
suspend fun searchExam(
page: String,
searchContent: String
): Result<GetExamListResponse> {
return try {
Result.success(
httpClient.post("https://vipexam.cn/examseek/speedinessSearch"){
vipExamHeaders(referrer = "exam_paper.html?field=1&exam_paper.html?field=1&keys=$searchContent")
setBody("""
account=$account&token=$token&data={"page":$page,"limit":20,"fields":"1","keyword":"$searchContent","matching":"like"}
""".trimIndent())
}.body()
)
} catch (e: Exception){
Result.failure(e)
}
}
suspend fun translateToZH(text: String): Result<TranslationResponse> {
return try {
Result.success(
httpClient.post("https://api.deeplx.org/translate") {
header("Accept", "application/json, text/javascript, */*; q=0.01")
contentType(ContentType.Application.Json)
setBody(
mapOf(
"text" to text,
"source_lang" to "EN",
"target_lang" to "ZH"
)
)
}.body()
)
} catch (e: Exception) {
return Result.failure(e)
}
}
suspend fun download(
fileName: String,
examId: String,
){
val client = HttpClient(CIO)
try {
val res = client.get("""
https://vipexam.cn/web/getExamWordByStu?examID=$examId&account=$account&token=$token
""".trimIndent()){
headers {
append("Host", "vipexam.cn")
append("Connection", "keep-alive")
append("sec-ch-ua", "\"Not A(Brand\";v=\"99\", \"Microsoft Edge\";v=\"121\", \"Chromium\";v=\"121\"")
append("sec-ch-ua-mobile", "?0")
append("sec-ch-ua-platform", "\"macOS\"")
append("Upgrade-Insecure-Requests", "1")
append("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0")
append("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
append("Sec-Fetch-Site", "none")
append("Sec-Fetch-Mode", "navigate")
append("Sec-Fetch-User", "?1")
append("Sec-Fetch-Dest", "document")
append("Accept-Encoding", "gzip, deflate, br")
append("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
}
}.bodyAsChannel().also {
val downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val file = File(downloadsPath, "$fileName.doc")
if (!downloadsPath.exists()) {
downloadsPath.mkdirs()
}
it.copyAndClose(file.writeChannel())
}
println(res)
} catch (e: Exception) {
println(e)
}
}
suspend fun addQCollect(
examId: String,
questionCode: String
): Result<AddQCollectResponse> {
return try {
Result.success(
httpClient.post("https://vipexam.cn/questioncollect/addQCollect.action") {
vipExamHeaders("https://vipexam.cn/begin_testing2.html?id=$examId")
setBody(
"""
account=$account&token=$token&ExamID=$examId&QuestionCode=$questionCode
""".trimIndent()
)
}.body()
)
} catch (e: Exception) {
Result.failure(e)
}
}
suspend fun deleteQCollect(
examId: String,
questionCode: String
): Result<DeleteQCollectResponse> {
return try {
Result.success(
httpClient.post("https://vipexam.cn/questioncollect/deleteQCollect.action") {
vipExamHeaders("https://vipexam.cn/begin_testing2.html?id=$examId")
setBody(
"""
account=$account&token=$token&ExamID=$examId&QuestionCode=$questionCode
""".trimIndent()
)
}.body()
)
} catch (e: Exception) {
Result.failure(e)
}
}
suspend fun tiJiaoTest(payload: TiJiaoTestPayload): Result<TiJiaoTestResponse> {
return try {
println(Json.encodeToString(payload))
Result.success(
httpClient.post("https://vipexam.cn/exam/TiJiaoTest") {
vipExamHeaders("https://vipexam.cn/begin_testing.html?id=${payload.examID}")
setBody(
"data=" + Json.encodeToString(
payload.copy(
account = account,
token = token,
)
)
)
}.run {
println(this.bodyAsText())
this.body<TiJiaoTestResponse>()
}
)
} catch (e: Exception) {
println(e)
Result.failure(e)
}
}
suspend fun momoLookUp(
offset: Int,
keyword: String,
paperType: String = "CET6"
): Result<MomoLookUpResponse> {
return try {
Result.success(
httpClient.get("https://lookup.maimemo.com/api/v1/search?offset=$offset&limit=10&keyword=$keyword&paper_type=$paperType")
.body<MomoLookUpResponse>()
)
} catch (e: Exception) {
Result.failure(e)
}
}
}
| vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/NetWorkRepository.kt | 3875475075 |
package app.xlei.vipexam.core.network.module.eudic
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Data(
@SerialName("id")
val id: String,
@SerialName("language")
val language: String,
@SerialName("name")
val name: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/Data.kt | 3626294431 |
package app.xlei.vipexam.core.network.module.eudic
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class AddNewCategoryResponse(
@SerialName("data")
val `data`: Data,
@SerialName("message")
val message: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/AddNewCategoryResponse.kt | 457777723 |
package app.xlei.vipexam.core.network.module.eudic
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GetAllCategoryResponse(
@SerialName("data")
val `data`: List<Data>,
@SerialName("message")
val message: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/GetAllCategoryResponse.kt | 2070468948 |
package app.xlei.vipexam.core.network.module.eudic
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class AddWordsResponse(
@SerialName("message")
val message: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/AddWordsResponse.kt | 1805897571 |
package app.xlei.vipexam.core.network.module.getExamList
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Exam(
@SerialName("collectDate")
val collectDate: String? = null,
@SerialName("examTypeEName")
val examTypeEName: String = "",
@SerialName("examdate")
val examdate: String = "",
@SerialName("examid")
val examid: String = "",
@SerialName("examname")
val examname: String = "",
@SerialName("examstyle")
val examstyle: String = "",
@SerialName("examtyleStr")
val examtyleStr: String = "",
@SerialName("examtypeII")
val examtypeII: String? = null,
@SerialName("examtypecode")
val examtypecode: String = "",
@SerialName("fullName")
val fullName: String = "",
@SerialName("temlExamtimeLimit")
val temlExamtimeLimit: Int = 0,
@SerialName("templatecode")
val templatecode: String = "",
@SerialName("tid")
val tid: Int = 0,
@SerialName("tmplExamScore")
val tmplExamScore: Int = 0
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamList/Exam.kt | 3672553677 |
package app.xlei.vipexam.core.network.module.getExamList
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GetExamListResponse(
@SerialName("code")
val code: String = "",
@SerialName("count")
val count: Int = 0,
@SerialName("list")
val list: List<Exam> = listOf(),
@SerialName("msg")
val msg: String = "",
@SerialName("resourceType")
val resourceType: Int = 0
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamList/GetExamListResponse.kt | 3164184904 |
package app.xlei.vipexam.core.network.module.getExamResponse
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Shiti(
@SerialName("answerPic")
val answerPic: String = "",
@SerialName("audioFiles")
val audioFiles: String = "",
@SerialName("children")
val children: List<Children> = listOf(),
@SerialName("discPic")
val discPic: String = "",
@SerialName("discription")
val discription: String = "",
@SerialName("fifth")
val fifth: String = "",
@SerialName("fifthPic")
val fifthPic: String = "",
@SerialName("first")
val first: String = "",
@SerialName("firstPic")
val firstPic: String = "",
@SerialName("fourth")
val fourth: String = "",
@SerialName("fourthPic")
val fourthPic: String = "",
@SerialName("groupCodePrimQuestion")
val groupCodePrimQuestion: String = "",
@SerialName("isCollect")
val isCollect: String = "",
@SerialName("originalText")
val originalText: String = "",
@SerialName("primPic")
val primPic: String = "",
@SerialName("primQuestion")
val primQuestion: String = "",
@SerialName("questionCode")
val questionCode: String = "",
@SerialName("refAnswer")
val refAnswer: String = "",
@SerialName("second")
val second: String = "",
@SerialName("secondPic")
val secondPic: String = "",
@SerialName("secondQuestion")
val secondQuestion: String? = null,
@SerialName("subPrimPic")
val subPrimPic: String = "",
@SerialName("subjectTypeEname")
val subjectTypeEname: String = "",
@SerialName("third")
val third: String = "",
@SerialName("thirdPic")
val thirdPic: String = ""
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/Shiti.kt | 539922747 |
package app.xlei.vipexam.core.network.module.getExamResponse
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Children(
@SerialName("answerPic")
val answerPic: String = "",
@SerialName("audioFiles")
val audioFiles: String = "",
@SerialName("discPic")
val discPic: String = "",
@SerialName("discription")
val discription: String = "",
@SerialName("fifth")
val fifth: String = "",
@SerialName("fifthPic")
val fifthPic: String = "",
@SerialName("first")
val first: String = "",
@SerialName("firstPic")
val firstPic: String = "",
@SerialName("fourth")
val fourth: String = "",
@SerialName("fourthPic")
val fourthPic: String = "",
@SerialName("isCollect")
val isCollect: String = "",
@SerialName("originalText")
val originalText: String = "",
@SerialName("primPic")
val primPic: String = "",
@SerialName("primQuestion")
val primQuestion: String = "",
@SerialName("questionCode")
val questionCode: String = "",
@SerialName("refAnswer")
val refAnswer: String = "",
@SerialName("second")
val second: String = "",
@SerialName("secondPic")
val secondPic: String = "",
@SerialName("secondQuestion")
val secondQuestion: String = "",
@SerialName("subPrimPic")
val subPrimPic: String = "",
@SerialName("subjectTypeEname")
val subjectTypeEname: String = "",
@SerialName("third")
val third: String = "",
@SerialName("thirdPic")
val thirdPic: String = ""
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/Children.kt | 3138195974 |
package app.xlei.vipexam.core.network.module.getExamResponse
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Muban(
@SerialName("basic")
val basic: String = "",
@SerialName("cname")
val cname: String = "",
@SerialName("cunt")
val cunt: Int = 0,
@SerialName("ename")
val ename: String = "",
@SerialName("grade")
val grade: String = "",
@SerialName("shiti")
val shiti: List<Shiti> = listOf()
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/Muban.kt | 188128934 |
package app.xlei.vipexam.core.network.module.getExamResponse
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GetExamResponse(
@SerialName("code")
val code: Int = 0,
@SerialName("count")
val count: Int = 0,
@SerialName("examID")
val examID: String = "",
@SerialName("examName")
val examName: String = "",
@SerialName("examTypeCode")
val examTypeCode: String = "",
@SerialName("examstyle")
val examstyle: String = "",
@SerialName("msg")
val msg: String = "",
@SerialName("muban")
val muban: List<Muban> = listOf(),
@SerialName("planID")
val planID: String = "",
@SerialName("timelimit")
val timelimit: Int = 0
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/GetExamResponse.kt | 4288815216 |
package app.xlei.vipexam.core.network.module
import kotlinx.serialization.Serializable
@Serializable
data class TranslationResponse(
val code: Int,
val id: String,
val data: String,
val alternatives: List<String>,
)
| vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TranslationResponse.kt | 1280449400 |
package app.xlei.vipexam.core.network.module.momoLookUp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Total(
@SerialName("relation")
val relation: String,
@SerialName("value")
val value: Int
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Total.kt | 1743361055 |
package app.xlei.vipexam.core.network.module.momoLookUp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Context(
@SerialName("answers")
val answers: List<String>,
@SerialName("options")
val options: List<Option>,
@SerialName("phrase")
val phrase: String,
@SerialName("translation")
val translation: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Context.kt | 1452598656 |
package app.xlei.vipexam.core.network.module.momoLookUp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Data(
@SerialName("phrases")
val phrases: List<Phrase>,
@SerialName("time_cost")
val timeCost: Int,
@SerialName("total")
val total: Total
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Data.kt | 3607752772 |
package app.xlei.vipexam.core.network.module.momoLookUp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Highlight(
@SerialName("context")
val context: Context
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Highlight.kt | 4126577149 |
package app.xlei.vipexam.core.network.module.momoLookUp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class MomoLookUpResponse(
@SerialName("data")
val `data`: Data,
@SerialName("errors")
val errors: List<String>,
@SerialName("success")
val success: Boolean
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/MomoLookUpResponse.kt | 410383793 |
package app.xlei.vipexam.core.network.module.momoLookUp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Option(
@SerialName("option")
val option: String,
@SerialName("phrase")
val phrase: String,
@SerialName("translation")
val translation: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Option.kt | 993485946 |
package app.xlei.vipexam.core.network.module.momoLookUp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Phrase(
@SerialName("context")
val context: Context,
@SerialName("highlight")
val highlight: Highlight,
@SerialName("paper_id")
val paperId: String,
@SerialName("path")
val path: String,
@SerialName("phrase_en")
val phraseEn: String,
@SerialName("phrase_id")
val phraseId: String,
@SerialName("phrase_zh")
val phraseZh: String,
@SerialName("source")
val source: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Phrase.kt | 3672884726 |
package app.xlei.vipexam.core.network.module.TiJiaoTest
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class TiJiaoTestPayload(
@SerialName("account")
val account: String? = null,
@SerialName("count")
val count: String,
@SerialName("examID")
val examID: String,
@SerialName("examName")
val examName: String,
@SerialName("examStyle")
val examStyle: String,
@SerialName("examTypeCode")
val examTypeCode: String,
@SerialName("TestQuestion")
val testQuestion: List<TestQuestion>,
@SerialName("token")
val token: String? = null
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TiJiaoTest/TiJiaoTestPayload.kt | 534435237 |
package app.xlei.vipexam.core.network.module.TiJiaoTest
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class TiJiaoTestResponse(
@SerialName("code")
val code: Int,
@SerialName("grade")
val grade: Double,
@SerialName("gradedCount")
val gradedCount: String,
@SerialName("msg")
val msg: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TiJiaoTest/TiJiaoTestResponse.kt | 2533703278 |
package app.xlei.vipexam.core.network.module.TiJiaoTest
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class TestQuestion(
@SerialName("basic")
val basic: String,
@SerialName("grade")
val grade: String,
@SerialName("questionCode")
val questionCode: String,
@SerialName("questiontype")
val questiontype: String,
@SerialName("refAnswer")
val refAnswer: String
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TiJiaoTest/TestQuestion.kt | 1695533809 |
package app.xlei.vipexam.core.network.module
import app.xlei.vipexam.core.network.module.eudic.AddNewCategoryResponse
import app.xlei.vipexam.core.network.module.eudic.AddWordsResponse
import app.xlei.vipexam.core.network.module.eudic.GetAllCategoryResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.client.request.headers
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
object EudicRemoteDatasource {
lateinit var api: String
private val httpClient by lazy {
_httpClient.value
}
private val _httpClient = lazy {
HttpClient(CIO) {
engine {
requestTimeout = 0
}
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
})
}
}
}
private suspend fun getAllCategory(): Result<GetAllCategoryResponse> {
return try {
Result.success(
httpClient.get("https://api.frdic.com/api/open/v1/studylist/category?language=en") {
headers {
append("Authorization", api)
}
}.body<GetAllCategoryResponse>().also { println(it) }
)
} catch (e: Exception) {
println(e)
Result.failure(e)
}
}
private suspend fun uploadAllWords(words: List<String>, id: String): Result<AddWordsResponse> {
return try {
Result.success(
httpClient.post("https://api.frdic.com/api/open/v1/studylist/words") {
headers {
append("Authorization", api)
}
setBody(
AddNewWordsPayload(
id,
"en",
words
)
)
contentType(ContentType.Application.Json)
}.body<AddWordsResponse>().also { println(it) }
)
} catch (e: Exception) {
println(e)
Result.failure(e)
}
}
private suspend fun createNewCategory(): Result<String> {
return try {
Result.success(
httpClient.post("https://api.frdic.com/api/open/v1/studylist/category") {
headers {
append("Authorization", api)
}
setBody("{\n \"language\": \"en\",\n \"name\": \"vipexam\"\n}")
contentType(ContentType.Application.Json)
}.run {
bodyAsText().also { println(it) }
body<AddNewCategoryResponse>().data.id
}
)
} catch (e: Exception) {
println(e)
Result.failure(e)
}
}
suspend fun check() = getAllCategory()
suspend fun sync(words: List<String>): Boolean {
if (words.isEmpty()) {
return false
} else {
getAllCategory()
.onSuccess { resp ->
resp.data.firstOrNull { it.name == "vipexam" }
.let { data ->
if (data != null)
uploadAllWords(words, data.id)
.onSuccess { return true }
.onFailure { return false }
else {
createNewCategory()
.onSuccess {
uploadAllWords(words, it)
.onSuccess { return true }
.onFailure { return false }
}
.onFailure { return false }
}
}
}
.onFailure {
return false
}
return false
}
}
}
@Serializable
private data class AddNewWordsPayload(
val id: String,
val language: String,
val words: List<String>,
) | vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/EudicRemoteDatasource.kt | 3552708609 |
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/deleteQCollect/DeleteQCollectResponse.kt | 3309695410 |
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/Resource.kt | 1846246178 |
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/User.kt | 1772585537 |
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/network/src/main/java/app/xlei/vipexam/core/network/module/login/LoginResponse.kt | 4188861840 |
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/androidTest/java/app/xlei/vipexam/template/ExampleInstrumentedTest.kt | 2265665574 |
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/test/java/app/xlei/vipexam/template/ExampleUnitTest.kt | 3254058872 |
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/TemplateBuilder.kt | 2459416575 |
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/templateRender.kt | 3284307764 |
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/ClozeViewModel.kt | 2225165122 |
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/Cloze.kt | 1393167125 |
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/cloze/ClozeUiState.kt | 3882760047 |
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/ReadClozeViewModel.kt | 3287351753 |
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/ReadClozeUiState.kt | 1566778151 |
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/readCloze/ReadCloze.kt | 3571601354 |
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/TranslateUiState.kt | 2143270813 |
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/TranslateViewModel.kt | 1726237258 |
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/translate/Translate.kt | 170340326 |
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/ReadUiState.kt | 552372447 |
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/ReadViewModel.kt | 2637641769 |
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/read/Read.kt | 231930464 |
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/templateModule.kt | 168993466 |
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/writting.kt | 4155040248 |
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/WritingUiState.kt | 2344998108 |
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/template/src/main/java/app/xlei/vipexam/template/writing/WritingViewModel.kt | 3735754709 |
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/androidTest/java/app/xlei/vipexam/preference/ExampleInstrumentedTest.kt | 4008356912 |
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/test/java/app/xlei/vipexam/preference/ExampleUnitTest.kt | 2990892288 |
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/Language.kt | 266833837 |
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/Settings.kt | 1243090257 |
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/ShowAnswerOption.kt | 1109915769 |
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/DataStore.kt | 3653236433 |
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/ThemeModePreference.kt | 529446525 |
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/ShowAnswerPreference.kt | 3864665230 |
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/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 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/PinnedExams.kt | 2986556453 |
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/Preference.kt | 355330905 |
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/LongPressAction.kt | 3860202440 |
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/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 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/preference/src/main/java/app/xlei/vipexam/preference/Organization.kt | 1830560372 |
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/vipexam/core/data/ExampleInstrumentedTest.kt | 3958186011 |
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/androidTest/java/app/xlei/data/ExampleInstrumentedTest.kt | 4063835108 |
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/vipexam/core/data/ExampleUnitTest.kt | 2793821503 |
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/test/java/app/xlei/data/ExampleUnitTest.kt | 4086928371 |
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/WordRepository.kt | 180098271 |
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/ExamHistoryRepository.kt | 342383433 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.