Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for select multiple request. #1130

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ internal class HttpTransactionDatabaseRepository(private val database: ChuckerDa
transactionDao.deleteAll()
}

override suspend fun deleteSelectedTransactions(selectedTransactions: List<Long>) {
transactionDao.deleteSelected(selectedTransactions)
}

override suspend fun insertTransaction(transaction: HttpTransaction) {
val id = transactionDao.insert(transaction)
transaction.id = id ?: 0
Expand All @@ -57,4 +61,8 @@ internal class HttpTransactionDatabaseRepository(private val database: ChuckerDa
val timestamp = minTimestamp ?: 0L
return transactionDao.getTransactionsInTimeRange(timestamp)
}

override suspend fun getSelectedTransactions(selectedTransactions: List<Long>): List<HttpTransaction> {
return transactionDao.getSelectedTransactions(selectedTransactions)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import com.chuckerteam.chucker.internal.data.entity.HttpTransactionTuple
* with [HttpTransaction] and [HttpTransactionTuple]. Please use [HttpTransactionDatabaseRepository] that
* uses Room and SqLite to run those operations.
*/
@Suppress("TooManyFunctions")
internal interface HttpTransactionRepository {
suspend fun insertTransaction(transaction: HttpTransaction)

Expand All @@ -18,6 +19,8 @@ internal interface HttpTransactionRepository {

suspend fun deleteAllTransactions()

suspend fun deleteSelectedTransactions(selectedTransactions: List<Long>)

fun getSortedTransactionTuples(): LiveData<List<HttpTransactionTuple>>

fun getFilteredTransactionTuples(
Expand All @@ -30,4 +33,6 @@ internal interface HttpTransactionRepository {
suspend fun getAllTransactions(): List<HttpTransaction>

fun getTransactionsInTimeRange(minTimestamp: Long?): List<HttpTransaction>

suspend fun getSelectedTransactions(selectedTransactions: List<Long>): List<HttpTransaction>
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import androidx.room.Update
import com.chuckerteam.chucker.internal.data.entity.HttpTransaction
import com.chuckerteam.chucker.internal.data.entity.HttpTransactionTuple

@Suppress("TooManyFunctions")
@Dao
internal interface HttpTransactionDao {
@Query(
Expand Down Expand Up @@ -39,6 +40,9 @@ internal interface HttpTransactionDao {
@Query("DELETE FROM transactions")
suspend fun deleteAll(): Int

@Query("DELETE FROM transactions WHERE id IN (:selectedTransactions)")
suspend fun deleteSelected(selectedTransactions: List<Long>)

@Query("SELECT * FROM transactions WHERE id = :id")
fun getById(id: Long): LiveData<HttpTransaction?>

Expand All @@ -48,6 +52,9 @@ internal interface HttpTransactionDao {
@Query("SELECT * FROM transactions")
suspend fun getAll(): List<HttpTransaction>

@Query("SELECT * FROM transactions WHERE id IN (:selectedTransactions)")
suspend fun getSelectedTransactions(selectedTransactions: List<Long>): List<HttpTransaction>

@Query("SELECT * FROM transactions WHERE requestDate >= :timestamp")
fun getTransactionsInTimeRange(timestamp: Long): List<HttpTransaction>
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ internal class MainActivity :

private lateinit var mainBinding: ChuckerActivityMainBinding
private lateinit var transactionsAdapter: TransactionAdapter
private var isMultipleSelected = false

private val applicationName: CharSequence
get() = applicationInfo.loadLabel(packageManager)
Expand All @@ -67,9 +68,19 @@ internal class MainActivity :

mainBinding = ChuckerActivityMainBinding.inflate(layoutInflater)
transactionsAdapter =
TransactionAdapter(this) { transactionId ->
TransactionActivity.start(this, transactionId)
}
TransactionAdapter(
context = this,
longPress = { transactionId ->
viewModel.selectItem(transactionId)
},
onTransactionClick = { transactionId ->
if (isMultipleSelected) {
viewModel.selectItem(transactionId)
} else {
TransactionActivity.start(this, transactionId)
}
},
)

with(mainBinding) {
setContentView(root)
Expand Down Expand Up @@ -99,6 +110,9 @@ internal class MainActivity :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
handleNotificationsPermission()
}
viewModel.isItemSelected.observe(this) {
isMultipleSelected = it
}
}

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
Expand Down Expand Up @@ -150,14 +164,21 @@ internal class MainActivity :
getClearDialogData(),
onPositiveClick = {
viewModel.clearTransactions()
resetSelection()
},
onNegativeClick = null,
)
true
}
R.id.share_text -> {
showDialog(
getExportDialogData(R.string.chucker_export_text_http_confirmation),
getExportDialogData(
if (viewModel.isItemSelected.value == true) {
R.string.chucker_export_text_selected_http_confirmation
} else {
R.string.chucker_export_text_http_confirmation
},
),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because of this, the function is now getting too long and letting detekt fail:


> Task :library:detekt
/home/runner/work/chucker/chucker/library/src/main/kotlin/com/chuckerteam/chucker/internal/ui/MainActivity.kt:161:18: The function onOptionsItemSelected is too long (60). The maximum length is 60. [LongMethod]

You can see it in the CI signal.

Can you export this + lines 193/199 to separate functions

onPositiveClick = {
exportTransactions(EXPORT_TXT_FILE_NAME) { transactions ->
TransactionListDetailsSharable(transactions, encodeUrls = false)
Expand All @@ -169,7 +190,13 @@ internal class MainActivity :
}
R.id.share_har -> {
showDialog(
getExportDialogData(R.string.chucker_export_har_http_confirmation),
getExportDialogData(
if (viewModel.isItemSelected.value == true) {
R.string.chucker_export_har_selected_http_confirmation
} else {
R.string.chucker_export_har_http_confirmation
},
),
onPositiveClick = {
exportTransactions(EXPORT_HAR_FILE_NAME) { transactions ->
TransactionDetailsHarSharable(
Expand All @@ -191,13 +218,27 @@ internal class MainActivity :
}
}

override fun onSaveInstanceState(outState: Bundle) {
outState.putIntArray("selectedItems", (transactionsAdapter.getSelectedItem().toIntArray()));
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
val itemList = savedInstanceState.getIntArray("selectedItems")
transactionsAdapter.setSelectedItem(itemList?.toList() ?: emptyList())
}

override fun onQueryTextSubmit(query: String): Boolean = true

override fun onQueryTextChange(newText: String): Boolean {
viewModel.updateItemsFilter(newText)
return true
}

private fun resetSelection() {
transactionsAdapter.clearSelections()
}

private fun exportTransactions(
fileName: String,
block: suspend (List<HttpTransaction>) -> Sharable,
Expand All @@ -224,15 +265,26 @@ internal class MainActivity :
if (shareIntent != null) {
startActivity(shareIntent)
} else {
showToast(applicationContext.getString(R.string.chucker_export_no_file))
showToast(
applicationContext.getString(
R.string.chucker_export_no_file,
),
)
}
}
}

private fun getClearDialogData(): DialogData =
DialogData(
title = getString(R.string.chucker_clear),
message = getString(R.string.chucker_clear_http_confirmation),
message =
getString(
if (viewModel.isItemSelected.value == true) {
R.string.chucker_clear_selected_http_confirmation
} else {
R.string.chucker_clear_http_confirmation
},
),
positiveButtonText = getString(R.string.chucker_clear),
negativeButtonText = getString(R.string.chucker_cancel),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.chuckerteam.chucker.internal.data.entity.HttpTransaction
Expand All @@ -14,6 +15,11 @@ import kotlinx.coroutines.launch

internal class MainViewModel : ViewModel() {
private val currentFilter = MutableLiveData("")
private val selectedItemId: MutableLiveData<MutableList<Long>> =
MutableLiveData<MutableList<Long>>(mutableListOf())

private var _isItemSelected = MutableLiveData<Boolean>(false)
val isItemSelected = _isItemSelected.distinctUntilChanged()

val transactions: LiveData<List<HttpTransactionTuple>> =
currentFilter.switchMap { searchQuery ->
Expand All @@ -32,15 +38,38 @@ internal class MainViewModel : ViewModel() {
}
}

suspend fun getAllTransactions(): List<HttpTransaction> = RepositoryProvider.transaction().getAllTransactions()
fun selectItem(itemId: Long) {
viewModelScope.launch {
if (selectedItemId.value?.contains(itemId) == true) {
selectedItemId.value?.remove(itemId)
_isItemSelected.value = selectedItemId.value.isNullOrEmpty().not() == true
} else {
selectedItemId.value?.add(itemId)
_isItemSelected.value = true
}
}
}

suspend fun getAllTransactions(): List<HttpTransaction> {
return if (isItemSelected.value == true) {
RepositoryProvider.transaction().getSelectedTransactions(selectedItemId.value!!)
} else {
RepositoryProvider.transaction().getAllTransactions()
}
}

fun updateItemsFilter(searchQuery: String) {
currentFilter.value = searchQuery
}

fun clearTransactions() {
viewModelScope.launch {
RepositoryProvider.transaction().deleteAllTransactions()
if (isItemSelected.value == true) {
_isItemSelected.value = false
RepositoryProvider.transaction().deleteSelectedTransactions(selectedItemId.value!!)
} else {
RepositoryProvider.transaction().deleteAllTransactions()
}
}
NotificationHelper.clearBuffer()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.chuckerteam.chucker.internal.ui.transaction
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
Expand All @@ -22,9 +23,14 @@ import javax.net.ssl.HttpsURLConnection
internal class TransactionAdapter internal constructor(
context: Context,
private val onTransactionClick: (Long) -> Unit,
) : ListAdapter<HttpTransactionTuple, TransactionAdapter.TransactionViewHolder>(
private val longPress: (Long) -> Unit,
) : ListAdapter<
HttpTransactionTuple,
TransactionAdapter.TransactionViewHolder,
>(
TransactionDiffCallback,
) {
private val selectedPos = mutableListOf<Int>()
private val colorDefault: Int = ContextCompat.getColor(context, R.color.chucker_status_default)
private val colorRequested: Int =
ContextCompat.getColor(
Expand All @@ -35,6 +41,32 @@ internal class TransactionAdapter internal constructor(
private val color500: Int = ContextCompat.getColor(context, R.color.chucker_status_500)
private val color400: Int = ContextCompat.getColor(context, R.color.chucker_status_400)
private val color300: Int = ContextCompat.getColor(context, R.color.chucker_status_300)
private val chuckerStatusHighlighted: Int = ContextCompat.getColor(context, R.color.chucker_status_highlighted)
val outValue = TypedValue()

@Suppress("UnusedPrivateProperty")
private val defaultColor =
context.theme.resolveAttribute(
android.R.attr.selectableItemBackground,
outValue,
true,
)

fun getSelectedItem(): List<Int> {
return selectedPos
}

fun setSelectedItem(selectedItem: List<Int>) {
selectedPos.addAll(selectedItem)
}

fun clearSelections() {
val pos = selectedPos
selectedPos.clear()
pos.forEach {
notifyItemRemoved(it)
}
}

override fun onCreateViewHolder(
parent: ViewGroup,
Expand Down Expand Up @@ -63,14 +95,39 @@ internal class TransactionAdapter internal constructor(
itemView.setOnClickListener {
transactionId?.let {
onTransactionClick.invoke(it)
if (selectedPos.isNotEmpty()) {
if (selectedPos.contains(adapterPosition)) {
selectedPos.remove(adapterPosition)
} else {
selectedPos.add(adapterPosition)
}
notifyItemChanged(adapterPosition)
}
}
}

itemView.setOnLongClickListener {
transactionId?.let {
longPress.invoke(it)
if (selectedPos.contains(adapterPosition)) {
selectedPos.remove(adapterPosition)
} else {
selectedPos.add(adapterPosition)
}
notifyItemChanged(adapterPosition)
true
} ?: false
}
}

@SuppressLint("SetTextI18n")
fun bind(transaction: HttpTransactionTuple) {
transactionId = transaction.id

if (selectedPos.find { it == adapterPosition } != null) {
itemView.setBackgroundColor(chuckerStatusHighlighted)
} else {
itemView.setBackgroundResource(outValue.resourceId)
}
itemBinding.apply {
displayGraphQlFields(transaction.graphQlOperationName, transaction.graphQlDetected)
path.text = "${transaction.method} ${transaction.getFormattedPath(encode = false)}"
Expand Down Expand Up @@ -134,6 +191,7 @@ private fun ChuckerListItemTransactionBinding.displayGraphQlFields(
graphqlPath.isVisible = graphQLDetected

if (graphQLDetected) {
graphqlPath.text = graphQlOperationName ?: root.resources.getString(R.string.chucker_graphql_operation_is_empty)
graphqlPath.text = graphQlOperationName
?: root.resources.getString(R.string.chucker_graphql_operation_is_empty)
}
}
2 changes: 2 additions & 0 deletions library/src/main/res/values-night/colors.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
<color name="chucker_background_span_color">#ffe082</color>
<color name="chucker_foreground_span_color">#ef5350</color>

<color name="chucker_status_highlighted">#FF9800</color>

<color name="chucker_json_key_color">#75bec4</color>
<color name="chucker_json_value_color">#9e7162</color>
<color name="chucker_json_digit_and_null_value_color">#669f50</color>
Expand Down
2 changes: 2 additions & 0 deletions library/src/main/res/values/colors.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
<color name="chucker_background_span_color">#ffffff00</color>
<color name="chucker_foreground_span_color">#ffff0000</color>

<color name="chucker_status_highlighted">#FF9800</color>

<color name="chucker_chessboard_even_square_light">#F8FAFC</color>
<color name="chucker_chessboard_odd_square_light">#D2DADF</color>
<color name="chucker_chessboard_even_square_dark">#182531</color>
Expand Down
Loading
Loading