path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
vipexam/app/src/main/java/app/xlei/vipexam/ui/question/writing/writting.kt | 1958878183 | package app.xlei.vipexam.ui.question.writing
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
import coil.compose.AsyncImage
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WritingView(
viewModel: WritingViewModel = hiltViewModel(),
muban: Muban,
){
val showAnswer = LocalShowAnswer.current.isShowAnswer()
viewModel.setMuban(muban)
viewModel.setWritings()
val uiState by viewModel.uiState.collectAsState()
writing(
writings = uiState.writings,
showAnswer = showAnswer
)
}
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
private fun writing(
writings: List<WritingUiState.Writing>,
showAnswer: Boolean,
) {
val scrollState = rememberLazyListState()
LazyColumn(
modifier = Modifier
.fillMaxWidth(),
state = scrollState
) {
items(writings.size) {
Column(
modifier = Modifier
.padding(top = 16.dp, start = 16.dp, end = 16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
) {
VipexamArticleContainer(
onDragContent = writings[it].question
+ "\n\n" + writings[it].refAnswer
+ "\n\n" + writings[it].description
) {
Text(
text = writings[it].question,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier
.padding(start = 4.dp, end = 4.dp)
)
}
if (shouldShowImage(writings[it].question)) {
Row {
Spacer(Modifier.weight(2f))
AsyncImage(
model = "https://rang.vipexam.org/images/${writings[it].image}.jpg",
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.padding(top = 24.dp)
.align(Alignment.CenterVertically)
.weight(6f)
.fillMaxWidth()
)
Spacer(Modifier.weight(2f))
}
}
}
if (showAnswer) {
Column {
Text(
text = writings[it].refAnswer,
modifier = Modifier
.padding(horizontal = 24.dp),
)
Text(
text = writings[it].description,
modifier = Modifier
.padding(horizontal = 24.dp),
)
}
}
}
}
}
private fun shouldShowImage(text: String): Boolean {
val pattern = Regex("""\[\*\]""")
return pattern.findAll(text).toList().isNotEmpty()
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/question/writing/WritingUiState.kt | 4238676531 | package app.xlei.vipexam.ui.question.writing
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class WritingUiState(
val muban: Muban?=null,
val writings: List<Writing>
){
data class Writing(
val question: String,
val refAnswer: String,
val image: String,
val description: String,
)
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/question/writing/WritingViewModel.kt | 948191637 | package app.xlei.vipexam.ui.question.writing
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class WritingViewModel @Inject constructor(
writingUiState: WritingUiState
) : ViewModel() {
private val _uiState = MutableStateFlow(writingUiState)
val uiState: StateFlow<WritingUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban // function scope
)
}
}
fun setWritings(){
val writings = mutableListOf<WritingUiState.Writing>()
_uiState.value.muban!!.shiti.forEach {
writings.add(
WritingUiState.Writing(
question = it.primQuestion,
refAnswer = it.refAnswer,
image = it.primPic,
description = it.discription
)
)
}
_uiState.update {
it.copy(
writings = writings
)
}
}
}
|
vipexam/app/src/main/java/app/xlei/vipexam/ui/question/qread/QreadUiState.kt | 2877301944 | package app.xlei.vipexam.ui.question.qread
import androidx.compose.runtime.MutableState
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
data class QreadUiState(
val muban: Muban?=null,
var showBottomSheet: Boolean = false,
var showOptionsSheet: Boolean = false,
val articles: List<Article>
){
data class Article(
val title: String,
val content: String,
val questions: List<Question>,
val options: List<Option>,
)
data class Question(
val index: String,
val question: String,
var choice: MutableState<String>,
val refAnswer: String,
val description: String,
)
data class Option(
val index: Int,
val option: String,
)
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/question/qread/QreadViewModel.kt | 1777456164 | package app.xlei.vipexam.ui.question.qread
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.lifecycle.ViewModel
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.database.module.Word
import app.xlei.vipexam.core.network.module.getExamResponse.Children
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class QreadViewModel @Inject constructor(
qreadUiState: QreadUiState,
private val repository: Repository<Word>,
) : ViewModel() {
private val _uiState = MutableStateFlow(qreadUiState)
val uiState: StateFlow<QreadUiState> = _uiState.asStateFlow()
fun setMuban(muban: Muban) {
_uiState.update {
it.copy(
muban = muban
)
}
}
@Composable
fun SetArticles () {
val articles = mutableListOf<QreadUiState.Article>()
_uiState.collectAsState().value.muban!!.shiti.forEach {
articles.add(
QreadUiState.Article(
title = extractFirstPart(it.primQuestion),
content = extractSecondPart(it.primQuestion),
questions = getQuestions(it.children),
options = getOptions(it.primQuestion),
)
)
}
_uiState.update {
it.copy(
articles = articles
)
}
}
fun toggleBottomSheet(){
_uiState.update {
it.copy(
showBottomSheet = !it.showBottomSheet
)
}
}
fun toggleOptionsSheet() {
_uiState.update {
it.copy(
showOptionsSheet = !it.showOptionsSheet
)
}
}
fun setOption(selectedArticleIndex: Int, selectedQuestion: Int, option: String) {
_uiState.value.articles[selectedArticleIndex].questions[selectedQuestion].choice.value = option
}
private fun getOptions(text: String): MutableList<QreadUiState.Option> {
val result = mutableListOf<QreadUiState.Option>()
var pattern = Regex("""([A-Z])([)])""")
var matches = pattern.findAll(text)
if (matches.count() < 10) {
pattern = Regex("""([A-Z])(])""")
matches = pattern.findAll(text)
}
for ((index, match) in matches.withIndex()) {
result.add(
QreadUiState.Option(
index = index + 1,
option = match.groupValues[1]
)
)
}
return result
}
@Composable
private fun getQuestions(children: List<Children>): MutableList<QreadUiState.Question> {
val questions = mutableListOf<QreadUiState.Question>()
children.forEachIndexed {index,it->
questions.add(
QreadUiState.Question(
index = "${index + 1}",
question = it.secondQuestion,
choice = rememberSaveable { mutableStateOf("") },
refAnswer = it.refAnswer,
description = it.discription
)
)
}
return questions
}
private fun extractFirstPart(text: String): String {
val lines = text.split("\n")
if (lines.isNotEmpty()) {
return lines.first().trim()
}
return ""
}
private fun extractSecondPart(text: String): String {
val index = text.indexOf("\n")
if (index != -1) {
return text.substring(index + 1)
}
return ""
}
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/question/qread/Qread.kt | 868406433 | package app.xlei.vipexam.ui.question.qread
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.network.module.getExamResponse.Muban
import app.xlei.vipexam.core.ui.VipexamArticleContainer
import app.xlei.vipexam.preference.LocalShowAnswer
import app.xlei.vipexam.preference.LocalVibrate
@Composable
fun QreadView(
submitMyAnswer: (String, String) -> Unit,
viewModel: QreadViewModel = hiltViewModel(),
muban: Muban,
) {
viewModel.setMuban(muban)
viewModel.SetArticles()
val vibrate = LocalVibrate.current.isVibrate()
val showAnswer = LocalShowAnswer.current.isShowAnswer()
val uiState by viewModel.uiState.collectAsState()
val haptics = LocalHapticFeedback.current
var selectedQuestionIndex by rememberSaveable { mutableIntStateOf(0) }
Qread(
showBottomSheet = uiState.showBottomSheet,
showOptionsSheet = uiState.showOptionsSheet,
articles = uiState.articles,
toggleBottomSheet = viewModel::toggleBottomSheet,
toggleOptionsSheet = viewModel::toggleOptionsSheet,
onArticleLongClicked = {
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
onQuestionClicked = {
selectedQuestionIndex = it
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
onOptionClicked = { selectedArticleIndex, option ->
submitMyAnswer(
muban.shiti[selectedArticleIndex].children[selectedQuestionIndex].questionCode,
option
)
viewModel.setOption(selectedArticleIndex, selectedQuestionIndex, option)
if (vibrate) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
},
showAnswer = showAnswer,
)
}
@OptIn(
ExperimentalMaterial3Api::class,
ExperimentalLayoutApi::class
)
@Composable
private fun Qread(
showBottomSheet: Boolean,
showOptionsSheet: Boolean,
articles: List<QreadUiState.Article>,
toggleBottomSheet: () -> Unit,
toggleOptionsSheet: () -> Unit,
onArticleLongClicked: () -> Unit,
onQuestionClicked: (Int) -> Unit,
onOptionClicked: (Int, String) -> Unit,
showAnswer: Boolean,
){
val scrollState = rememberLazyListState()
val selectedArticle by rememberSaveable { mutableIntStateOf(0) }
Column {
LazyColumn(
state = scrollState
) {
articles.forEachIndexed { articleIndex, article ->
item {
VipexamArticleContainer(
onArticleLongClick = {
onArticleLongClicked.invoke()
toggleBottomSheet.invoke()
},
onDragContent = article.title
+ "\n\n" + article.content
+ article.questions.joinToString{ "\n\n" + it.index + ". " + it.question }
) {
Column(
modifier = Modifier
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
) {
Text(
text = articles[articleIndex].title,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontSize = 24.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.align(Alignment.CenterHorizontally)
)
Text(
text = articles[articleIndex].content,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier
.padding(16.dp)
)
}
}
}
items(article.questions.size) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
onQuestionClicked(it)
toggleOptionsSheet()
}
) {
Column(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = "${article.questions[it].index}. ${article.questions[it].question}",
color = MaterialTheme.colorScheme.onPrimaryContainer,
)
if (article.questions[it].choice.value != "") {
SuggestionChip(
onClick = toggleOptionsSheet,
label = { Text(article.questions[it].choice.value) }
)
}
}
}
if (showAnswer)
articles[articleIndex].questions[it].let { question ->
Text(
text = question.index + question.refAnswer,
modifier = Modifier.padding(horizontal = 24.dp)
)
Text(
text = question.description,
modifier = Modifier
.padding(horizontal = 24.dp)
)
}
}
}
}
// Questions
if (showBottomSheet) {
ModalBottomSheet(
onDismissRequest = toggleBottomSheet,
) {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
) {
articles[selectedArticle].questions.forEachIndexed { index, it ->
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
onQuestionClicked(index)
toggleOptionsSheet()
}
) {
Text(
text = "${it.index}. ${it.question}",
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(16.dp)
)
if (it.choice.value != "") {
SuggestionChip(
onClick = toggleOptionsSheet,
label = { Text(it.choice.value) }
)
}
}
}
}
}
}
// options
if (showOptionsSheet) {
ModalBottomSheet(
onDismissRequest = toggleOptionsSheet,
) {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
){
FlowRow(
horizontalArrangement = Arrangement.Start,
maxItemsInEachRow = 5,
modifier = Modifier
.padding(bottom = 24.dp)
) {
articles[selectedArticle].options.forEach {
Column(
modifier = Modifier
.weight(1f)
) {
SuggestionChip(
onClick = {
onOptionClicked(selectedArticle, it.option)
toggleOptionsSheet()
},
label = {
Text(it.option)
}
)
}
}
}
}
}
}
}
}
|
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/CheckBox.kt | 262100628 | package app.xlei.vipexam.ui.components
import androidx.compose.material3.Checkbox
import androidx.compose.runtime.Composable
/**
* Vipexam checkbox
*
* @param checked
* @param onCheckedChange
*/
@Composable
fun VipexamCheckbox(
checked: Boolean,
onCheckedChange: ((Boolean) -> Unit)?,
){
Checkbox(
checked = checked,
onCheckedChange = onCheckedChange,
)
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/HideOnScrollFAB.kt | 2024194698 | package app.xlei.vipexam.ui.components
|
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/AppNavRail.kt | 2617237517 | package app.xlei.vipexam.ui.components
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Spacer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import app.xlei.vipexam.ui.navigation.AppDestinations
/**
* App nav rail
*
* @param logo 侧边导航的logo
* @param homeNavController 主页导航控制器
* @param currentRoute 当前导航页面
* @param navigationToTopLevelDestination 导航函数
* @param modifier
* @receiver
* @receiver
*/
@Composable
fun AppNavRail(
logo: @Composable () -> Unit = {},
homeNavController: NavHostController,
currentRoute: String,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
@SuppressLint("ModifierParameter") modifier: Modifier = Modifier
) {
NavigationRail(
header = {
logo()
},
containerColor = NavigationRailDefaults.ContainerColor,
modifier = modifier
) {
Spacer(Modifier.weight(1f))
AppDestinations.entries.forEach {
NavigationRailItem(
currentRoute = currentRoute,
appDestination = it,
navigationToTopLevelDestination = navigationToTopLevelDestination
)
}
if (currentRoute == AppDestinations.HOME_ROUTE.name &&
homeNavController.previousBackStackEntry != null
)
IconButton(
onClick = { homeNavController.navigateUp() },
) {
Icon(Icons.AutoMirrored.Filled.KeyboardArrowLeft, null)
}
Spacer(Modifier.weight(1f))
}
}
@Composable
private fun NavigationRailItem(
currentRoute: String,
appDestination: AppDestinations,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
){
NavigationRailItem(
selected = currentRoute == appDestination.name,
onClick = { navigationToTopLevelDestination(appDestination) },
icon = { Icon(appDestination.icon, stringResource(appDestination.title)) },
label = { Text(stringResource(appDestination.title)) },
alwaysShowLabel = false
)
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/Dialog.kt | 1012172805 | package app.xlei.vipexam.ui.components
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.vector.ImageVector
/**
* Text icon dialog
*
* @param onDismissRequest 忽略事件
* @param onConfirmation 确认事件
* @param dialogTitle 对话框标题
* @param dialogText 对话框文字内容
* @param icon 图标
* @receiver
* @receiver
*/
@Composable
fun TextIconDialog(
onDismissRequest: () -> Unit,
onConfirmation: () -> Unit,
dialogTitle: String,
dialogText: String,
icon: ImageVector,
) {
AlertDialog(
icon = {
Icon(icon, contentDescription = "Icon")
},
title = {
Text(text = dialogTitle)
},
text = {
Text(text = dialogText)
},
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(
onClick = onConfirmation
) {
Text("Confirm")
}
},
dismissButton = {
TextButton(
onClick = onDismissRequest
) {
Text("Dismiss")
}
}
)
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/vm/SearchViewModel.kt | 218477334 | package app.xlei.vipexam.ui.components.vm
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import app.xlei.vipexam.core.data.paging.ExamListItem
import app.xlei.vipexam.core.data.paging.ExamListRepository
import app.xlei.vipexam.core.network.module.NetWorkRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Search view model
*
* @property examListRepository 试卷列表
* @constructor Create empty Search view model
*/
@HiltViewModel
class SearchViewModel @Inject constructor(
private val examListRepository : ExamListRepository,
) : ViewModel() {
private val _examListState: MutableStateFlow<PagingData<ExamListItem>> =
MutableStateFlow(value = PagingData.empty())
val examListState: MutableStateFlow<PagingData<ExamListItem>>
get() = _examListState
/**
* Search
* 搜索试卷
* @param query 搜索关键词
*/
fun search(query: String) {
viewModelScope.launch {
examListRepository.search(query)
.distinctUntilChanged()
.cachedIn(viewModelScope)
.collect {
_examListState.value = it
}
}
}
/**
* Download
* 下载试卷
* @param fileName 文件名
* @param examId 试卷id
*/
fun download(
fileName: String,
examId: String,
) {
viewModelScope.launch {
NetWorkRepository
.download(
fileName = fileName,
examId = examId
)
}
}
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/CustomFloatingButton.kt | 2784525198 | package app.xlei.vipexam.ui.components
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.R
/**
* Custom floating action button
*
* @param expandable 是否能展开
* @param onFabClick 按钮点击事件
* @param iconUnExpanded 未展开图标
* @param iconExpanded 展开图标
* @param items 展开显示的内容,按从上到下排列
* @param onItemClick 内容点击事件
* @receiver
* @receiver
*/
@Composable
fun CustomFloatingActionButton(
expandable: Boolean,
onFabClick: () -> Unit,
iconUnExpanded: ImageVector,
iconExpanded: ImageVector,
items: List<Pair<String, String>>,
onItemClick: (String) -> Unit,
) {
var isExpanded by remember { mutableStateOf(false) }
if (!expandable) { // Close the expanded fab if you change to non expandable nav destination
isExpanded = false
}
val fabSize = 56.dp
val expandedFabWidth by animateDpAsState(
targetValue = if (isExpanded) 200.dp else fabSize,
animationSpec = spring(dampingRatio = 3f), label = ""
)
val expandedFabHeight by animateDpAsState(
targetValue = if (isExpanded) 56.dp else fabSize,
animationSpec = spring(dampingRatio = 3f), label = ""
)
Column {
Column(
modifier = Modifier
.offset(y = (16).dp)
.size(
width = expandedFabWidth,
height = (animateDpAsState(
if (isExpanded) 225.dp else 0.dp,
animationSpec = spring(dampingRatio = 4f), label = ""
)).value
)
.background(
MaterialTheme.colorScheme.surfaceContainer,
shape = RoundedCornerShape(16.dp)
)
.verticalScroll(rememberScrollState())
) {
Column(
modifier = Modifier
.padding(bottom = 16.dp)
) {
items.forEach{
Column(
modifier = Modifier
.fillMaxWidth()
.height(fabSize)
.padding(4.dp)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.primaryContainer)
.clickable {
onItemClick(it.first)
isExpanded = false
}
) {
Spacer(modifier = Modifier.weight(1f))
Text(
text = it.second,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = MaterialTheme.typography.bodyLarge.fontWeight,
modifier = Modifier
.align(Alignment.CenterHorizontally)
)
Spacer(modifier = Modifier.weight(1f))
}
}
}
}
FloatingActionButton(
onClick = {
onFabClick()
if (expandable) {
isExpanded = !isExpanded
}
},
modifier = Modifier
.width(expandedFabWidth)
.height(expandedFabHeight),
shape = RoundedCornerShape(16.dp)
) {
Icon(
imageVector = if(isExpanded){iconExpanded}else{iconUnExpanded},
contentDescription = null,
modifier = Modifier
.size(24.dp)
.offset(
x = animateDpAsState(
if (isExpanded) -70.dp else 0.dp,
animationSpec = spring(dampingRatio = 3f), label = ""
).value
)
)
Text(
text = stringResource(R.string.close_button),
softWrap = false,
modifier = Modifier
.offset(
x = animateDpAsState(
if (isExpanded) 10.dp else 50.dp,
animationSpec = spring(dampingRatio = 3f), label = ""
).value
)
.alpha(
animateFloatAsState(
targetValue = if (isExpanded) 1f else 0f,
animationSpec = tween(
durationMillis = if (isExpanded) 350 else 100,
delayMillis = if (isExpanded) 100 else 0,
easing = EaseIn
), label = ""
).value
)
)
}
}
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/AppDrawer.kt | 1185275010 | package app.xlei.vipexam.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.ui.navigation.AppDestinations
/**
* App drawer
*
* @param currentRoute 当前导航
* @param navigationToTopLevelDestination 导航函数
* @param closeDrawer 关闭抽屉函数
* @param modifier
* @receiver
* @receiver
*/
@Composable
fun AppDrawer(
currentRoute: String,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
closeDrawer: () -> Unit,
modifier: Modifier = Modifier
) {
ModalDrawerSheet(
drawerContainerColor = MaterialTheme.colorScheme.surfaceContainer,
drawerContentColor = MaterialTheme.colorScheme.surface,
modifier = modifier
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(top = 24.dp)
) {
AppDestinations.entries.forEach {
VipexamDrawerItem(
currentRoute = currentRoute,
destination = it,
navigationToTopLevelDestination = navigationToTopLevelDestination
) {
closeDrawer.invoke()
}
}
}
}
}
@Composable
private fun VipexamDrawerItem(
currentRoute: String,
destination: AppDestinations,
navigationToTopLevelDestination: (AppDestinations) -> Unit,
closeDrawer: () -> Unit,
){
NavigationDrawerItem(
label = { Text(stringResource(id = destination.title)) },
icon = { Icon(destination.icon, null) },
selected = currentRoute == destination.name,
onClick = { navigationToTopLevelDestination(destination); closeDrawer() },
colors = NavigationDrawerItemDefaults.colors(
unselectedContainerColor = MaterialTheme.colorScheme.surfaceContainer
),
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
)
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/Timer.kt | 2058787557 | package app.xlei.vipexam.ui.components
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
/**
* Timer view model
* 计时器vm
* @constructor Create empty Timer view model
*/
class TimerViewModel : ViewModel() {
private val _time = MutableStateFlow(0)
val time: StateFlow<Int> = _time
private var timerJob: Job? = null
fun startTimer() {
timerJob?.cancel()
timerJob = viewModelScope.launch {
while (true) {
delay(1000)
_time.value++
}
}
}
fun stopTimer() {
timerJob?.cancel()
}
fun resetTimer() {
_time.value = 0
}
}
/**
* Timer
* 计时器
* @param timerViewModel 计时器vm
* @param isTimerStart 开始
* @param isResetTimer 结束
* @param modifier
*/
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun Timer(
timerViewModel: TimerViewModel = viewModel(),
isTimerStart: Boolean,
isResetTimer: Boolean,
@SuppressLint("ModifierParameter") modifier: Modifier = Modifier,
) {
val time by timerViewModel.time.collectAsState()
Column(
modifier = modifier,
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = formatTime(time), style = MaterialTheme.typography.labelLarge)
}
if (isTimerStart)
timerViewModel.startTimer()
else
timerViewModel.stopTimer()
if (isResetTimer)
timerViewModel.resetTimer()
}
@SuppressLint("DefaultLocale")
private fun formatTime(seconds: Int): String {
val minutes = seconds / 60
val remainingSeconds = seconds % 60
return String.format("%02d:%02d", minutes, remainingSeconds)
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/components/ExamSearchBar.kt | 4287023011 | package app.xlei.vipexam.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.SearchBar
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import app.xlei.vipexam.core.ui.ErrorMessage
import app.xlei.vipexam.core.ui.LoadingNextPageItem
import app.xlei.vipexam.core.ui.PageLoader
import app.xlei.vipexam.ui.components.vm.SearchViewModel
import compose.icons.FeatherIcons
import compose.icons.feathericons.Search
import compose.icons.feathericons.X
/**
* Exam search bar
*
* @param modifier
* @param viewModel 搜索vm
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExamSearchBar(
modifier: Modifier = Modifier,
viewModel: SearchViewModel = hiltViewModel()
){
var queryString by remember {
mutableStateOf("")
}
var isActive by remember {
mutableStateOf(false)
}
SearchBar(
query = queryString,
onQueryChange = { queryString = it },
onSearch = { viewModel.search(queryString) },
active = isActive,
onActiveChange = { isActive = it },
leadingIcon = {
IconButton(onClick = { isActive = true }) {
Icon(imageVector = FeatherIcons.Search, contentDescription = null)
}
},
trailingIcon = {
if (isActive)
IconButton(onClick = {
isActive = false
queryString = ""
}) {
Icon(imageVector = FeatherIcons.X, contentDescription = null)
}
},
modifier = modifier,
) {
val results = viewModel.examListState.collectAsLazyPagingItems()
LazyColumn {
items(results.itemCount) {
ListItem(
headlineContent = { results[it]?.exam?.let { exam->
Text(text = exam.examname) } },
modifier = Modifier
.clickable {
results[it]?.exam?.let { exam ->
viewModel.download(
fileName = exam.examname,
examId = exam.examid,
)
}
}
)
}
results.apply {
when {
loadState.refresh is LoadState.Loading -> {
item { PageLoader(modifier = Modifier.fillParentMaxSize()) }
}
loadState.refresh is LoadState.Error -> {
val error = results.loadState.refresh as LoadState.Error
item {
ErrorMessage(
modifier = Modifier.fillParentMaxSize(),
message = error.error.localizedMessage!!,
onClickRetry = { retry() })
}
}
loadState.append is LoadState.Loading -> {
item { LoadingNextPageItem(modifier = Modifier) }
}
loadState.append is LoadState.Error -> {
val error = results.loadState.append as LoadState.Error
item {
ErrorMessage(
modifier = Modifier,
message = error.error.localizedMessage!!,
onClickRetry = { retry() })
}
}
}
}
}
}
}
|
vipexam/app/src/main/java/app/xlei/vipexam/ui/theme/Color.kt | 2563283388 | package app.xlei.vipexam.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF9B404F)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFFFD9DC)
val md_theme_light_onPrimaryContainer = Color(0xFF400011)
val md_theme_light_secondary = Color(0xFF765659)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFFFD9DC)
val md_theme_light_onSecondaryContainer = Color(0xFF2C1518)
val md_theme_light_tertiary = Color(0xFF785830)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFDDB7)
val md_theme_light_onTertiaryContainer = Color(0xFF2A1700)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF201A1A)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF201A1A)
val md_theme_light_surfaceVariant = Color(0xFFF4DDDE)
val md_theme_light_onSurfaceVariant = Color(0xFF524344)
val md_theme_light_outline = Color(0xFF847374)
val md_theme_light_inverseOnSurface = Color(0xFFFBEEEE)
val md_theme_light_inverseSurface = Color(0xFF362F2F)
val md_theme_light_inversePrimary = Color(0xFFFFB2BA)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF9B404F)
val md_theme_light_outlineVariant = Color(0xFFD7C1C3)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFFFB2BA)
val md_theme_dark_onPrimary = Color(0xFF5F1224)
val md_theme_dark_primaryContainer = Color(0xFF7D2939)
val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9DC)
val md_theme_dark_secondary = Color(0xFFE5BDC0)
val md_theme_dark_onSecondary = Color(0xFF43292C)
val md_theme_dark_secondaryContainer = Color(0xFF5C3F42)
val md_theme_dark_onSecondaryContainer = Color(0xFFFFD9DC)
val md_theme_dark_tertiary = Color(0xFFE9BF8F)
val md_theme_dark_onTertiary = Color(0xFF442B07)
val md_theme_dark_tertiaryContainer = Color(0xFF5E411B)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDDB7)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF201A1A)
val md_theme_dark_onBackground = Color(0xFFECE0E0)
val md_theme_dark_surface = Color(0xFF201A1A)
val md_theme_dark_onSurface = Color(0xFFECE0E0)
val md_theme_dark_surfaceVariant = Color(0xFF524344)
val md_theme_dark_onSurfaceVariant = Color(0xFFD7C1C3)
val md_theme_dark_outline = Color(0xFF9F8C8D)
val md_theme_dark_inverseOnSurface = Color(0xFF201A1A)
val md_theme_dark_inverseSurface = Color(0xFFECE0E0)
val md_theme_dark_inversePrimary = Color(0xFF9B404F)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFFFB2BA)
val md_theme_dark_outlineVariant = Color(0xFF524344)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFFFEDFE1) |
vipexam/app/src/main/java/app/xlei/vipexam/ui/theme/Theme.kt | 3577379923 | package app.xlei.vipexam.ui.theme
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
import app.xlei.vipexam.preference.ThemeModePreference
import com.google.android.material.color.utilities.Scheme
const val defaultAccentColor = "fedfe1"
fun String.hexToColor() = Color(android.graphics.Color.parseColor("#$this"))
@SuppressLint("RestrictedApi")
@Composable
fun VipexamTheme(
themeMode: ThemeModePreference,
shouldShowNavigationRegion: Boolean = false,
content: @Composable () -> Unit,
) {
val darkTheme = when (themeMode) {
ThemeModePreference.Auto -> isSystemInDarkTheme()
ThemeModePreference.Light -> false
ThemeModePreference.Dark, ThemeModePreference.Black -> true
}
var colorScheme = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
else -> {
val seed = defaultAccentColor.hexToColor().toArgb()
if (darkTheme) Scheme.dark(seed).toColorScheme() else Scheme.light(seed).toColorScheme()
}
}
if (themeMode == ThemeModePreference.Black) colorScheme =
colorScheme.copy(background = Color.Black, surface = Color.Black)
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val activity = view.context as Activity
activity.window.navigationBarColor = colorScheme.run {
if (shouldShowNavigationRegion)
this.surfaceContainer.toArgb()
else
this.surface.toArgb()
}
activity.window.statusBarColor = colorScheme.run {
if (shouldShowNavigationRegion)
this.surfaceContainer.toArgb()
else
this.surface.toArgb()
}
WindowCompat.getInsetsController(
activity.window,
view
).isAppearanceLightStatusBars = !darkTheme
WindowCompat.getInsetsController(
activity.window,
view
).isAppearanceLightNavigationBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@SuppressLint("RestrictedApi")
fun Scheme.toColorScheme() = ColorScheme(
primary = Color(primary),
onPrimary = Color(onPrimary),
primaryContainer = Color(primaryContainer),
onPrimaryContainer = Color(onPrimaryContainer),
inversePrimary = Color(inversePrimary),
secondary = Color(secondary),
onSecondary = Color(onSecondary),
secondaryContainer = Color(secondaryContainer),
onSecondaryContainer = Color(onSecondaryContainer),
tertiary = Color(tertiary),
onTertiary = Color(onTertiary),
tertiaryContainer = Color(tertiaryContainer),
onTertiaryContainer = Color(onTertiaryContainer),
background = Color(background),
onBackground = Color(onBackground),
surface = Color(surface),
onSurface = Color(onSurface),
surfaceVariant = Color(surfaceVariant),
onSurfaceVariant = Color(onSurfaceVariant),
surfaceTint = Color(primary),
inverseSurface = Color(inverseSurface),
inverseOnSurface = Color(inverseOnSurface),
error = Color(error),
onError = Color(onError),
errorContainer = Color(errorContainer),
onErrorContainer = Color(onErrorContainer),
outline = Color(outline),
outlineVariant = Color(outlineVariant),
scrim = Color(scrim)
) |
vipexam/app/src/main/java/app/xlei/vipexam/ui/theme/Type.kt | 990349594 | package app.xlei.vipexam.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) |
vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/ExamScreen.kt | 2087320433 | package app.xlei.vipexam.ui.screen
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.expanded.ExamScreenSupportingPane
import app.xlei.vipexam.ui.page.ExamPage
/**
* Exam screen
* 试卷页面
* @param questionListUiState 问题列表
* @param setQuestion 问题点击事件
* @param widthSizeClass 屏幕宽度
* @param modifier
* @param navController 试卷页面导航控制器,用于切换问题
* @receiver
*/
@Composable
fun ExamScreen(
questionListUiState: VipexamUiState.QuestionListUiState,
setQuestion: (String, GetExamResponse) -> Unit,
widthSizeClass: WindowWidthSizeClass,
modifier: Modifier = Modifier,
navController: NavHostController = rememberNavController(),
submitMyAnswer: (String, String) -> Unit,
onExamClick: (String) -> Unit,
) {
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> {
ExamPage(
questionListUiState = questionListUiState,
setQuestion = setQuestion,
navController = navController,
submitMyAnswer = submitMyAnswer
)
}
WindowWidthSizeClass.Medium -> {
ExamPage(
questionListUiState = questionListUiState,
setQuestion = setQuestion,
navController = navController,
submitMyAnswer = submitMyAnswer
)
}
WindowWidthSizeClass.Expanded -> {
Row (
modifier = modifier
){
Column(
modifier = Modifier
.padding(horizontal = 24.dp)
.weight(1f)
) {
ExamPage(
questionListUiState = questionListUiState,
setQuestion = setQuestion,
navController = navController,
showFab = false,
submitMyAnswer = submitMyAnswer
)
}
ExamScreenSupportingPane(
questionListUiState = questionListUiState,
navController = navController,
modifier = Modifier
.width(360.dp)
.padding(end = 24.dp)
.fillMaxSize(),
onExamClick = onExamClick
)
}
}
}
}
|
vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/HomeScreen.kt | 2599877859 | package app.xlei.vipexam.ui.screen
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalConfiguration
import androidx.navigation.NavHostController
import app.xlei.vipexam.ui.VipExamMainScreenViewModel
import app.xlei.vipexam.ui.appbar.VipExamAppBar
import app.xlei.vipexam.ui.navigation.MainScreenNavigation
/**
* Home screen
*
* @param modifier
* @param logoText
* @param widthSizeClass 屏幕宽度
* @param viewModel 主页vm
* @param navController 主页导航控制器
* @param openDrawer 打开侧边抽屉事件
* @receiver
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
modifier: Modifier = Modifier,
logoText: (@Composable () -> Unit)? = null,
widthSizeClass: WindowWidthSizeClass,
viewModel: VipExamMainScreenViewModel,
navController: NavHostController,
openDrawer: () -> Unit,
) {
val uiState by viewModel.uiState.collectAsState()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
val localConfiguration = LocalConfiguration.current
Scaffold(
modifier = modifier
.fillMaxSize()
.statusBarsPadding()
.run {
// LazyColumn will not be scrollable without this in expanded width size
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> this.nestedScroll(scrollBehavior.nestedScrollConnection)
WindowWidthSizeClass.Expanded -> {
when (localConfiguration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> this
Configuration.ORIENTATION_PORTRAIT -> this.nestedScroll(scrollBehavior.nestedScrollConnection)
else -> this
}
}
else -> this
}
},
topBar = {
when (widthSizeClass) {
WindowWidthSizeClass.Compact ->
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
WindowWidthSizeClass.Medium -> {
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
}
WindowWidthSizeClass.Expanded -> {
when (localConfiguration.orientation) {
Configuration.ORIENTATION_PORTRAIT -> {
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
}
else -> {
VipExamAppBar(
appBarTitle = uiState.title,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
openDrawer = openDrawer,
scrollBehavior = scrollBehavior,
scrollable = false,
myAnswer = viewModel.myAnswer.collectAsState().value,
)
}
}
}
}
}
) { padding ->
MainScreenNavigation(
navHostController = navController,
widthSizeClass = widthSizeClass,
modifier = Modifier.padding(padding),
viewModel = viewModel,
)
}
}
|
vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/ExamListScreen.kt | 154197823 | package app.xlei.vipexam.ui.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.R
import app.xlei.vipexam.core.ui.OnError
import app.xlei.vipexam.core.ui.OnLoading
import app.xlei.vipexam.core.ui.PageLoader
import app.xlei.vipexam.ui.UiState
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.expanded.ExamListScreenSupportingPane
import app.xlei.vipexam.ui.page.ExamListView
/**
* Exam list screen
* 试卷列表页面
* @param examListUiState 试卷列表
* @param onLastExamClick 最近试卷点击事件
* @param onExamClick 试卷点击事件
* @param widthSizeClass 屏幕宽度
* @param modifier
* @receiver
* @receiver
* @receiver
*/
@Composable
fun ExamListScreen(
examListUiState: UiState<VipexamUiState.ExamListUiState>,
onLastExamClick: (String) -> Unit,
onExamClick: (String) -> Unit,
widthSizeClass: WindowWidthSizeClass,
modifier: Modifier = Modifier
) {
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> {
when (examListUiState) {
is UiState.Success -> {
ExamListView(
isReal = examListUiState.uiState.isReal,
onExamClick = onExamClick,
)
}
is UiState.Loading -> {
PageLoader()
}
is UiState.Error -> {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.internet_error),
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
}
}
WindowWidthSizeClass.Medium -> {
when (examListUiState) {
is UiState.Success -> {
ExamListView(
isReal = examListUiState.uiState.isReal,
onExamClick = onExamClick,
modifier = modifier
.background(MaterialTheme.colorScheme.surfaceContainer)
)
}
is UiState.Loading -> {
OnLoading()
}
is UiState.Error -> {
OnError()
}
}
}
WindowWidthSizeClass.Expanded -> {
Row(
modifier = modifier
) {
Card(
modifier = Modifier
.background(MaterialTheme.colorScheme.surface)
.padding(horizontal = 24.dp)
.weight(1f)
) {
when (examListUiState) {
is UiState.Success -> {
ExamListView(
isReal = examListUiState.uiState.isReal,
onExamClick = onExamClick,
modifier = Modifier
.background(MaterialTheme.colorScheme.primaryContainer)
.fillMaxSize()
)
}
is UiState.Loading -> {
OnLoading()
}
is UiState.Error -> {
OnError()
}
}
}
ExamListScreenSupportingPane(
modifier = Modifier
.width(360.dp)
.padding(end = 24.dp)
.fillMaxSize()
){
onExamClick.invoke(it)
}
}
}
}
} |
vipexam/app/src/main/java/app/xlei/vipexam/ui/screen/ExamTypeListScreen.kt | 160440491 | package app.xlei.vipexam.ui.screen
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.core.data.constant.ExamType
import app.xlei.vipexam.ui.UiState
import app.xlei.vipexam.ui.VipexamUiState
import app.xlei.vipexam.ui.page.ExamTypeListView
/**
* Exam type list screen
* 试卷类型列表页面
* @param examTypeListUiState 试卷类型列表
* @param onExamTypeClick 试卷类型点击事件
* @param widthSizeClass 屏幕宽度
* @param modifier
* @receiver
* @receiver
*/
@Composable
fun ExamTypeListScreen(
examTypeListUiState: UiState<VipexamUiState.ExamTypeListUiState>,
onExamTypeClick: (ExamType) -> Unit,
onLastViewedClick: (String) -> Unit,
widthSizeClass: WindowWidthSizeClass,
modifier: Modifier = Modifier
) {
when (widthSizeClass) {
WindowWidthSizeClass.Compact -> {
ExamTypeListView(
examTypeListUiState = examTypeListUiState,
onExamTypeClick = onExamTypeClick,
onLastViewedClick = onLastViewedClick
)
}
WindowWidthSizeClass.Medium -> {
ExamTypeListView(
examTypeListUiState = examTypeListUiState,
onExamTypeClick = onExamTypeClick,
onLastViewedClick = onLastViewedClick
)
}
WindowWidthSizeClass.Expanded -> {
Column(
modifier = modifier
.padding(horizontal = 24.dp)
.clip(MaterialTheme.shapes.extraLarge)
//.background(MaterialTheme.colorScheme.surfaceContainer)
) {
ExamTypeListView(
examTypeListUiState = examTypeListUiState,
onExamTypeClick = onExamTypeClick,
onLastViewedClick = onLastViewedClick,
modifier = Modifier
.fillMaxSize()
)
}
}
}
}
|
vipexam/app/src/main/java/app/xlei/vipexam/ui/VipExamState.kt | 1208998739 | package app.xlei.vipexam.ui
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import app.xlei.vipexam.core.data.util.NetworkMonitor
import app.xlei.vipexam.ui.navigation.AppDestinations
import app.xlei.vipexam.ui.navigation.VipExamNavigationActions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
@Composable
fun rememberVipExamAppState(
windowSizeClass: WindowWidthSizeClass,
networkMonitor: NetworkMonitor,
coroutineScope: CoroutineScope = rememberCoroutineScope(),
navController: NavHostController = rememberNavController(),
): VipExamState {
return remember(
navController,
coroutineScope,
windowSizeClass,
) {
VipExamState(
vipExamNavigationActions = VipExamNavigationActions(navController),
coroutineScope = coroutineScope,
widthSizeClass = windowSizeClass,
navController = navController,
networkMonitor,
)
}
}
@Stable
class VipExamState(
val vipExamNavigationActions: VipExamNavigationActions,
val coroutineScope: CoroutineScope,
val widthSizeClass: WindowWidthSizeClass,
val navController: NavHostController,
networkMonitor: NetworkMonitor,
) {
val shouldShowTopBar: Boolean
get() = widthSizeClass == WindowWidthSizeClass.Compact
val shouldShowNavRail: Boolean
get() = widthSizeClass == WindowWidthSizeClass.Medium
val shouldShowAppDrawer: Boolean
get() = widthSizeClass == WindowWidthSizeClass.Expanded
fun navigateToAppDestination(appDestination: AppDestinations) {
when (appDestination) {
AppDestinations.HOME_ROUTE -> vipExamNavigationActions.navigateToHome()
AppDestinations.SECOND_ROUTE -> vipExamNavigationActions.navigateToWords()
AppDestinations.SETTINGS_ROUTE -> vipExamNavigationActions.navigateToSettings()
AppDestinations.HISTORY -> vipExamNavigationActions.navigateToHistory()
AppDestinations.BOOKMARKS -> vipExamNavigationActions.navigateToBookmarks()
}
}
val isOffline = networkMonitor.isOnline
.map(Boolean::not)
.stateIn(
scope = coroutineScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = false,
)
} |
vipexam/app/src/main/java/app/xlei/vipexam/MainActivity.kt | 2137856102 | package app.xlei.vipexam
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.systemBars
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.core.data.repository.Repository
import app.xlei.vipexam.core.data.util.NetworkMonitor
import app.xlei.vipexam.core.database.module.Word
import app.xlei.vipexam.core.ui.AddToWordListButton
import app.xlei.vipexam.core.ui.TranslateDialog
import app.xlei.vipexam.feature.wordlist.WordListScreen
import app.xlei.vipexam.feature.wordlist.components.copyToClipboard
import app.xlei.vipexam.feature.wordlist.constant.SortMethod
import app.xlei.vipexam.preference.LanguagePreference
import app.xlei.vipexam.preference.LocalThemeMode
import app.xlei.vipexam.preference.SettingsProvider
import app.xlei.vipexam.preference.languages
import app.xlei.vipexam.ui.App
import app.xlei.vipexam.ui.rememberVipExamAppState
import app.xlei.vipexam.ui.theme.VipexamTheme
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var networkMonitor: NetworkMonitor
@Inject
lateinit var wordRepository: Repository<Word>
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT < 33) {
LanguagePreference.fromValue(languages).let {
LanguagePreference.setLocale(it)
}
}
setContent {
val widthSizeClass = calculateWindowSizeClass(this).widthSizeClass
val appState = rememberVipExamAppState(
windowSizeClass = widthSizeClass,
networkMonitor = networkMonitor,
)
val density = LocalDensity.current
val windowsInsets = WindowInsets.systemBars
val bottomInset = with(density) { windowsInsets.getBottom(density).toDp() }
val scrollAwareWindowInsets = remember(bottomInset) {
windowsInsets
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top)
.add(WindowInsets(bottom = bottomInset))
}
CompositionLocalProvider(
LocalScrollAwareWindowInsets provides scrollAwareWindowInsets
) {
SettingsProvider {
VipexamTheme(
themeMode = LocalThemeMode.current,
shouldShowNavigationRegion = appState.shouldShowAppDrawer,
) {
App(
widthSizeClass = widthSizeClass,
appState = appState
)
}
}
}
}
handleIntentData()
}
private fun getIntentText(): String? {
return intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()
?: intent?.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString()
?: intent.getCharSequenceExtra(Intent.ACTION_SEND)?.toString()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
this.intent = intent
handleIntentData()
}
private fun handleIntentData() {
getIntentText()?.let {
this.copyToClipboard(it)
setContent {
SettingsProvider {
VipexamTheme(
themeMode = LocalThemeMode.current,
) {
var showTranslateDialog by remember {
mutableStateOf(true)
}
WordListScreen(
initSortMethod = SortMethod.NEW_TO_OLD
) {
}
val context = LocalContext.current
val successTip = stringResource(id = R.string.add_to_word_list_success)
if (showTranslateDialog)
TranslateDialog(
onDismissRequest = {
finish()
},
confirmButton = {
AddToWordListButton(onClick = {
showTranslateDialog = false
Toast.makeText(context, successTip, Toast.LENGTH_SHORT)
.show()
})
}
)
}
}
}
}
}
}
val LocalScrollAwareWindowInsets =
compositionLocalOf<WindowInsets> { error("No WindowInsets provided") } |
vipexam/app/src/main/java/app/xlei/vipexam/VipExamApplication.kt | 1066240076 | package app.xlei.vipexam
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class VipExamApplication : Application() {
} |
vipexam/feature/settings/src/androidTest/java/app/xlei/vipexam/feature/settings/ExampleInstrumentedTest.kt | 192857979 | package app.xlei.vipexam.feature.settings
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("app.xlei.vipexam.feature.settings.test", appContext.packageName)
}
} |
vipexam/feature/settings/src/test/java/app/xlei/vipexam/feature/settings/ExampleUnitTest.kt | 2705382971 | package app.xlei.vipexam.feature.settings
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/SettingsScreen.kt | 2013500069 | package app.xlei.vipexam.feature.settings
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.feature.settings.components.EudicApiKeyDialog
import app.xlei.vipexam.feature.settings.components.LanguagePreferenceDialog
import app.xlei.vipexam.feature.settings.components.LongPressActionDialog
import app.xlei.vipexam.feature.settings.components.OrganizationDialog
import app.xlei.vipexam.feature.settings.components.PreferenceItem
import app.xlei.vipexam.feature.settings.components.SettingsCategory
import app.xlei.vipexam.feature.settings.components.ShowAnswerDialog
import app.xlei.vipexam.feature.settings.components.SwitchPreference
import app.xlei.vipexam.feature.settings.components.ThemeModeDialog
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalVibrate
import app.xlei.vipexam.preference.VibratePreference
import compose.icons.FeatherIcons
import compose.icons.feathericons.Menu
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
openDrawer: () -> Unit,
modifier: Modifier = Modifier,
) {
var showLanguagePreference by remember {
mutableStateOf(false)
}
var showThemeOptions by remember {
mutableStateOf(false)
}
var showShowAnswerOptions by remember {
mutableStateOf(false)
}
var showLongPressActions by remember {
mutableStateOf(false)
}
var showOrganizationDialog by remember {
mutableStateOf(false)
}
var showEudicApiKeyDialog by remember {
mutableStateOf(false)
}
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
Scaffold(
modifier = modifier
.statusBarsPadding()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
LargeTopAppBar(
title = {
Text(
stringResource(R.string.settings)
)
},
navigationIcon = {
IconButton(
onClick = openDrawer
) {
Icon(
imageVector = FeatherIcons.Menu,
contentDescription = null,
)
}
},
scrollBehavior = scrollBehavior
)
}
) { paddingValues ->
LazyColumn(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize()
.padding(horizontal = 24.dp)
) {
item {
SettingsCategory(stringResource(R.string.general))
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.app_language),
summary = stringResource(id = R.string.app_language),
) {
showLanguagePreference = true
}
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(R.string.app_theme),
summary = stringResource(R.string.app_theme_summary)
) {
showThemeOptions = true
}
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(R.string.show_answer),
summary = stringResource(R.string.show_answer_summary)
) {
showShowAnswerOptions = true
}
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(R.string.long_press_action),
summary = stringResource(R.string.long_press_action)
) {
showLongPressActions = true
}
}
item {
SwitchPreference(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.vibrate),
summary = stringResource(id = R.string.vibrate_summary),
checked = LocalVibrate.current == VibratePreference.On,
preferencesKey = DataStoreKeys.Vibrate
)
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.organiztion),
summary = stringResource(id = R.string.edit_organiztion)
) {
showOrganizationDialog = true
}
}
item {
SettingsCategory(stringResource(R.string.advanced))
}
item {
PreferenceItem(
modifier = Modifier
.padding(top = 10.dp),
title = stringResource(id = R.string.eudic),
summary = stringResource(id = R.string.edit_eudic_apikey),
) {
showEudicApiKeyDialog = true
}
}
}
if (showLanguagePreference)
LanguagePreferenceDialog {
showLanguagePreference = false
}
if (showThemeOptions)
ThemeModeDialog {
showThemeOptions = false
}
if (showShowAnswerOptions) {
ShowAnswerDialog {
showShowAnswerOptions = false
}
}
if (showLongPressActions)
LongPressActionDialog {
showLongPressActions = false
}
if (showOrganizationDialog)
OrganizationDialog {
showOrganizationDialog = false
}
if (showEudicApiKeyDialog)
EudicApiKeyDialog {
showEudicApiKeyDialog = false
}
}
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/SettingsCategory.kt | 2499468459 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun SettingsCategory(
title: String
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
top = 20.dp,
bottom = 5.dp,
end = 5.dp
)
) {
Text(
text = title.uppercase(),
fontSize = 12.sp,
color = MaterialTheme.colorScheme.secondary
)
}
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ShowAnswerDialog.kt | 2228119022 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalShowAnswerOption
import app.xlei.vipexam.preference.ShowAnswerOptionPreference
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun ShowAnswerDialog(
onDismiss: () -> Unit
) {
val showAnswerOption = LocalShowAnswerOption.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.show_answer),
onDismissRequest = {
onDismiss.invoke()
},
options = listOf(
ListPreferenceOption(
name = stringResource(R.string.always),
value = ShowAnswerOptionPreference.Always.value,
isSelected = showAnswerOption == ShowAnswerOptionPreference.Always
),
ListPreferenceOption(
name = stringResource(R.string.once),
value = ShowAnswerOptionPreference.Once.value,
isSelected = showAnswerOption == ShowAnswerOptionPreference.Once
),
),
onOptionSelected = { option ->
context.dataStore.put(
DataStoreKeys.ShowAnswerOption,
option.value
)
}
)
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/DialogButton.kt | 3324673483 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun DialogButton(
modifier: Modifier = Modifier,
text: String,
onClick: () -> Unit
) {
TextButton(
modifier = modifier,
onClick = onClick
) {
Text(text)
}
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/SelectableItem.kt | 699148252 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
@Composable
fun SelectableItem(
text: String,
isSelected: Boolean = false,
onClick: () -> Unit = {}
) {
Card(
shape = RoundedCornerShape(30.dp),
modifier = Modifier
.fillMaxWidth()
.clip(
RoundedCornerShape(30.dp)
)
.clickable {
onClick.invoke()
},
colors = CardDefaults.cardColors(
containerColor = Color.Transparent
)
) {
Text(
text = text,
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
fontWeight = if (isSelected) FontWeight.ExtraBold else FontWeight.Normal,
color = MaterialTheme.colorScheme.onSurface,
)
}
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ThemeModeDialog.kt | 1037749974 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalThemeMode
import app.xlei.vipexam.preference.ThemeModePreference
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun ThemeModeDialog(
onDismiss: () -> Unit,
) {
val themeMode = LocalThemeMode.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.select_theme),
onDismissRequest = {
onDismiss.invoke()
},
options = listOf(
ListPreferenceOption(
name = stringResource(R.string.theme_auto),
value = ThemeModePreference.Auto.value,
isSelected = themeMode == ThemeModePreference.Auto
),
ListPreferenceOption(
name = stringResource(R.string.theme_light),
value = ThemeModePreference.Light.value,
isSelected = themeMode == ThemeModePreference.Light
),
ListPreferenceOption(
name = stringResource(R.string.theme_dark),
value = ThemeModePreference.Dark.value,
isSelected = themeMode == ThemeModePreference.Dark
),
ListPreferenceOption(
name = stringResource(R.string.theme_black),
value = ThemeModePreference.Black.value,
isSelected = themeMode == ThemeModePreference.Black
)
),
onOptionSelected = { option ->
context.dataStore.put(DataStoreKeys.ThemeMode, option.value)
}
)
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/PreferenceItem.kt | 1680554183 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun PreferenceItem(
title: String,
summary: String,
modifier: Modifier = Modifier,
onClick: () -> Unit = {}
) {
val interactionSource = remember { MutableInteractionSource() }
Row(
modifier = modifier
.fillMaxWidth()
.clickable(
interactionSource = interactionSource,
indication = null
) {
onClick.invoke()
}
) {
Column {
Text(title)
Spacer(Modifier.height(4.dp))
Text(
text = summary,
fontSize = 12.sp,
lineHeight = 18.sp
)
}
}
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/OrgnizationDialog.kt | 2543427119 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalOrganization
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import kotlinx.coroutines.launch
@Composable
fun OrganizationDialog(
onDismissRequest: () -> Unit,
) {
val coroutine = rememberCoroutineScope()
val context = LocalContext.current
val org = LocalOrganization.current
var organization by remember {
mutableStateOf(org.value)
}
AlertDialog(
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(onClick = {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.Organization,
organization
)
onDismissRequest.invoke()
}
}) {
Text(text = stringResource(id = R.string.okay))
}
},
title = {
Text(text = stringResource(id = R.string.edit_organiztion))
},
text = {
OutlinedTextField(
value = organization,
onValueChange = { organization = it },
shape = RoundedCornerShape(8.dp),
)
}
)
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/LanaguagePreferenceDialog.kt | 3051392793 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LanguagePreference
import app.xlei.vipexam.preference.LocalLanguage
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun LanguagePreferenceDialog(
onDismiss: () -> Unit
) {
val language = LocalLanguage.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.app_language),
onDismissRequest = {
onDismiss.invoke()
},
options = LanguagePreference.values.map {
ListPreferenceOption(
name = it.toDesc(),
value = it.value,
isSelected = it == language
)
},
onOptionSelected = { option ->
LanguagePreference.values.first {
it.value == option.value
}.apply {
context.dataStore.put(
DataStoreKeys.Language,
option.value
)
LanguagePreference.setLocale(this@apply)
}
}
)
}
|
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/LongPressActionDialog.kt | 3347538931 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalLongPressAction
import app.xlei.vipexam.preference.LongPressAction
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
@Composable
fun LongPressActionDialog(
onDismiss: () -> Unit
) {
val longPressAction = LocalLongPressAction.current
val context = LocalContext.current
ListPreferenceDialog(
title = stringResource(R.string.long_press_action),
onDismissRequest = {
onDismiss.invoke()
},
options = listOf(
ListPreferenceOption(
name = stringResource(R.string.show_question),
value = LongPressAction.ShowQuestion.value,
isSelected = longPressAction.isShowQuestion()
),
ListPreferenceOption(
name = stringResource(R.string.show_translation),
value = LongPressAction.ShowTranslation.value,
isSelected = longPressAction.isShowTranslation()
),
ListPreferenceOption(
name = stringResource(R.string.none),
value = LongPressAction.None.value,
isSelected = longPressAction == LongPressAction.None
),
),
onOptionSelected = { option ->
context.dataStore.put(
DataStoreKeys.LongPressAction,
option.value
)
}
)
}
|
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ListPreferenceDialog.kt | 2970079373 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.settings.R
import kotlinx.coroutines.launch
@Composable
fun ListPreferenceDialog(
onDismissRequest: () -> Unit,
options: List<ListPreferenceOption>,
currentValue: Int? = null,
title: String? = null,
onOptionSelected: suspend (ListPreferenceOption) -> Unit = {}
) {
val coroutine = rememberCoroutineScope()
AlertDialog(
onDismissRequest = onDismissRequest,
title = {
if (title != null)
Text(title)
},
text = {
LazyColumn {
items(options) {
SelectableItem(
text = if (it.value == currentValue) "${it.name} ✓" else it.name,
onClick = {
coroutine.launch {
onOptionSelected.invoke(it).apply {
onDismissRequest.invoke()
}
}
},
isSelected = it.isSelected
)
}
}
},
confirmButton = {
TextButton(
onClick = {
onDismissRequest.invoke()
}
) {
Text(
stringResource(
R.string.cancel
)
)
}
},
)
}
data class ListPreferenceOption(
val name: String,
val value: Int,
val isSelected: Boolean = false
) |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/EudicApiKeyDialog.kt | 3860398372 | package app.xlei.vipexam.feature.settings.components
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import app.xlei.vipexam.core.network.module.EudicRemoteDatasource
import app.xlei.vipexam.feature.settings.R
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.LocalEudicApiKey
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import compose.icons.FeatherIcons
import compose.icons.feathericons.Check
import compose.icons.feathericons.CheckCircle
import compose.icons.feathericons.X
import kotlinx.coroutines.launch
@Composable
fun EudicApiKeyDialog(
onDismissRequest: () -> Unit,
) {
val coroutine = rememberCoroutineScope()
val context = LocalContext.current
val apiKey = LocalEudicApiKey.current
var eudicApiKey by remember {
mutableStateOf(apiKey.value)
}
var available by remember {
mutableStateOf(false to false)
}
AlertDialog(
onDismissRequest = onDismissRequest,
confirmButton = {
TextButton(onClick = {
coroutine.launch {
context.dataStore.put(
DataStoreKeys.EudicApiKey,
eudicApiKey
)
onDismissRequest.invoke()
}
}) {
Text(text = stringResource(id = R.string.okay))
}
},
title = {
Text(text = stringResource(id = R.string.edit_eudic_apikey))
},
text = {
Column {
OutlinedTextField(
value = eudicApiKey,
onValueChange = { eudicApiKey = it },
shape = RoundedCornerShape(8.dp),
)
Row(
modifier = Modifier.padding(top = 4.dp)
) {
Icon(imageVector = Icons.Default.Info, contentDescription = null)
Text(
text = stringResource(id = R.string.get_your_eudic_apikey),
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.clickable {
val intent = Intent(
Intent.ACTION_VIEW,
"https://my.eudic.net/OpenAPI/Authorization".toUri()
)
val packageManager = context.packageManager
context.startActivity(
intent.setPackage(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.resolveActivity(
intent,
PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong())
)
} else {
packageManager.resolveActivity(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
}!!.activityInfo.packageName
)
)
}
.padding(start = 4.dp)
)
}
Row(
modifier = Modifier.padding(top = 4.dp)
) {
Icon(imageVector = FeatherIcons.CheckCircle, contentDescription = null)
Text(
text = stringResource(id = R.string.check_availability),
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.clickable {
coroutine.launch {
EudicRemoteDatasource.api = eudicApiKey
EudicRemoteDatasource
.check()
.onSuccess {
available = true to true
}
.onFailure {
available = true to false
}
}
}
.padding(start = 4.dp)
)
if (available.first)
when (available.second) {
true -> {
Icon(imageVector = FeatherIcons.Check, contentDescription = null)
}
false -> {
Icon(imageVector = FeatherIcons.X, contentDescription = null)
}
}
}
}
}
)
}
|
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/ListPreference.kt | 2444631351 | package app.xlei.vipexam.feature.settings.components
|
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/StyledIconButton.kt | 782613053 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
@Composable
fun StyledIconButton(
modifier: Modifier = Modifier,
imageVector: ImageVector,
contentDescription: String? = null,
onClick: () -> Unit = {}
) {
IconButton(
onClick = {
onClick.invoke()
}
) {
Icon(
modifier = modifier,
imageVector = imageVector,
contentDescription = contentDescription
)
}
} |
vipexam/feature/settings/src/main/java/app/xlei/vipexam/feature/settings/components/SwitchPreference.kt | 1205091200 | package app.xlei.vipexam.feature.settings.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.xlei.vipexam.preference.DataStoreKeys
import app.xlei.vipexam.preference.dataStore
import app.xlei.vipexam.preference.put
import kotlinx.coroutines.launch
@Composable
fun SwitchPreference(
title: String,
summary: String,
checked: Boolean,
preferencesKey: DataStoreKeys<Boolean>,
modifier: Modifier = Modifier,
) {
val interactionSource = remember { MutableInteractionSource() }
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
Row(
modifier = modifier
.fillMaxWidth()
.clickable(
interactionSource = interactionSource,
indication = null
) {
coroutine.launch {
context.dataStore.put(
preferencesKey,
!checked
)
}
},
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text(title)
Spacer(Modifier.height(4.dp))
Text(
text = summary,
fontSize = 12.sp,
lineHeight = 18.sp
)
}
Spacer(modifier = Modifier.weight(1f))
Column {
Switch(
checked = checked,
onCheckedChange = {
coroutine.launch {
context.dataStore.put(
preferencesKey,
!checked
)
}
},
colors = SwitchDefaults.colors(
checkedThumbColor = MaterialTheme.colorScheme.surfaceColorAtElevation(10.dp)
)
)
}
}
} |
vipexam/feature/wordlist/src/androidTest/java/app/xlei/vipexam/feature/wordlist/ExampleInstrumentedTest.kt | 746190434 | package app.xlei.vipexam.feature.wordlist
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("app.xlei.vipexam.feature.wordlist.test", appContext.packageName)
}
} |
vipexam/feature/wordlist/src/test/java/app/xlei/vipexam/feature/wordlist/ExampleUnitTest.kt | 2592941980 | package app.xlei.vipexam.feature.wordlist
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/WordListViewModel.kt | 849720985 | package app.xlei.vipexam.feature.wordlist
import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
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.EudicRemoteDatasource
import app.xlei.vipexam.feature.wordlist.constant.SortMethod
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVPrinter
import java.io.File
import java.io.PrintWriter
import javax.inject.Inject
@HiltViewModel
class WordListViewModel @Inject constructor(
private val repository: Repository<Word>,
) : ViewModel() {
private val _wordList = MutableStateFlow(emptyList<Word>())
private val _syncState = MutableStateFlow<SyncState<Nothing>>(SyncState.Default)
val wordList
get() = _wordList.asStateFlow()
val syncState
get() = _syncState.asStateFlow()
var sortMethod = MutableStateFlow(SortMethod.OLD_TO_NEW)
init {
getWordList()
}
private fun getWordList() {
viewModelScope.launch {
repository.getAll()
.flowOn(Dispatchers.IO)
.collect { wordList: List<Word> ->
_wordList.update {
wordList
}
}
}
}
fun addWord(word: Word) {
viewModelScope.launch(Dispatchers.IO) {
repository.add(word)
}
}
fun removeWord(word: Word) {
viewModelScope.launch(Dispatchers.IO) {
repository.remove(word)
}
}
fun setSortMethod(sortMethod: SortMethod) {
this.sortMethod.value = sortMethod
viewModelScope.launch {
repository.getAll()
.flowOn(Dispatchers.IO)
.map { words ->
when (sortMethod) {
SortMethod.OLD_TO_NEW -> words.sortedBy { it.created }
SortMethod.NEW_TO_OLD -> words.sortedByDescending { it.created }
SortMethod.A_TO_Z -> words.sortedBy { it.word }
SortMethod.Z_TO_A -> words.sortedByDescending { it.word }
}
}
.collect { sortedWordList: List<Word> ->
_wordList.update {
sortedWordList
}
}
}
}
fun exportWordsToCSV(context: Context) {
viewModelScope.launch(Dispatchers.IO) {
val words = repository.getAll().first()
val csvFile = File(context.cacheDir, "words-${System.currentTimeMillis()}.csv")
CSVPrinter(
PrintWriter(csvFile),
CSVFormat.DEFAULT.withHeader("id", "word", "created")
).use { printer ->
words.forEach { word ->
printer.printRecord(word.id, word.word, word.created)
}
}
withContext(Dispatchers.Main) {
shareCSVFile(context, csvFile)
}
}
}
private fun shareCSVFile(context: Context, file: File) {
val contentUri =
FileProvider.getUriForFile(context, "${context.packageName}.provider", file)
val shareIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, contentUri)
type = "text/csv"
}
context.startActivity(Intent.createChooser(shareIntent, "Save file..."))
}
fun syncToEudic(apiKey: String) {
apiKey.takeIf { it != "" }?.let {
_syncState.update {
SyncState.Syncing
}
viewModelScope.launch {
EudicRemoteDatasource.api = it
if (EudicRemoteDatasource.sync(_wordList.value.map { it.word }))
_syncState.update { SyncState.Success }
else _syncState.update { SyncState.Error }
}
}
}
fun resetSyncState() {
_syncState.update {
SyncState.Default
}
}
}
sealed class SyncState<out T> {
data object Default : SyncState<Nothing>()
data object Success : SyncState<Nothing>()
data object Syncing : SyncState<Nothing>()
data object Error : SyncState<Nothing>()
} |
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/WordListScreen.kt | 3452517232 | package app.xlei.vipexam.feature.wordlist
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AssistChip
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.ui.DateText
import app.xlei.vipexam.feature.wordlist.components.CopyToClipboardButton
import app.xlei.vipexam.feature.wordlist.components.TranslationSheet
import app.xlei.vipexam.feature.wordlist.constant.SortMethod
import app.xlei.vipexam.preference.EudicApiKey
import app.xlei.vipexam.preference.LocalEudicApiKey
import compose.icons.FeatherIcons
import compose.icons.feathericons.Check
import compose.icons.feathericons.Menu
import compose.icons.feathericons.RefreshCcw
import compose.icons.feathericons.RefreshCw
import compose.icons.feathericons.X
import kotlinx.coroutines.delay
@OptIn(
ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class,
)
@Composable
fun WordListScreen(
modifier: Modifier = Modifier,
initSortMethod: SortMethod = SortMethod.OLD_TO_NEW,
viewModel: WordListViewModel = hiltViewModel(),
openDrawer: () -> Unit,
) {
val wordListState by viewModel.wordList.collectAsState()
val syncState by viewModel.syncState.collectAsState()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
var textToTranslate by remember { mutableStateOf("") }
var showTranslationSheet by remember { mutableStateOf(false) }
var showSortMethods by rememberSaveable {
mutableStateOf(false)
}
LaunchedEffect(Unit) {
viewModel.setSortMethod(initSortMethod)
}
val sortMethod = viewModel.sortMethod.collectAsState()
val context = LocalContext.current
val eudicApiKey = LocalEudicApiKey.current
LaunchedEffect(syncState) {
if (syncState == SyncState.Success || syncState == SyncState.Error) {
delay(2000)
viewModel.resetSyncState()
}
}
Scaffold(
topBar = {
LargeTopAppBar(
actions = {
IconButton(
onClick = { viewModel.syncToEudic(eudicApiKey.value) },
enabled = eudicApiKey is EudicApiKey.Some
) {
when (syncState) {
SyncState.Default -> {
Icon(
imageVector = FeatherIcons.RefreshCw,
contentDescription = null
)
}
SyncState.Error -> {
Icon(imageVector = FeatherIcons.X, contentDescription = null)
}
SyncState.Success -> {
Icon(imageVector = FeatherIcons.Check, contentDescription = null)
}
SyncState.Syncing -> {
Icon(
imageVector = FeatherIcons.RefreshCcw,
contentDescription = null
)
}
}
}
IconButton(onClick = { viewModel.exportWordsToCSV(context) }) {
Icon(imageVector = Icons.Default.Share, contentDescription = null)
}
},
title = {
Text(
stringResource(R.string.words)
)
},
navigationIcon = {
IconButton(
onClick = openDrawer
) {
Icon(
imageVector = FeatherIcons.Menu,
contentDescription = null,
)
}
},
scrollBehavior = scrollBehavior
)
},
modifier = modifier
.background(MaterialTheme.colorScheme.background)
.statusBarsPadding()
.nestedScroll(scrollBehavior.nestedScrollConnection),
) { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
) {
LazyColumn {
stickyHeader {
Column(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.background)
) {
LazyRow {
item {
AssistChip(
onClick = { showSortMethods = !showSortMethods },
label = { Text(text = stringResource(id = R.string.sort)) },
trailingIcon = {
Icon(
imageVector = if (showSortMethods) {
Icons.Default.KeyboardArrowUp
} else {
Icons.Default.KeyboardArrowDown
},
contentDescription = null,
)
},
modifier = Modifier
.padding(horizontal = 8.dp)
)
}
}
LazyRow {
if (showSortMethods)
SortMethod.entries.forEach {
item {
FilterChip(
onClick = {
viewModel.setSortMethod(it)
},
label = { Text(text = stringResource(id = it.method)) },
selected = it == sortMethod.value,
modifier = Modifier
.padding(horizontal = 8.dp)
)
}
}
}
}
}
items(wordListState.size) { index ->
ListItem(
headlineContent = { Text(wordListState[index].word) },
supportingContent = { DateText(wordListState[index].created) },
trailingContent = { CopyToClipboardButton(text = wordListState[index].word) },
modifier = Modifier
.combinedClickable(
onClick = {
textToTranslate = wordListState[index].word
showTranslationSheet = true
},
onLongClick = { viewModel.removeWord(wordListState[index]) }
)
)
}
item {
if (wordListState.isEmpty())
Text(
text = stringResource(R.string.empty_wordlist_tips),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxSize()
)
}
}
if (showTranslationSheet)
TranslationSheet(
textToTranslate
) {
showTranslationSheet = !showTranslationSheet
}
}
}
}
|
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/components/viewmodel/TranslationSheetViewModel.kt | 423331269 | package app.xlei.vipexam.feature.wordlist.components.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import app.xlei.vipexam.core.data.paging.MomoLookUpApi
import app.xlei.vipexam.core.data.paging.MomoLookUpRepository
import app.xlei.vipexam.core.network.module.momoLookUp.Phrase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class TranslationSheetViewModel @Inject constructor(
private val momoLookUpRepository: MomoLookUpRepository
) : ViewModel() {
private val _phrases: MutableStateFlow<PagingData<Phrase>> =
MutableStateFlow(PagingData.empty())
val phrases = _phrases
private var searchJob: Job? = null
suspend fun search(keyword: String) {
MomoLookUpApi.keyword = keyword
searchJob?.cancel()
searchJob = viewModelScope.launch {
momoLookUpRepository.search().distinctUntilChanged()
.cachedIn(viewModelScope)
.collect {
_phrases.value = it
}
}
}
fun clean() {
searchJob?.cancel()
_phrases.value = PagingData.empty()
}
suspend fun refresh(keyword: String) = search(keyword)
} |
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/components/TranslationSheet.kt | 4277944015 | package app.xlei.vipexam.feature.wordlist.components
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
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.LazyRow
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
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.LocalContext
import androidx.compose.ui.platform.LocalTextToolbar
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.collectAsLazyPagingItems
import app.xlei.vipexam.core.data.paging.MomoLookUpApi
import app.xlei.vipexam.core.data.paging.Source
import app.xlei.vipexam.core.network.module.NetWorkRepository
import app.xlei.vipexam.core.ui.EmptyTextToolbar
import app.xlei.vipexam.core.ui.TranslateDialog
import app.xlei.vipexam.feature.wordlist.components.viewmodel.TranslationSheetViewModel
import compose.icons.FeatherIcons
import compose.icons.feathericons.Loader
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun TranslationSheet(
text: String,
viewModel: TranslationSheetViewModel = hiltViewModel(),
toggleBottomSheet: () -> Unit,
) {
val phrases = viewModel.phrases.collectAsLazyPagingItems()
var translation by remember {
mutableStateOf(
app.xlei.vipexam.core.network.module.TranslationResponse(
code = 200,
id = "",
data = "",
emptyList()
)
)
}
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
var showTranslationDialog by remember {
mutableStateOf(false)
}
var selectedSource by remember {
mutableStateOf(Source.ALL)
}
DisposableEffect(Unit) {
coroutine.launch {
val res = NetWorkRepository.translateToZH(text)
res.onSuccess {
translation = it
}
res.onFailure {
toggleBottomSheet()
Toast.makeText(context, it.toString(), Toast.LENGTH_SHORT).show()
}
viewModel.search(text)
}
onDispose { viewModel.clean() }
}
ModalBottomSheet(
onDismissRequest = toggleBottomSheet,
) {
Column(
modifier = Modifier
.run {
if (phrases.itemCount == 0)
this.padding(bottom = 120.dp)
else
this
}
) {
Column(
modifier = Modifier
.padding(horizontal = 24.dp)
) {
Text(
text = text,
fontWeight = FontWeight.Bold,
)
HorizontalDivider()
Text(
text = translation.data,
fontSize = 24.sp,
)
LazyRow {
if (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)
)
}
}
}
}
AnimatedVisibility(visible = phrases.itemCount > 0) {
FlowRow(
modifier = Modifier.padding(4.dp)
) {
Source.entries.forEach {
FilterChip(
selected = selectedSource == it,
onClick = {
selectedSource = it
MomoLookUpApi.source = it
coroutine.launch {
viewModel.refresh(text)
}
},
label = { Text(text = it.displayName) },
modifier = Modifier.padding(start = 4.dp)
)
}
}
}
LazyColumn {
items(phrases.itemCount) {
CompositionLocalProvider(
value = LocalTextToolbar provides EmptyTextToolbar {
showTranslationDialog = true
}
) {
SelectionContainer {
phrases[it]?.let { phrase ->
ListItem(
headlineContent = {
Text(
text = "${it + 1}. ${
phrase.context.phrase.removeSuffix(
"//"
)
}"
)
},
supportingContent = {
Column {
Text(
text = phrase.context.options.joinToString(
separator = "\n"
) { option ->
option.option + ". " + option.phrase
})
Text(text = phrase.source)
}
}
)
}
}
}
}
}
}
if (showTranslationDialog)
TranslateDialog(
onDismissRequest = { showTranslationDialog = false },
dismissButton = {}
)
}
}
|
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/components/CopyToClipBoardButton.kt | 1384371937 | package app.xlei.vipexam.feature.wordlist.components
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.widget.Toast
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.xlei.vipexam.feature.wordlist.R
import compose.icons.FeatherIcons
import compose.icons.feathericons.Clipboard
@Composable
fun CopyToClipboardButton(
modifier: Modifier = Modifier,
text: String,
) {
val context = LocalContext.current
val string = stringResource(R.string.CopyToClipboardSuccess)
fun copyToClipboard(word: String) {
context.copyToClipboard(word)
}
IconButton(
onClick = {
copyToClipboard(text)
Toast.makeText(context, "$text $string", Toast.LENGTH_LONG).show()
},
modifier = modifier,
) {
Icon(
imageVector = FeatherIcons.Clipboard,
contentDescription = null,
)
}
}
@SuppressLint("ServiceCast")
fun Context.copyToClipboard(text: CharSequence) {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("label", text)
clipboard.setPrimaryClip(clip)
} |
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/constant/SortMethod.kt | 1903604796 | package app.xlei.vipexam.feature.wordlist.constant
import app.xlei.vipexam.feature.wordlist.R
enum class SortMethod(val method: Int) {
OLD_TO_NEW(R.string.sort_by_old_to_new),
NEW_TO_OLD(R.string.sort_by_new_to_old),
A_TO_Z(R.string.sort_by_a_z),
Z_TO_A(R.string.sort_by_z_a),
} |
vipexam/feature/bookmarks/src/androidTest/java/app/xlei/vipexam/feature/bookmarks/ExampleInstrumentedTest.kt | 1652261363 | package app.xlei.vipexam.feature.bookmarks
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("app.xlei.vipexam.feature.bookmarks.test", appContext.packageName)
}
} |
vipexam/feature/bookmarks/src/test/java/app/xlei/vipexam/feature/bookmarks/ExampleUnitTest.kt | 2285093559 | package app.xlei.vipexam.feature.bookmarks
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
vipexam/feature/bookmarks/src/main/java/app/xlei/vipexam/feature/bookmarks/BookmarksViewModel.kt | 3736653888 | package app.xlei.vipexam.feature.bookmarks
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.xlei.vipexam.core.data.repository.BookmarkRepository
import app.xlei.vipexam.core.database.module.Bookmark
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class BookmarksViewModel @Inject constructor(
private val bookmarkRepository: BookmarkRepository
) : ViewModel() {
private val _bookmarks = MutableStateFlow(emptyList<Bookmark>())
val bookmarks = _bookmarks.asStateFlow()
private var _filter = MutableStateFlow("")
val filter = _filter.asStateFlow()
init {
getBookmarks()
}
private fun getBookmarks() {
viewModelScope.launch {
bookmarkRepository
.getAllBookmarks()
.flowOn(Dispatchers.IO)
.collect { bookmark: List<Bookmark> ->
_bookmarks.update {
if (_filter.value == "")
bookmark
else
bookmark.filter {
it.question == _filter.value
}
}
}
}
}
fun setFilter(question: String? = null) {
_filter.update {
question ?: ""
}
getBookmarks()
}
fun delete(index: Int) {
viewModelScope.launch(Dispatchers.IO) {
bookmarkRepository.deleteBookmark(
_bookmarks.value[index]
)
}
}
} |
vipexam/feature/bookmarks/src/main/java/app/xlei/vipexam/feature/bookmarks/BookmarksScreen.kt | 26919229 | package app.xlei.vipexam.feature.bookmarks
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.AssistChip
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.ui.DateText
import app.xlei.vipexam.core.ui.LoginAlert
import compose.icons.FeatherIcons
import compose.icons.feathericons.Menu
@OptIn(
ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class,
)
@Composable
fun BookmarksScreen(
modifier: Modifier = Modifier,
viewModel: BookmarksViewModel = hiltViewModel(),
openDrawer: () -> Unit,
onBookmarkClick: (String,String) -> Boolean,
) {
val bookmarksState by viewModel.bookmarks.collectAsState()
val filter by viewModel.filter.collectAsState()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
var showFilter by rememberSaveable {
mutableStateOf(false)
}
var showLoginAlert by remember {
mutableStateOf(false)
}
val questions = bookmarksState.map { it.question }.toSet()
Scaffold(
topBar = {
LargeTopAppBar(
title = {
Text(
stringResource(R.string.bookmarks)
)
},
navigationIcon = {
IconButton(
onClick = openDrawer
) {
Icon(
imageVector = FeatherIcons.Menu,
contentDescription = null,
)
}
},
scrollBehavior = scrollBehavior
)
},
modifier = Modifier
.background(MaterialTheme.colorScheme.background)
.statusBarsPadding()
.nestedScroll(scrollBehavior.nestedScrollConnection),
) { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
) {
LazyColumn {
stickyHeader {
Column(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.background)
) {
LazyRow {
item {
AssistChip(
onClick = { showFilter = !showFilter },
label = { Text(text = stringResource(id = R.string.question)) },
trailingIcon = {
Icon(
imageVector = if (showFilter) {
Icons.Default.KeyboardArrowUp
} else {
Icons.Default.KeyboardArrowDown
},
contentDescription = null,
)
},
modifier = Modifier
.padding(horizontal = 8.dp)
)
}
}
LazyRow {
if (showFilter)
questions.forEach {
item {
FilterChip(
onClick = {
when (filter) {
it -> viewModel.setFilter()
else -> viewModel.setFilter(it)
}
},
label = { Text(text = it) },
selected = it == filter,
modifier = Modifier
.padding(horizontal = 8.dp)
)
}
}
}
}
}
items(bookmarksState.size) { index ->
ListItem(
headlineContent = { Text(bookmarksState[index].question) },
supportingContent = {
Text(
text = bookmarksState[index].examName,
style = MaterialTheme.typography.bodySmall,
) },
trailingContent = { DateText(bookmarksState[index].created) },
modifier = Modifier
.combinedClickable(
onClick = {
showLoginAlert = onBookmarkClick
.invoke(
bookmarksState[index].examId,
bookmarksState[index].question
).not()
},
onLongClick = {
viewModel.delete(index)
}
)
)
}
item {
if (bookmarksState.isEmpty())
Text(
text = stringResource(R.string.empty_bookmarks_tips),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxSize()
)
}
}
if (showLoginAlert) LoginAlert {
showLoginAlert = false
}
}
}
} |
vipexam/feature/history/src/androidTest/java/app/xlei/vipexam/feature/history/ExampleInstrumentedTest.kt | 2012098225 | package app.xlei.vipexam.feature.history
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("app.xlei.vipexam.feature.history.test", appContext.packageName)
}
} |
vipexam/feature/history/src/test/java/app/xlei/vipexam/feature/history/ExampleUnitTest.kt | 1693953276 | package app.xlei.vipexam.feature.history
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
vipexam/feature/history/src/main/java/app/xlei/vipexam/feature/history/HistoryScreen.kt | 657954324 | package app.xlei.vipexam.feature.history
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.hilt.navigation.compose.hiltViewModel
import app.xlei.vipexam.core.ui.DateText
import app.xlei.vipexam.core.ui.LoginAlert
import compose.icons.FeatherIcons
import compose.icons.feathericons.Menu
import compose.icons.feathericons.Trash2
@OptIn(
ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class,
)
@Composable
fun HistoryScreen(
modifier: Modifier = Modifier,
viewModel: HistoryViewModel = hiltViewModel(),
openDrawer: () -> Unit,
onHistoryClick: (String) -> Boolean,
) {
val examHistoryState by viewModel.examHistory.collectAsState()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
rememberTopAppBarState()
)
var showLoginAlert by remember {
mutableStateOf(false)
}
Scaffold(
topBar = {
LargeTopAppBar(
title = {
Text(
stringResource(R.string.history)
)
},
navigationIcon = {
IconButton(
onClick = openDrawer
) {
Icon(
imageVector = FeatherIcons.Menu,
contentDescription = null,
)
}
},
actions = {
IconButton(
onClick = { viewModel.cleanHistory() },
enabled = examHistoryState.isNotEmpty()
) {
Icon(imageVector = FeatherIcons.Trash2, contentDescription = null)
}
},
scrollBehavior = scrollBehavior
)
},
modifier = Modifier
.background(MaterialTheme.colorScheme.background)
.statusBarsPadding()
.nestedScroll(scrollBehavior.nestedScrollConnection),
) { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
) {
LazyColumn {
items(examHistoryState.size) { index ->
ListItem(
headlineContent = { Text(examHistoryState[index].examName) },
supportingContent = { DateText(examHistoryState[index].lastOpen) },
modifier = Modifier
.combinedClickable(
onClick = {
showLoginAlert =
onHistoryClick.invoke(examHistoryState[index].examId).not()
},
onLongClick = {
viewModel.delete(index)
}
)
)
}
item {
if (examHistoryState.isEmpty())
Text(
text = stringResource(R.string.empty_history_tips),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxSize()
)
}
}
if (showLoginAlert) LoginAlert {
showLoginAlert = false
}
}
}
} |
vipexam/feature/history/src/main/java/app/xlei/vipexam/feature/history/HistoryViewModel.kt | 1118662323 | package app.xlei.vipexam.feature.history
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.xlei.vipexam.core.data.repository.ExamHistoryRepository
import app.xlei.vipexam.core.database.module.ExamHistory
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HistoryViewModel @Inject constructor(
private val examHistoryRepository: ExamHistoryRepository
) : ViewModel() {
private val _examHistory = MutableStateFlow(emptyList<ExamHistory>())
val examHistory = _examHistory.asStateFlow()
init {
getExamHistory()
}
private fun getExamHistory() {
viewModelScope.launch {
examHistoryRepository
.getAllExamHistory()
.flowOn(Dispatchers.IO)
.collect { examHistory: List<ExamHistory> ->
_examHistory.update {
examHistory
}
}
}
}
fun cleanHistory() {
viewModelScope.launch(Dispatchers.IO) {
examHistoryRepository
.removeAllHistory()
}
}
fun delete(index: Int) {
viewModelScope.launch(Dispatchers.IO) {
examHistoryRepository
.removeHistory(_examHistory.value[index])
}
}
} |
sea-battle/app/src/androidTest/java/com/project/seaBattle/ExampleInstrumentedTest.kt | 835518946 | package com.project.seaBattle
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.project.seaBattle", appContext.packageName)
}
} |
sea-battle/app/src/test/java/com/project/seaBattle/ExampleUnitTest.kt | 3711427116 | package com.project.seaBattle
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)
}
} |
sea-battle/app/src/main/java/com/project/seaBattle/utils/showToast.kt | 1651745712 | package com.project.seaBattle.utils
import android.content.Context
import android.widget.Toast
fun showToast(
message: String,
context: Context,
) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
|
sea-battle/app/src/main/java/com/project/seaBattle/utils/setupOnBackPressedCallback.kt | 2489669220 | package com.project.seaBattle.utils
import androidx.activity.OnBackPressedDispatcherOwner
import androidx.activity.addCallback
fun OnBackPressedDispatcherOwner.setupOnBackPressedCallback(onBackPressedAction: () -> Unit) {
onBackPressedDispatcher.addCallback(this) {
onBackPressedAction.invoke()
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/battle/BattleEditor.kt | 2642921899 | package com.project.seaBattle.logics.battle
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.project.seaBattle.R
import com.project.seaBattle.logics.board.BoardSide
import com.project.seaBattle.logics.board.Cell
import com.project.seaBattle.logics.board.GameBoard
import com.project.seaBattle.logics.ship.Ship
class BattleEditor(context: Context, attrs: AttributeSet?) : View(context, attrs) {
var leftShips: MutableList<Ship>? = null
var rightShips: MutableList<Ship>? = null
private var rightBoard: GameBoard? = null
private var leftBoard: GameBoard? = null
private var currentGameBoard: GameBoard? = null
private var currentShipsForCheck: MutableList<Ship>? = null
private var lastDamagedShip: Ship? = null
private var currentPlayerBitmap: Bitmap? = null
private var currentPlayerImgRect: Rect? = null
private var onGameOver: ((loser: BoardSide) -> Unit)? = null
private val pressedCells: MutableList<Cell> = mutableListOf()
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
for (cell in pressedCells) {
cell.drawClick(canvas)
}
currentPlayerBitmap?.let {
currentPlayerImgRect?.let { rect ->
canvas.drawBitmap(it, null, rect, null)
}
}
}
fun setLeftBoard(board: GameBoard) {
leftBoard = board
}
fun setRightBoard(board: GameBoard) {
rightBoard = board
currentGameBoard = rightBoard
currentShipsForCheck = rightShips
initializeCurrentPlayerImg()
}
private fun initializeCurrentPlayerImg() {
currentPlayerBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.right_plays)
currentGameBoard?.setBoardLimits(context)
val cellSize = currentGameBoard?.cellSize
val rightForRect = (rightBoard?.leftLimit!! - cellSize!!).toInt()
val topForRect = ((currentGameBoard?.bottomLimit!! / 2) - (currentGameBoard?.topLimit!! / 2)).toInt()
val leftForRect = rightForRect.minus(cellSize)
val bottomForRect = topForRect.plus(2 * cellSize)
currentPlayerImgRect = Rect(leftForRect, topForRect, rightForRect, bottomForRect)
}
private fun setCurrentBoard() {
if (currentGameBoard == rightBoard) {
currentGameBoard = leftBoard
currentShipsForCheck = leftShips
currentPlayerBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.left_plays)
} else {
currentGameBoard = rightBoard
currentShipsForCheck = rightShips
currentPlayerBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.right_plays)
}
}
private fun checkHits(imgRect: Rect): Boolean {
for (ship in currentShipsForCheck!!) {
if (ship.checkHits(imgRect)) {
lastDamagedShip = ship
return true
}
}
return false
}
private fun getCellImageRect(
x: Float,
y: Float,
): Rect {
return Rect(
x.toInt(),
y.toInt(),
(x + currentGameBoard!!.cellSize).toInt(),
(y + currentGameBoard!!.cellSize).toInt(),
)
}
private fun addSurroundingCell(newCell: Cell) {
val hasCellWithSameImgRect = pressedCells.any { it.imageRect.intersect(newCell.imageRect) }
if (!hasCellWithSameImgRect) {
pressedCells.add(newCell)
}
}
private fun determineTheLoser() {
currentGameBoard?.let { onGameOver?.invoke(it.side) }
}
fun setOnGameOver(listener: (winner: BoardSide) -> Unit) {
onGameOver = listener
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> handleActionDown(event.x, event.y)
}
return true
}
private fun handleActionDown(
x: Float,
y: Float,
) {
if (currentGameBoard!!.checkPressureWithinBoard(x, y)) {
val xCord = currentGameBoard!!.getXCellCordForShip(x)
val yCord = currentGameBoard!!.getYCellCordForShip(y)
val cellImageRect = getCellImageRect(xCord!!, yCord!!)
processCellClick(cellImageRect)
}
}
private fun processCellClick(cellImageRect: Rect) {
val isCellPressed = pressedCells.any { it.imageRect.intersect(cellImageRect) }
if (!isCellPressed) {
val isHit = checkHits(cellImageRect)
pressedCells.add(Cell(cellImageRect, isHit, context))
if (isHit) {
handleHit()
} else {
setCurrentBoard()
}
invalidate()
}
}
private fun handleHit() {
if (lastDamagedShip!!.checkDestruction()) {
handleShipDestruction()
}
}
private fun handleShipDestruction() {
val surroundingCells = lastDamagedShip!!.getSurroundingCells()
for (surroundingCellImageRect in surroundingCells) {
if (currentGameBoard!!.checkImgRectWithinBoard(surroundingCellImageRect)) {
addSurroundingCell(Cell(surroundingCellImageRect, false, context))
}
}
currentShipsForCheck?.remove(lastDamagedShip!!)
val shipsList = if (currentGameBoard == rightBoard) rightShips else leftShips
shipsList?.remove(lastDamagedShip!!)
if (rightShips?.isEmpty() == true || leftShips?.isEmpty() == true) {
determineTheLoser()
}
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/GameBoard.kt | 127135960 | package com.project.seaBattle.logics.board
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import com.project.seaBattle.R
import com.project.seaBattle.logics.ship.ShipOrientation
class GameBoard(val side: BoardSide) {
var leftLimit: Float = 0.0f
var topLimit: Float = 0.0f
var cellSize: Int = 0
var bottomLimit: Float = 0.0f
var startXForPlacementShips: Int? = 0
private var rightLimit: Float = 0.0f
private var screenHeight: Float? = 0f
private var lettersBitmap: Bitmap? = null
private var numbersBitmap: Bitmap? = null
private var lettersImgRect: Rect? = null
private var numbersImgRect: Rect? = null
private val verticalLines = mutableListOf<Float>()
private val horizontalLines = mutableListOf<Float>()
private val cellsNumberInRow: Int = 10
fun setBoardLimits(context: Context) {
val displayMetrics = context.resources.displayMetrics
val screenWidth = displayMetrics.widthPixels.toFloat()
val centerInWidth = screenWidth / 2
screenHeight = displayMetrics.heightPixels.toFloat()
val boardSize = calculateBoardSize(screenHeight!!)
lettersBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.letters)
numbersBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.numbers)
setLimitsAndStartX(centerInWidth, boardSize, screenWidth)
cellSize = calculateCellSize()
setImgRectForImages()
createLinesForBoard()
}
private fun calculateBoardSize(screenHeight: Float): Float {
val indentFromTopPercentage = 0.1f
val bottomBoardIndentFromTopPercentage = 0.8f
return screenHeight * bottomBoardIndentFromTopPercentage - screenHeight * indentFromTopPercentage
}
private fun setLimitsAndStartX(
centerInWidth: Float,
boardSize: Float,
screenWidth: Float,
) {
val indentBoardFromCenterPercentage = 0.05f
if (side == BoardSide.RIGHT) {
leftLimit = centerInWidth + screenWidth * indentBoardFromCenterPercentage
startXForPlacementShips = (centerInWidth - screenWidth * indentBoardFromCenterPercentage - boardSize).toInt()
} else {
leftLimit = centerInWidth - screenWidth * indentBoardFromCenterPercentage - boardSize
startXForPlacementShips = (centerInWidth + screenWidth * indentBoardFromCenterPercentage).toInt()
}
topLimit = screenHeight!! / 2 - boardSize / cellsNumberInRow - boardSize / 2
rightLimit = leftLimit + boardSize
bottomLimit = topLimit + boardSize
}
private fun calculateCellSize(): Int {
return ((rightLimit - leftLimit) / cellsNumberInRow).toInt()
}
private fun setImgRectForImages() {
val imgDisplacementCf = 1.2f
val leftForLettersImgRect = (leftLimit - imgDisplacementCf * cellSize).toInt()
val topForNumbersImgRect = (topLimit - imgDisplacementCf * cellSize).toInt()
lettersImgRect = Rect(leftForLettersImgRect, topLimit.toInt(), leftForLettersImgRect + cellSize, bottomLimit.toInt())
numbersImgRect = Rect(leftLimit.toInt(), topForNumbersImgRect, rightLimit.toInt(), topForNumbersImgRect + cellSize)
}
private fun createLinesForBoard() {
val lineCountInOnePlane = 9
val boardWidth = rightLimit - leftLimit
val colsSize = boardWidth / cellsNumberInRow
var verticalLineStartX = leftLimit
var horizontalLineStartY = topLimit
for (i in 0..lineCountInOnePlane) {
verticalLines.add(verticalLineStartX)
horizontalLines.add(horizontalLineStartY)
verticalLineStartX += colsSize
horizontalLineStartY += colsSize
}
verticalLines.add(rightLimit)
horizontalLines.add(bottomLimit)
}
fun checkPressureWithinBoard(
x: Float,
y: Float,
): Boolean {
return (x in leftLimit..rightLimit && y in topLimit..bottomLimit)
}
fun checkImgRectWithinBoard(cellImgRect: Rect): Boolean {
val boardRect = Rect(leftLimit.toInt(), topLimit.toInt(), rightLimit.toInt(), bottomLimit.toInt())
return cellImgRect.intersect((boardRect))
}
fun drawBoard(
canvas: Canvas,
paint: Paint,
) {
for (line in verticalLines) canvas.drawLine(line, topLimit, line, bottomLimit, paint)
for (line in horizontalLines) canvas.drawLine(leftLimit, line, rightLimit, line, paint)
lettersBitmap?.let {
lettersImgRect?.let { rect ->
canvas.drawBitmap(it, null, rect, null)
}
}
numbersBitmap?.let {
numbersImgRect?.let { rect ->
canvas.drawBitmap(it, null, rect, null)
}
}
}
fun getXCellCordForShip(x: Float): Float? {
val rightVerticalLineOfCell = verticalLines.find { it > x }
return rightVerticalLineOfCell?.minus(cellSize)
}
fun getYCellCordForShip(y: Float): Float? {
val lowerHorizontalLineOfCell = horizontalLines.find { it > y }
return lowerHorizontalLineOfCell?.minus(cellSize)
}
fun getShipDisplacement(
x: Float,
y: Float,
shipLength: Int,
shipPosition: ShipOrientation,
): Float {
val permissibleLine: Float
var shipDisplacement = 0f
val linesForCheck = if (shipPosition == ShipOrientation.HORIZONTAL) verticalLines else horizontalLines
val numberPermissibleLine = linesForCheck.size - shipLength
permissibleLine = linesForCheck[numberPermissibleLine]
val cellCord = if (shipPosition == ShipOrientation.HORIZONTAL) getXCellCordForShip(x) else getYCellCordForShip(y)
if (cellCord!! - permissibleLine > 0) shipDisplacement = cellCord - permissibleLine + cellSize
return shipDisplacement
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/BoardSide.kt | 704683384 | package com.project.seaBattle.logics.board
enum class BoardSide {
RIGHT,
LEFT,
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/DrawingBoard.kt | 1296736199 | package com.project.seaBattle.logics.board
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
class DrawingBoard(context: Context, attrs: AttributeSet?) : View(context, attrs) {
private val paint = Paint()
private var rightBoard: GameBoard? = null
private var leftBoard: GameBoard? = null
init {
paint.color = Color.BLACK
paint.strokeWidth = 10f
paint.style = Paint.Style.STROKE
paint.isAntiAlias = true
}
fun setBoard(board: GameBoard) {
if (board.side == BoardSide.RIGHT) {
rightBoard = board
} else {
leftBoard = board
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (rightBoard != null) {
rightBoard?.setBoardLimits(context)
rightBoard?.drawBoard(canvas, paint)
}
if (leftBoard != null) {
leftBoard?.setBoardLimits(context)
leftBoard?.drawBoard(canvas, paint)
}
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/Cell.kt | 1857626112 | package com.project.seaBattle.logics.board
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import com.project.seaBattle.R
class Cell(val imageRect: Rect, private val isHit: Boolean, context: Context) {
private var bitmapMiss: Bitmap? = null
private var bitmapHit: Bitmap? = null
init {
bitmapMiss = BitmapFactory.decodeResource(context.resources, R.drawable.miss)
bitmapHit = BitmapFactory.decodeResource(context.resources, R.drawable.hit)
}
private fun drawMiss(canvas: Canvas) {
bitmapMiss?.let {
imageRect.let { rect ->
canvas.drawBitmap(it, null, rect, null)
}
}
}
private fun drawHit(canvas: Canvas) {
bitmapHit?.let {
imageRect.let { rect ->
canvas.drawBitmap(it, null, rect, null)
}
}
}
fun drawClick(canvas: Canvas) {
if (isHit) {
drawHit(canvas)
} else {
drawMiss(canvas)
}
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/ship/Ship.kt | 3342669311 | package com.project.seaBattle.logics.ship
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Rect
import com.project.seaBattle.R
class Ship(private val context: Context, resourceId: Int, private val cellSize: Int) {
var currentX: Int = 0
var currentY: Int = 0
var startX: Int = 0
var startY: Int = 0
var imageRect: Rect? = null
var shipLength: Int = 0
var shipPosition: ShipOrientation = ShipOrientation.HORIZONTAL
private var bitmap: Bitmap? = null
private var constantForShipSize: Float = 0.0f
private var remainingCells: Int = 0
init {
bitmap = BitmapFactory.decodeResource(context.resources, resourceId)
setConstants()
setStartPosition()
}
private fun setConstants() {
val smallestShip = BitmapFactory.decodeResource(context.resources, R.drawable.ship_single)
constantForShipSize = smallestShip.width.toFloat()
shipLength = (bitmap!!.width / constantForShipSize).toInt()
remainingCells = shipLength
}
fun draw(canvas: Canvas) {
bitmap?.let {
imageRect?.let { rect ->
canvas.drawBitmap(it, null, rect, null)
}
}
}
fun setStartPosition() {
if (shipPosition == ShipOrientation.VERTICAL) setShipHorizontal()
val width = cellSize * shipLength
imageRect =
Rect(
startX,
startY,
startX + width,
startY + cellSize,
)
}
private fun setShipVertical() {
shipPosition = ShipOrientation.VERTICAL
bitmap?.let {
val matrix = Matrix()
matrix.postRotate(90f)
bitmap = Bitmap.createBitmap(it, 0, 0, it.width, it.height, matrix, true)
}
}
private fun setShipHorizontal() {
shipPosition = ShipOrientation.HORIZONTAL
bitmap?.let {
val matrix = Matrix()
matrix.postRotate(-90f)
bitmap = Bitmap.createBitmap(it, 0, 0, it.width, it.height, matrix, true)
}
}
fun toggleShipOrientation() {
if (shipPosition == ShipOrientation.HORIZONTAL) {
setShipVertical()
} else {
setShipHorizontal()
}
}
private fun getUnavailableSpace(): Rect {
return Rect(
imageRect!!.left - cellSize / 2,
imageRect!!.top - cellSize / 2,
imageRect!!.right + cellSize,
imageRect!!.bottom + cellSize,
)
}
fun checkNeighborhoods(shipSpace: Rect): Boolean {
return shipSpace.intersect(getUnavailableSpace())
}
fun checkHits(cellImgRect: Rect): Boolean {
val isHit = cellImgRect.intersect(imageRect!!)
if (isHit) remainingCells--
return isHit
}
fun checkDestruction(): Boolean {
return remainingCells == 0
}
fun moveShipTo(
x: Int,
y: Int,
) {
currentX = x
currentY = y
}
private fun calculateOutermostCells(): Pair<Rect, Rect> {
val width = shipLength * cellSize
return if (shipPosition == ShipOrientation.HORIZONTAL) {
Pair(
Rect(currentX - cellSize, currentY, currentX, currentY + cellSize),
Rect(currentX + width, currentY, currentX + width + cellSize, currentY + cellSize),
)
} else {
Pair(
Rect(currentX, currentY - cellSize, currentX + cellSize, currentY),
Rect(currentX, currentY + width, currentX + cellSize, currentY + width + cellSize),
)
}
}
private fun addCellsToList(
cellsList: MutableList<Rect>,
firstOutermostCell: Rect,
secondOutermostCell: Rect,
) {
cellsList.add(firstOutermostCell)
cellsList.add(secondOutermostCell)
}
private fun addSurroundingCells(
cellsList: MutableList<Rect>,
outermostCell: Rect,
isHorizontal: Boolean,
) {
val left = outermostCell.left
val right = outermostCell.right
val top = outermostCell.top
val bottom = outermostCell.bottom
for (cell in 0 until shipLength + 2) {
val leftOffset = left + cell * cellSize
val rightOffset = right + cell * cellSize
val topOffset = top + cell * cellSize
val bottomOffset = bottom + cell * cellSize
if (isHorizontal) {
cellsList.add(Rect(leftOffset, currentY - cellSize, rightOffset, currentY))
cellsList.add(Rect(leftOffset, currentY + cellSize, rightOffset, currentY + 2 * cellSize))
} else {
cellsList.add(Rect(currentX - cellSize, topOffset, currentX, bottomOffset))
cellsList.add(Rect(currentX + cellSize, topOffset, currentX + 2 * cellSize, bottomOffset))
}
}
}
fun getSurroundingCells(): MutableList<Rect> {
val surroundingCells = mutableListOf<Rect>()
val (firstOutermostCell, secondOutermostCell) = calculateOutermostCells()
addCellsToList(surroundingCells, firstOutermostCell, secondOutermostCell)
addSurroundingCells(surroundingCells, firstOutermostCell, shipPosition == ShipOrientation.HORIZONTAL)
return surroundingCells
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/ship/ShipOrientation.kt | 1845722267 | package com.project.seaBattle.logics.ship
enum class ShipOrientation {
HORIZONTAL,
VERTICAL,
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/shipsSetting/ShipsSetter.kt | 3023537595 | package com.project.seaBattle.logics.shipsSetting
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.project.seaBattle.R
import com.project.seaBattle.logics.board.GameBoard
import com.project.seaBattle.logics.ship.Ship
import com.project.seaBattle.logics.ship.ShipOrientation
class ShipsSetter(context: Context, attrs: AttributeSet?) : View(context, attrs) {
var gameBoard: GameBoard? = null
val ships = mutableListOf<Ship>()
private var movingShip: Ship? = null
private var touchX = 0f
private var touchY = 0f
private var cellSize: Int = 0
private var shipCapsizes: Boolean = false
private var xUntilMoving = 0
private var yUntilMoving = 0
fun initializeShips() {
gameBoard?.setBoardLimits(context)
cellSize = gameBoard?.cellSize!!
addShips(R.drawable.ship_single, 4, cellSize)
addShips(R.drawable.ship_double, 3, cellSize)
addShips(R.drawable.ship_triple, 2, cellSize)
addShips(R.drawable.ship_fourfold, 1, cellSize)
}
private fun addShips(
resourceId: Int,
count: Int,
cellSize: Int,
) {
val yIndentFromBoardTop = 50f
val startY = (gameBoard?.topLimit!! + yIndentFromBoardTop).toInt()
val startX = gameBoard?.startXForPlacementShips
var distanceMultiplier = 0
repeat(count) {
val newShip = Ship(context, resourceId, cellSize)
val shipTypesNumber = 4
newShip.currentY = startY + ((shipTypesNumber - count) * cellSize * 2)
val xDistanceBetweenShips = 7 - count
if (startX != null) newShip.currentX = startX + distanceMultiplier * cellSize * xDistanceBetweenShips
newShip.startX = newShip.currentX
newShip.startY = newShip.currentY
newShip.setStartPosition()
ships.add(newShip)
distanceMultiplier++
}
}
private fun checkPossibilityInstallingShip(): Boolean {
var falseCount = 0
for (ship in ships) {
movingShip?.imageRect?.let {
if (ship.checkNeighborhoods(it)) {
falseCount++
if (falseCount == 2) return false
}
}
}
return true
}
fun areAllShipsInstalled(): Boolean {
for (ship in ships) {
if (ship.imageRect?.let { gameBoard?.checkImgRectWithinBoard(it) } != true) {
return false
}
}
return true
}
private fun handleShipMovement(
ship: Ship,
touchX: Float,
touchY: Float,
) {
val displacement = gameBoard?.getShipDisplacement(touchX, touchY, ship.shipLength, ship.shipPosition)
ship.currentX = gameBoard?.getXCellCordForShip(touchX)?.toInt()!!
ship.currentY = gameBoard?.getYCellCordForShip(touchY)?.toInt()!!
if (ship.shipPosition == ShipOrientation.HORIZONTAL) {
ship.currentX -= displacement!!.toInt()
} else {
ship.currentY -= displacement!!.toInt()
}
}
private fun updateImageRect(ship: Ship) {
val width = if (ship.shipPosition == ShipOrientation.HORIZONTAL) cellSize * ship.shipLength else cellSize
val height = if (ship.shipPosition == ShipOrientation.HORIZONTAL) cellSize else cellSize * ship.shipLength
ship.imageRect?.set(ship.currentX, ship.currentY, ship.currentX + width, ship.currentY + height)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
for (ship in ships) {
ship.draw(canvas)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
touchX = event.x
touchY = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> {
shipCapsizes = true
for (ship in ships) {
if (ship.imageRect!!.contains(touchX.toInt(), touchY.toInt())) {
movingShip = ship
movingShip?.let {
xUntilMoving = it.currentX
yUntilMoving = it.currentY
it.currentX = touchX.toInt()
it.currentY = touchY.toInt()
}
}
}
}
MotionEvent.ACTION_MOVE -> {
shipCapsizes = false
movingShip?.let {
val deltaX = touchX.toInt() - it.currentX
val deltaY = touchY.toInt() - it.currentY
val width = if (it.shipPosition == ShipOrientation.HORIZONTAL) cellSize * it.shipLength else cellSize
val height = if (it.shipPosition == ShipOrientation.HORIZONTAL) cellSize else cellSize * it.shipLength
it.currentX += deltaX
it.currentY += deltaY
it.imageRect!!.set(
it.currentX,
it.currentY,
it.currentX + width,
it.currentY + height,
)
}
invalidate()
}
MotionEvent.ACTION_UP -> {
if (gameBoard!!.checkPressureWithinBoard(touchX, touchY)) {
movingShip?.let {
if (!checkPossibilityInstallingShip()) {
it.moveShipTo(xUntilMoving, yUntilMoving)
} else {
if (gameBoard?.checkPressureWithinBoard(touchX, touchY) == true) {
handleShipMovement(it, touchX, touchY)
if (shipCapsizes) {
it.toggleShipOrientation()
handleShipMovement(it, touchX, touchY)
}
updateImageRect(it)
if (!checkPossibilityInstallingShip()) {
if (shipCapsizes) it.toggleShipOrientation()
it.moveShipTo(xUntilMoving, yUntilMoving)
}
}
}
updateImageRect(it)
}
} else {
movingShip?.setStartPosition()
}
invalidate()
}
}
return true
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/logics/shipsSetting/GameInfoManager.kt | 783446715 | package com.project.seaBattle.logics.shipsSetting
import com.project.seaBattle.logics.board.BoardSide
import com.project.seaBattle.logics.ship.Ship
class GameInfoManager private constructor() {
var rightPlayerName: String? = null
var winnerName: String? = null
val rightShips: MutableList<Ship> = mutableListOf()
val leftShips: MutableList<Ship> = mutableListOf()
var leftPlayerName: String? = null
fun addShips(
ships: MutableList<Ship>,
side: BoardSide,
) {
if (side == BoardSide.RIGHT) {
rightShips.addAll(ships)
} else {
leftShips.addAll(ships)
}
}
fun setPlayerName(
name: String,
side: BoardSide,
) {
if (side == BoardSide.RIGHT) {
rightPlayerName = name
} else {
leftPlayerName = name
}
}
fun resetAllInfo() {
rightShips.clear()
leftShips.clear()
leftPlayerName = null
rightPlayerName = null
winnerName = null
}
companion object {
private var instance: GameInfoManager? = null
fun getInstance(): GameInfoManager {
if (instance == null) {
instance = GameInfoManager()
}
return instance!!
}
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/dialogs/ShowingWinnerDialog.kt | 1461186359 | package com.project.seaBattle.dialogs
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.fragment.app.DialogFragment
import com.project.seaBattle.activities.StartActivity
import com.project.seaBattle.databinding.DialogWinnerLayoutBinding
class ShowingWinnerDialog(private val winnerName: String) : DialogFragment() {
@Suppress("ktlint:standard:property-naming")
private var _binding: DialogWinnerLayoutBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = DialogWinnerLayoutBinding.inflate(inflater, container, false)
val view = binding.root
binding.winner.text = winnerName
binding.returnStartActivity.setOnClickListener {
val intent = Intent(context, StartActivity::class.java)
startActivity(intent)
}
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return dialog
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/dialogs/PlayerNameDialog.kt | 137357977 | package com.project.seaBattle.dialogs
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.fragment.app.DialogFragment
import com.project.seaBattle.databinding.DialogPlayerNameLayoutBinding
class PlayerNameDialog : DialogFragment() {
@Suppress("ktlint:standard:property-naming")
private var _binding: DialogPlayerNameLayoutBinding? = null
private var onNameEntered: ((name: String) -> Unit)? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = DialogPlayerNameLayoutBinding.inflate(inflater, container, false)
val view = binding.root
binding.saveName.setOnClickListener {
onNameEntered?.invoke(binding.enterName.text.toString())
dismiss()
}
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return dialog
}
fun setOnNameEntered(listener: (name: String) -> Unit) {
onNameEntered = listener
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/activities/StartActivity.kt | 2180414811 | package com.project.seaBattle.activities
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.project.seaBattle.databinding.ActivityMainBinding
import com.project.seaBattle.logics.board.BoardSide
import com.project.seaBattle.logics.shipsSetting.GameInfoManager
import com.project.seaBattle.utils.showToast
class StartActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
val gameInfoManager = GameInfoManager.getInstance()
binding.player1Button.setOnClickListener {
if (gameInfoManager.leftShips.isNotEmpty()) {
showToast("The ships for the first player are already installed", this)
} else {
val intent = Intent(this, SetShipsActivity::class.java)
intent.putExtra("SIDE", BoardSide.LEFT.name)
startActivity(intent)
}
}
binding.player2Button.setOnClickListener {
if (gameInfoManager.rightShips.isNotEmpty()) {
showToast("The ships for the second player are already installed", this)
} else {
val intent = Intent(this, SetShipsActivity::class.java)
intent.putExtra("SIDE", BoardSide.RIGHT.name)
startActivity(intent)
}
}
binding.startButton.setOnClickListener {
if (gameInfoManager.leftShips.isNotEmpty() && gameInfoManager.rightShips.isNotEmpty()) {
val intent = Intent(this, BattleActivity::class.java)
startActivity(intent)
} else {
showToast("Ships are not installed for all players", this)
}
}
binding.resetInfo.setOnClickListener {
gameInfoManager.resetAllInfo()
}
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/activities/BattleActivity.kt | 994047204 | package com.project.seaBattle.activities
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.project.seaBattle.databinding.ActivityBattleBinding
import com.project.seaBattle.dialogs.ShowingWinnerDialog
import com.project.seaBattle.logics.board.BoardSide
import com.project.seaBattle.logics.board.GameBoard
import com.project.seaBattle.logics.shipsSetting.GameInfoManager
import com.project.seaBattle.utils.setupOnBackPressedCallback
import com.project.seaBattle.utils.showToast
class BattleActivity : AppCompatActivity() {
private lateinit var binding: ActivityBattleBinding
private val leftGameBoard = GameBoard(BoardSide.LEFT)
private val rightGameBoard = GameBoard(BoardSide.RIGHT)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBattleBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
setupGame()
setupOnBackPressedCallback {
showToast("This button does not work in the game", this)
}
}
private fun setupGame() {
val gameInfoManager = GameInfoManager.getInstance()
binding.drawingBoard.setBoard(rightGameBoard)
binding.drawingBoard.setBoard(leftGameBoard)
binding.firstPlayerName.text = gameInfoManager.leftPlayerName
binding.secondPlayerName.text = gameInfoManager.rightPlayerName
binding.battleEditor.leftShips = gameInfoManager.leftShips
binding.battleEditor.rightShips = gameInfoManager.rightShips
binding.battleEditor.setRightBoard(rightGameBoard)
binding.battleEditor.setLeftBoard(leftGameBoard)
binding.battleEditor.setOnGameOver { loser ->
gameInfoManager.winnerName = if (loser == BoardSide.RIGHT) gameInfoManager.leftPlayerName else gameInfoManager.rightPlayerName
gameInfoManager.winnerName?.let {
val showingWinnerDialog = ShowingWinnerDialog(it)
showingWinnerDialog.show(supportFragmentManager, "ShowingWinnerDialog")
}
gameInfoManager.resetAllInfo()
}
}
}
|
sea-battle/app/src/main/java/com/project/seaBattle/activities/SetShipsActivity.kt | 2197241071 | package com.project.seaBattle.activities
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.project.seaBattle.databinding.ActivitySetShipsBinding
import com.project.seaBattle.dialogs.PlayerNameDialog
import com.project.seaBattle.logics.board.BoardSide
import com.project.seaBattle.logics.board.GameBoard
import com.project.seaBattle.logics.shipsSetting.GameInfoManager
import com.project.seaBattle.utils.setupOnBackPressedCallback
import com.project.seaBattle.utils.showToast
class SetShipsActivity : AppCompatActivity() {
private lateinit var binding: ActivitySetShipsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySetShipsBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
val boardSideName = intent.getStringExtra("SIDE")
val boardSide = boardSideName?.let { BoardSide.valueOf(it) }
val gameBoard = boardSide?.let { GameBoard(it) }
val gameInfoManager = GameInfoManager.getInstance()
val playerNameDialog = PlayerNameDialog()
playerNameDialog.show(supportFragmentManager, "PlayerNameDialog")
playerNameDialog.setOnNameEntered { name ->
gameInfoManager.setPlayerName(name, boardSide!!)
}
binding.drawingBoard.setBoard(gameBoard!!)
binding.shipsSetter.gameBoard = gameBoard
binding.shipsSetter.initializeShips()
binding.shipsInstalled.setOnClickListener {
if (binding.shipsSetter.areAllShipsInstalled()) {
gameInfoManager.addShips(binding.shipsSetter.ships, boardSide)
finish()
} else {
showToast("Not all ships are installed", this)
}
}
setupOnBackPressedCallback {
showToast("This button does not work in the game", this)
}
}
}
|
One_Homework/app/src/androidTest/java/com/example/onelab_homework/ExampleInstrumentedTest.kt | 591914039 | package com.example.onelab_homework
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.onelab_homework", appContext.packageName)
}
} |
One_Homework/app/src/test/java/com/example/onelab_homework/ExampleUnitTest.kt | 3046694333 | package com.example.onelab_homework
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)
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/database/BookDbEntity.kt | 2870244021 | package com.example.onelab_homework.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.example.homework.book.Book
import java.util.PriorityQueue
@Entity(tableName = "book")
public class BookDbEntity(
@PrimaryKey(autoGenerate = true) val id:Long,
@ColumnInfo(name ="name") val name:String,
@ColumnInfo(name ="description") var descr :String,
@ColumnInfo(name ="price") var imageUrl:String ,
@ColumnInfo(name ="isFavorite") var isFavorite:Boolean
) {
fun toBook(): Book {
BookDbEntity
return Book(
id =id,
name =name,
descr =descr,
imageUrl =imageUrl,
isFavorite= isFavorite
)
}
companion object {
fun toDbEntity(book: Book): BookDbEntity {
return BookDbEntity(
name = book.name,
descr = book.descr,
imageUrl = book.imageUrl,
id = book.id,
isFavorite = book.isFavorite
)
}
fun toBook(bookDbEntity: BookDbEntity): Book {
return Book(
id = bookDbEntity.id,
name = bookDbEntity.name,
descr = bookDbEntity.descr,
imageUrl =bookDbEntity.imageUrl,
isFavorite =bookDbEntity.isFavorite
)
}
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/database/AppDatabase.kt | 3258453640 | package com.example.onelab_homework.database
import androidx.room.Database
import androidx.room.Index
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
@Database(
version = 1,
entities = [BookDbEntity::class ]
)
//@TypeConverters(BookConverters::class )
abstract class AppDatabase:RoomDatabase() {
abstract fun getBookDao():BookDao
} |
One_Homework/app/src/main/java/com/example/onelab_homework/database/BookDao.kt | 191117691 | package com.example.onelab_homework.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.example.homework.book.Book
@Dao
interface BookDao {
@Query("Select * from book")
suspend fun getAllBooks():List<BookDbEntity>?
@Insert
suspend fun addBook(books:BookDbEntity)
@Query("Delete from book")
suspend fun deleteAll()
@Query("UPDATE book SET isFavorite =:isFavorite where name =:name")
suspend fun changeFavorite(name:String ,isFavorite:Boolean)
@Query("Select * from book where isFavorite =1")
suspend fun getAllFavorites() :List<BookDbEntity>?
} |
One_Homework/app/src/main/java/com/example/onelab_homework/database/BooksRepository.kt | 1752145813 | package com.example.onelab_homework.database
import com.example.homework.book.Book
import com.example.onelab_homework.book.Resource
interface BooksRepository {
suspend fun getBooks(text:String): Resource<List<Book>>
suspend fun getBooksFromCache():List<Book>?
suspend fun addBookToCache(books:List<Book>)
suspend fun getFavoritesBook():List<Book>
suspend fun addFavoriteBook(book: Book)
suspend fun getAllBooks():List<Book>
//clear cache
suspend fun deleteAllBooks()
suspend fun changeFavorite(name:String ,isFavorite:Boolean)
suspend fun getAllFavorites():List<Book>
} |
One_Homework/app/src/main/java/com/example/onelab_homework/database/BooksRepositoryImpl.kt | 1348254774 | package com.example.onelab_homework.database
import android.util.Log
import com.example.homework.book.Book
import com.example.homework.book.BookApi
import com.example.onelab_homework.book.Resource
class BooksRepositoryImpl(val api: BookApi, val bookDao:BookDao): BooksRepository {
override suspend fun getBooks(text:String): Resource<List<Book>> {
val response = try {
val ss =api.getBooksByQuery(text)
val resp = mutableListOf<Book>()
Log.d("12132321132","${ss.toString()} ")
Log.d("12132321132","${ss.items.size} ")
ss.items[0].volumeInfo.title
ss.items[0].volumeInfo.description
for(a in 0 until 8){
Log.d("12132321132" ,ss.items.get(a).volumeInfo.imageLinks.smallThumbnail)
Log.d("12132321132" ,ss.items.get(a).volumeInfo.title)
Log.d("12132321132" ,ss.items.get(a).volumeInfo.description ?: "No descr")
val sub =ss.items.get(a).volumeInfo.imageLinks.smallThumbnail.substring(4)
val s = Book(id = 0, imageUrl = "https${sub}",
name =ss.items[a].volumeInfo.title,
descr = ss.items[a].volumeInfo.description ?: "No description",
isFavorite = false
)
resp.add(s)
}
Log.d("12132321132","what")
return Resource.Success(resp)
} catch(e: Exception) {
Log.d("12132321132" ,e.toString())
return Resource.Error("An unknown error occured.")
}
return Resource.Loading()
//
//
// call.enqueue(object : Callback<BookResponse> {
// override fun onResponse(call: Call<BookResponse>, response: Response<BookResponse>) {
// if (response.isSuccessful) {
// val bookResponse = response.body()
// response
// for(a in 0 until bookResponse!!.items.size){
// listOfBook.add(Book(
// bookResponse.items.get(a).volumeInfo.imageLinks.thumbnail
// )
//
// )
// }
// } else {
// Log.d("LOGGING", "ERROR")
// // Handle error
// }
// }
//
// override fun onFailure(call: Call<BookResponse>, t: Throwable) {
// Log.d("LOGGING", "Failiare")
// }
// })
// return listOfBook
}
override suspend fun getBooksFromCache(): List<Book>? {
val sss =bookDao.getAllBooks()!!.map { BookDbEntity -> BookDbEntity.toBook() }
return sss
TODO("Not yet implemented")
}
override suspend fun addBookToCache(books: List<Book>) {
val bookDbEntities = mutableListOf<BookDbEntity>()
for(a in 0 until books.size){
bookDbEntities.add(BookDbEntity.toDbEntity(books[a]))
}
for(b in 0 until books.size){
bookDao.addBook(bookDbEntities[b])
}
Log.d("32132123", "books.added")
}
override suspend fun getFavoritesBook(): List<Book> {
//return bookDao.getFavoritesBooks().map { BookDbEntity -> BookDbEntity.toBook() }
return listOf()
}
override suspend fun addFavoriteBook(book: Book) {
// bookDao.addFavorites(BookDbEntity(book.id ,book.name ,book.descr ,book.imageUrl))
}
override suspend fun getAllBooks(): List<Book> {
TODO("Not yet implemented")
}
override suspend fun deleteAllBooks() {
bookDao.deleteAll()
}
override suspend fun changeFavorite(name:String ,isFavorite:Boolean) {
bookDao.changeFavorite(name,isFavorite)
}
override suspend fun getAllFavorites(): List<Book> {
val books =bookDao.getAllFavorites()
if(books==null){
return listOf()
}
else{
return bookDao.getAllFavorites()!!.map { BookDbEntity -> BookDbEntity.toBook() }
}
}
}
|
One_Homework/app/src/main/java/com/example/onelab_homework/MyReceiver.kt | 3207311045 | package com.example.onelab_homework
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationManagerCompat
class MyReceiver : BroadcastReceiver() {
override fun onReceive( context: Context, intent: Intent) {
}
}
|
One_Homework/app/src/main/java/com/example/onelab_homework/App.kt | 4144137228 | package com.example.onelab_homework
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.room.Room
import com.example.homework.book.BookApi
import com.example.onelab_homework.database.BooksRepository
import com.example.onelab_homework.database.AppDatabase
import com.example.onelab_homework.database.BooksRepositoryImpl
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object App {
lateinit var applicationContext: Context
fun init(context:Context){
applicationContext =context
}
val retrofit = Retrofit.Builder()
.baseUrl(BookApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
private val database1: AppDatabase by lazy<AppDatabase> {
Room.databaseBuilder(applicationContext, AppDatabase::class.java, "database.db")
// .createFromAsset("initial_database.db")
.build()
}
private val bookApi = retrofit.create(BookApi::class.java)
val booksRepository: BooksRepository by lazy{
BooksRepositoryImpl(bookApi, database1.getBookDao() )
}
}
|
One_Homework/app/src/main/java/com/example/onelab_homework/MyItemRecyclerViewAdapter.kt | 291539860 | package com.example.onelab_homework
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.homework.book.Book
import com.example.onelab_homework.database.BooksRepository
import com.example.onelab_homework.databinding.FragmentItemBinding
import kotlinx.coroutines.launch
class MyItemRecyclerViewAdapter(
val navController: NavController,
val context: Context,
val booksRepository: BooksRepository,
val lifecycleScope: LifecycleCoroutineScope
): RecyclerView.Adapter<MyItemRecyclerViewAdapter.SeedsViewHolder>() {
var itemList =mutableListOf<Book>()
set(newValue) {
field= newValue
notifyDataSetChanged()
}
fun assignist(listElement: MutableList<Book>){
Log.d("32132123","ASSigned")
for(a in listElement){
Log.d("32132123",a.toString())
}
itemList =listElement
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SeedsViewHolder {
Log.d("32132123","create")
val inflater =LayoutInflater.from(parent.context)
val binding =FragmentItemBinding.inflate(inflater,parent,false)
return SeedsViewHolder(binding)
}
override fun getItemCount()= itemList.size
override fun onBindViewHolder(holder: SeedsViewHolder, position: Int) {
val item =itemList[position]
Log.d("32132123","${item.imageUrl} herehrehrherhehrher")
Glide.with(context)
.load(item.imageUrl)
.into(holder.binding.itemImage)
holder.binding.root.setOnClickListener{
val bundle =Bundle()
//serilizable медленнее, но легче
bundle.putSerializable("KEY" ,item)
navController.navigate(R.id.action_itemFragment_to_elementDescriptionPage, bundle)
}
holder.binding.root.setOnLongClickListener{
lifecycleScope.launch {
booksRepository.addFavoriteBook(item)
Toast.makeText(context ,"Added!",Toast.LENGTH_SHORT).show()
}
true
}
}
class SeedsViewHolder(val binding:FragmentItemBinding):RecyclerView.ViewHolder(binding.root){
}
}
data class MyListElement(var name:String ,var text:String )
|
One_Homework/app/src/main/java/com/example/onelab_homework/MainActivity.kt | 2347717480 | package com.example.onelab_homework
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.NavigationUI.setupWithNavController
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.onelab_homework.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding :ActivityMainBinding
private lateinit var navController : NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding =ActivityMainBinding.inflate(layoutInflater)
App.init(applicationContext)
//setSupportActionBar(binding.toobarMainPage)
setContentView(binding.root)
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/fragments/placeholder/FavoritesFragment.kt | 3638578991 | package com.example.onelab_homework.fragments.placeholder
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.Coil
import coil.compose.AsyncImage
import com.example.homework.book.Book
import com.example.onelab_homework.R
import com.example.onelab_homework.databinding.FragmentFavoritesBinding
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [FavoritesFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class FavoritesFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
lateinit var binding:FragmentFavoritesBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =FragmentFavoritesBinding.inflate(layoutInflater)
val composeView = binding.composeView
val favorites = mutableListOf<Book>()
composeView.setContent {
// Compose code here
composeView.setContent {
val books =(arguments?.getSerializable("MYKEY") ?: mutableListOf(Book(0,"123","123","123" ,false)) )as MutableList<Book>
Log.d("1233312132312","$books")
Greeting(books)
}
}
// Inflate the layout for this fragment
return binding.root
}
@Composable
fun Greeting(favorites:MutableList<Book>) {
LazyColumn(){
items(favorites.size){
ListElement(favorites[it])
}
}
}
@Composable
fun ListElement(item:Book){
Row(Modifier.height(100.dp).padding(bottom =10.dp ,end =10.dp)) {
AsyncImage(
modifier = Modifier.fillMaxHeight().width(100.dp),
model = item.imageUrl,
contentDescription = null
)
Column(){
Text(item.name ,Modifier.padding(top =10.dp) ,fontWeight = FontWeight.Bold , fontSize =16.sp)
Text(getFirst20Words(item.descr),Modifier.padding(top =10.dp))
}
}
}
fun getFirst20Words(input: String): String {
val words = input.trim().split("\\s+".toRegex()) // Split the string into words
val first30Words = words.take(20) // Take the first 30 words
return first30Words.joinToString(" ") // Join the first 30 words back into a single string
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FavoritesFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FavoritesFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/ViewModelFactory.kt | 3094574634 | package com.example.onelab_homework
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
typealias ViewModelCreator<VM> = () -> VM
class ViewModelFactory<VM : ViewModel>(
private val viewModelCreator: ViewModelCreator<VM>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return viewModelCreator() as T
}
}
inline fun <reified VM : ViewModel> Fragment.viewModelCreator(noinline creator: ViewModelCreator<VM>): Lazy<VM> {
return viewModels { ViewModelFactory(creator) }
}
inline fun <reified VM : ViewModel> ComponentActivity.viewModelCreator(noinline creator: ViewModelCreator<VM>): Lazy<VM> {
return viewModels { ViewModelFactory(creator) }
} |
One_Homework/app/src/main/java/com/example/onelab_homework/ListViewModel.kt | 3496197212 | package com.example.onelab_homework
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.homework.book.Book
import com.example.onelab_homework.database.BooksRepository
import com.example.onelab_homework.book.Resource
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
class ListViewModel(val repository: BooksRepository ,val context: Context): ViewModel() {
var books = MutableLiveData<MutableList<Book>>()
var favorites =MutableLiveData<MutableList<Book>>()
fun getBooks(text:String){
viewModelScope.launch {
val bookss = repository.getBooksFromCache()!!
val comp = listOf<Book>()
if (bookss.size!=0 ) {
Log.d("32132123",bookss.size.toString())
books.value = bookss.toMutableList()
} else {
Log.d("32132123","HERE HH")
val res = repository.getBooks(text)
when (res) {
is Resource.Success -> {
Log.d("12132321132", res.data?.get(0)!!.imageUrl.toString())
books.value = res.data.toMutableList()
repository.addBookToCache(res.data)
}
is Resource.Loading -> {
Log.d("12132321132", "Loading")
}
is Resource.Error -> {
Log.d("12132321132", "Errorrrr")
}
}
}
}
}
fun deleteAll() {
viewModelScope.launch {
repository.deleteAllBooks()
}
}
suspend fun getAllFavorites() {
Log.d("1233312132312" ,"WHAT")
viewModelScope.launch {
favorites.value = repository.getAllFavorites().toMutableList()
}
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/ElementDescriptionViewModel.kt | 2104067655 | package com.example.onelab_homework
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.onelab_homework.database.BooksRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class ElementDescriptionViewModel(val repository: BooksRepository , val context: Context): ViewModel() {
private val CHANNEL_ID = "channel_id"
private val NOTIFICATION_ID = 123
var isFavorite= MutableLiveData<Boolean>()
fun changeFavorite(name:String ,isFavorite:Boolean){
viewModelScope.launch {
repository.changeFavorite(name ,isFavorite)
}
}
fun sendMsg(bookName:String) {
viewModelScope.launch(Dispatchers.IO) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"Channel Name",
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
}
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.baseline_timer_24)
.setContentTitle("Time to read!")
.setContentText("You need to read ${bookName}")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
notificationManager.notify(NOTIFICATION_ID, builder.build())
}
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/ItemFragment.kt | 1081666066 | package com.example.onelab_homework
import android.R.menu
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.example.homework.book.Book
import com.example.onelab_homework.databinding.FragmentItemListBinding
import kotlinx.coroutines.launch
import java.io.Serializable
/**
* A fragment representing a list of Items.
*/
class ItemFragment : Fragment() {
val viewModel by viewModelCreator {
ListViewModel(
App.booksRepository,
requireContext()
)
}
lateinit var binding : FragmentItemListBinding
lateinit var adapter: MyItemRecyclerViewAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =FragmentItemListBinding.inflate(layoutInflater)
adapter = MyItemRecyclerViewAdapter(findNavController(), requireContext() ,App.booksRepository ,lifecycleScope)
binding.list.adapter =adapter
binding.list.layoutManager =GridLayoutManager(context, 2)
// adapter.assignist(sss)
viewModel.getBooks("night")
// binding.toobarMainPage.menu
viewModel.favorites.observe(viewLifecycleOwner){items ->
val bundle =Bundle()
bundle.putSerializable("MYKEY" ,items as Serializable)
findNavController().navigate(R.id.action_itemFragment_to_favoritesFragment, bundle)
}
//viewModel.deleteAll()
viewModel.books.observe(viewLifecycleOwner){
Log.d("32132123", "observer works")
adapter.assignist(it)
}
// adapter.itemList = listOf{
// Book("123" ,)
// }
val toolbar =binding.toobarMainPage
toolbar.inflateMenu(R.menu.menu_main_page);
toolbar.title ="My App"
toolbar.setOnMenuItemClickListener {
when(it.itemId){
R.id.Favorites -> {
lifecycleScope.launch {
val s =viewModel.getAllFavorites()
// chtoto(s.await())
}
true
}
else -> {
false
}
}
}
return binding.root
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/book/Book.kt | 3897329101 | package com.example.homework.book
import com.example.onelab_homework.book.SeriesInfo
import java.io.Serializable
data class Book(var id:Long ,var name:String ,var descr :String ,var imageUrl :String, var isFavorite:Boolean):Serializable
|
One_Homework/app/src/main/java/com/example/onelab_homework/book/BookResponse.kt | 2981277289 | package com.example.onelab_homework.book
data class IndustryIdentifier(
val type: String,
val identifier: String
)
data class ReadingModes(
val text: Boolean,
val image: Boolean
)
data class PanelizationSummary(
val containsEpubBubbles: Boolean,
val containsImageBubbles: Boolean
)
data class ImageLinks(
val smallThumbnail: String,
val thumbnail: String
)
data class SaleInfo(
val country: String,
val saleability: String,
val isEbook: Boolean,
val listPrice: Map<String, Any>? = null,
val retailPrice: Map<String, Any>? = null,
val buyLink: String? = null,
val offers: List<Map<String, Any>>? = null
)
data class Epub(
val isAvailable: Boolean,
val acsTokenLink: String
)
data class Pdf(
val isAvailable: Boolean,
val acsTokenLink: String
)
data class AccessInfo(
val country: String,
val viewability: String,
val embeddable: Boolean,
val publicDomain: Boolean,
val textToSpeechPermission: String,
val epub: Epub? = null,
val pdf: Pdf? = null,
val webReaderLink: String? = null,
val accessViewStatus: String? = null,
val quoteSharingAllowed: Boolean? = null
)
data class VolumeInfo(
val title: String,
val subtitle: String? = null,
val authors: List<String>,
val publisher: String,
val publishedDate: String,
val description: String?,
val industryIdentifiers: List<IndustryIdentifier>,
val readingModes: ReadingModes,
val pageCount: Int,
val printType: String,
val categories: List<String>,
val maturityRating: String,
val allowAnonLogging: Boolean,
val contentVersion: String,
val panelizationSummary: PanelizationSummary,
val imageLinks: ImageLinks,
val language: String,
val previewLink: String,
val infoLink: String,
val canonicalVolumeLink: String,
val seriesInfo: Map<String, Any>? = null
)
data class SearchInfo(
val textSnippet: String
)
data class SeriesInfo(
val kind: String,
val bookDisplayNumber: String,
val volumeSeries: List<Map<String, Any>>
)
data class Volume(
val kind: String,
val id: String,
val etag: String,
val selfLink: String,
val volumeInfo: VolumeInfo,
val saleInfo: SaleInfo,
val accessInfo: AccessInfo,
val searchInfo: SearchInfo,
val seriesInfo: SeriesInfo? = null
)
data class BookResponse(
val kind: String,
val totalItems: Int,
val items: List<Volume>
) |
One_Homework/app/src/main/java/com/example/onelab_homework/book/Resource.kt | 1068643604 | package com.example.onelab_homework.book
sealed class Resource<T>(val data: T? = null, val message: String? = null) {
class Success<T>(data: T) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
class Loading<T> : Resource<T>()
} |
One_Homework/app/src/main/java/com/example/onelab_homework/book/BookApi.kt | 2449676395 | package com.example.homework.book
import com.example.onelab_homework.book.BookResponse
import retrofit2.http.GET
import retrofit2.http.Query
interface BookApi {
companion object {
const val BASE_URL = "https://www.googleapis.com/books/v1/"
}
@GET("volumes")
suspend fun getBooksByQuery(@Query("q") query: String): BookResponse
} |
One_Homework/app/src/main/java/com/example/onelab_homework/MyWorker.kt | 4148928846 | package com.example.onelab_homework
import android.content.Context
import android.content.Intent
import androidx.work.Worker
import androidx.work.WorkerParameters
class MyWorker(val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
override fun doWork(): Result {
// Отправляем широковещательное сообщение
val intent = Intent("com.example.MY_NOTIFICATION")
context.sendBroadcast(intent)
return Result.success()
}
} |
One_Homework/app/src/main/java/com/example/onelab_homework/ElementDescriptionPage.kt | 2366294254 | package com.example.onelab_homework
import android.app.AlertDialog
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.lifecycle.lifecycleScope
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.bumptech.glide.Glide
import com.example.homework.book.Book
import com.example.onelab_homework.databinding.FragmentElementDescriptionPageBinding
import com.example.onelab_homework.databinding.StartTimerBinding
import java.util.concurrent.TimeUnit
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ElementDescriptionPage.newInstance] factory method to
* create an instance of this fragment.
*/
class ElementDescriptionPage : Fragment() {
lateinit var binding:FragmentElementDescriptionPageBinding
lateinit var name:String
val viewModel by viewModelCreator {
ElementDescriptionViewModel(
App.booksRepository,
requireContext()
)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =FragmentElementDescriptionPageBinding.inflate(layoutInflater)
val book =(arguments?.getSerializable("KEY") ?: Book(0,"123","123","123" ,false) )as Book
viewModel.isFavorite.value =book.isFavorite
name =book.name
// if(book.isFavorite){
// val s =binding.toobarDescr.menu.findItem(R.id.addToFavorite)
// Log.d("asdjkljdsajkdlsajlkads" ,s.toString())
// }
Log.d("What" , book.imageUrl)
Glide.with(this)
.load(book.imageUrl)
.into(binding.imageView)
binding.descriptionItem.text =book.descr
binding.nameItemm.text =book.name
val toolbar =binding.toobarDescr
toolbar.inflateMenu(R.menu.menu_descriprion);
toolbar.setOnMenuItemClickListener {
when (it.itemId) {
R.id.addToFavorite -> {
Log.d("123123","2312231312213123")
//it.setIcon(R.drawable.baseline_favorite_24)
viewModel.isFavorite.value =!viewModel.isFavorite.value!!
true
}
R.id.addTimer -> {
val builder = AlertDialog.Builder(context)
var binding = StartTimerBinding.inflate(layoutInflater)
builder.setView(binding.root)
val alertDialog =builder.create()
binding.button.setOnClickListener{
viewModel.sendMsg(name)
}
if(alertDialog.window!=null){
alertDialog.window!!.setBackgroundDrawable(ColorDrawable(0))
}
alertDialog.show()
true
}
else -> {
true
}
}
}
toolbar.title ="My Descr"
viewModel.isFavorite.observe(viewLifecycleOwner){
Log.d("123123",it.toString())
val s = binding.toobarDescr.menu.findItem(R.id.addToFavorite)
if(it) {
Log.d("123123","trueasd")
s.setIcon(R.drawable.baseline_favorite_24)
viewModel.changeFavorite(name ,isFavorite =it )
}
else {
Log.d("123123","falseasd")
s.setIcon(R.drawable.baseline_not_favorite)
viewModel.changeFavorite(name ,isFavorite =it )
}
}
return binding.root
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ElementDescriptionPage.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ElementDescriptionPage().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
kotlin-chat/src/main/kotlin/com/example/demo/app/Styles.kt | 781067901 | package com.example.demo.app
import javafx.scene.text.FontWeight
import tornadofx.Stylesheet
import tornadofx.box
import tornadofx.cssclass
import tornadofx.px
class Styles : Stylesheet() {
companion object {
val heading by cssclass()
}
init {
label {
padding = box(10.px)
fontSize = 20.px
fontWeight = FontWeight.BOLD
}
heading {
fontSize = 45.px
fontWeight = FontWeight.EXTRA_BOLD
}
}
} |
kotlin-chat/src/main/kotlin/com/example/demo/app/MyApp.kt | 3054394858 | package com.example.demo.app
import com.example.demo.view.MainView
import tornadofx.App
class MyApp: App(MainView::class, Styles::class) {
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.