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

Factor out job cards into Composables for new data entry points #2892

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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 @@ -114,7 +114,7 @@ class SurveyRunnerTest : AutomatorRunner {
private fun zoomIntoLocation() {
clickLocationLock()
allowPermissions()
val loiCardSelector = byClass(CardView::class).hasDescendant(byText(R.string.collect_data))
val loiCardSelector = byClass(CardView::class).hasDescendant(byText(R.string.add_data))
if (device.wait(Until.hasObject(loiCardSelector), LONG_TIMEOUT) == null) {
captureScreenshot()
fail("Failed to zoom in to location.")
Expand All @@ -130,8 +130,8 @@ class SurveyRunnerTest : AutomatorRunner {
val cards = device.findObjects(loiCardSelector)
cards.forEach { it.swipe(Direction.LEFT, 1F) }
val loiCollectDataButtonSelector =
byText(R.string.collect_data)
.hasAncestor(loiCardSelector.hasDescendant(byText(R.string.new_site)))
byText(R.string.add_data)
.hasAncestor(loiCardSelector.hasDescendant(byText(R.string.add_site)))
if (!waitClickGone(loiCollectDataButtonSelector)) {
captureScreenshot()
fail("Failed to start ad-hoc loi data collection.")
Expand All @@ -145,7 +145,7 @@ class SurveyRunnerTest : AutomatorRunner {
fail("Failed to find predefined loi card")
}
// Assume that the first card is the predefined LOI.
val loiCollectDataButtonSelector = byText(R.string.collect_data)
val loiCollectDataButtonSelector = byText(R.string.add_data)
if (!waitClickGone(loiCollectDataButtonSelector)) {
captureScreenshot()
fail("Failed to start predefined loi data collection.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,18 @@ import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.ComposeView
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SnapHelper
import com.google.android.ground.R
import com.google.android.ground.coroutines.ApplicationScope
import com.google.android.ground.coroutines.IoDispatcher
import com.google.android.ground.coroutines.MainDispatcher
import com.google.android.ground.databinding.BasemapLayoutBinding
import com.google.android.ground.databinding.LoiCardsRecyclerViewBinding
import com.google.android.ground.databinding.MenuButtonBinding
import com.google.android.ground.model.locationofinterest.LOI_NAME_PROPERTY
import com.google.android.ground.model.locationofinterest.LocationOfInterest
import com.google.android.ground.proto.Survey.DataSharingTerms
import com.google.android.ground.repository.SubmissionRepository
import com.google.android.ground.repository.UserRepository
Expand All @@ -47,8 +40,8 @@ import com.google.android.ground.ui.common.EphemeralPopups
import com.google.android.ground.ui.home.DataSharingTermsDialog
import com.google.android.ground.ui.home.HomeScreenFragmentDirections
import com.google.android.ground.ui.home.HomeScreenViewModel
import com.google.android.ground.ui.home.mapcontainer.cards.MapCardAdapter
import com.google.android.ground.ui.home.mapcontainer.cards.MapCardUiData
import com.google.android.ground.ui.home.mapcontainer.jobs.JobMapAdapter
import com.google.android.ground.ui.home.mapcontainer.jobs.DataCollectionEntryPointData
import com.google.android.ground.ui.map.MapFragment
import com.google.android.ground.ui.theme.AppTheme
import dagger.hilt.android.AndroidEntryPoint
Expand All @@ -59,7 +52,7 @@ import kotlinx.coroutines.flow.cancellable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.runBlocking
import timber.log.Timber

/** Main app view, displaying the map and related controls (center cross-hairs, add button, etc). */
Expand All @@ -76,54 +69,53 @@ class HomeScreenMapContainerFragment : AbstractMapContainerFragment() {
private lateinit var mapContainerViewModel: HomeScreenMapContainerViewModel
private lateinit var homeScreenViewModel: HomeScreenViewModel
private lateinit var binding: BasemapLayoutBinding
private lateinit var adapter: MapCardAdapter
private lateinit var adapter: JobMapAdapter
private lateinit var infoPopup: EphemeralPopups.InfoPopup

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mapContainerViewModel = getViewModel(HomeScreenMapContainerViewModel::class.java)
homeScreenViewModel = getViewModel(HomeScreenViewModel::class.java)
adapter = MapCardAdapter { loi, view -> updateSubmissionCount(loi, view) }
adapter = JobMapAdapter { loi -> submissionRepository.getTotalSubmissionCount(loi) }

launchWhenStarted {
val canUserSubmitData = userRepository.canUserSubmitData()

// Handle collect button clicks
adapter.setCollectDataListener { mapCardUiData ->
adapter.setCollectDataListener { mapUiData ->
val job =
lifecycleScope.launch {
mapContainerViewModel.activeSurveyDataSharingTermsFlow.cancellable().collectLatest {
hasDataSharingTerms ->
onCollectData(
canUserSubmitData,
hasValidTasks(mapCardUiData),
hasValidTasks(mapUiData),
hasDataSharingTerms,
mapCardUiData,
mapUiData,
)
}
}
job.cancel()
}

// Bind data for cards
mapContainerViewModel.getMapCardUiData().launchWhenStartedAndCollect { (mapCards, loiCount) ->
adapter.updateData(canUserSubmitData, mapCards, loiCount - 1)
mapContainerViewModel.getMapCardUiData().launchWhenStartedAndCollect { (loiCard, jobCards) ->
sufyanAbbasi marked this conversation as resolved.
Show resolved Hide resolved
runBlocking { adapter.updateData(canUserSubmitData, loiCard, jobCards) }
}
}

map.featureClicks.launchWhenStartedAndCollect { mapContainerViewModel.onFeatureClicked(it) }
}

private fun hasValidTasks(cardUiData: MapCardUiData) =
private fun hasValidTasks(cardUiData: DataCollectionEntryPointData) =
when (cardUiData) {
// LOI tasks are filtered out of the tasks list for pre-defined tasks.
is MapCardUiData.LoiCardUiData ->
cardUiData.loi.job.tasks.values.count { !it.isAddLoiTask } > 0
is MapCardUiData.AddLoiCardUiData -> cardUiData.job.tasks.values.isNotEmpty()
is DataCollectionEntryPointData.SelectedLoiSheetData -> cardUiData.loi.job.tasks.values.count { !it.isAddLoiTask } > 0
is DataCollectionEntryPointData.AdHocDataCollectionButtonData -> cardUiData.job.tasks.values.isNotEmpty()
}

private fun renderDataSharingTermsDialog(
cardUiData: MapCardUiData,
cardUiData: DataCollectionEntryPointData,
dataSharingTerms: DataSharingTerms,
) =
ComposeView(requireContext()).apply {
Expand All @@ -149,7 +141,7 @@ class HomeScreenMapContainerFragment : AbstractMapContainerFragment() {
canUserSubmitData: Boolean,
hasTasks: Boolean,
hasDataSharingTerms: DataSharingTerms?,
cardUiData: MapCardUiData,
cardUiData: DataCollectionEntryPointData,
) {
if (!canUserSubmitData) {
// Skip data collection screen if the user can't submit any data
Expand Down Expand Up @@ -177,17 +169,6 @@ class HomeScreenMapContainerFragment : AbstractMapContainerFragment() {
navigateToDataCollectionFragment(cardUiData)
}

/** Updates the given [TextView] with the submission count for the given [LocationOfInterest]. */
private fun updateSubmissionCount(loi: LocationOfInterest, view: TextView) {
externalScope.launch {
val count = submissionRepository.getTotalSubmissionCount(loi)
val submissionText =
if (count == 0) resources.getString(R.string.no_submissions)
else resources.getQuantityString(R.plurals.submission_count, count, count)
withContext(mainDispatcher) { view.text = submissionText }
}
}

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
Expand All @@ -203,8 +184,8 @@ class HomeScreenMapContainerFragment : AbstractMapContainerFragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupMenuFab()
setupBottomLoiCards()
val menuBinding = setupMenuFab()
setupBottomLoiCards(menuBinding)
showDataCollectionHint()
}

Expand Down Expand Up @@ -249,54 +230,23 @@ class HomeScreenMapContainerFragment : AbstractMapContainerFragment() {
}
}

private fun setupMenuFab() {
private fun setupMenuFab(): MenuButtonBinding {
val mapOverlay = binding.overlay
val menuBinding = MenuButtonBinding.inflate(layoutInflater, mapOverlay, true)
menuBinding.homeScreenViewModel = homeScreenViewModel
menuBinding.lifecycleOwner = this
return menuBinding
}

private fun setupBottomLoiCards() {
val container = binding.bottomContainer
val recyclerViewBinding = LoiCardsRecyclerViewBinding.inflate(layoutInflater, container, true)
val recyclerView = recyclerViewBinding.recyclerView
recyclerView.adapter = adapter
recyclerView.addOnScrollListener(
object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()
val lastVisiblePosition = layoutManager.findLastVisibleItemPosition()
val firstCompletelyVisiblePosition =
layoutManager.findFirstCompletelyVisibleItemPosition()
var midPosition = (firstVisiblePosition + lastVisiblePosition) / 2

// Focus the last card
if (firstCompletelyVisiblePosition > midPosition) {
midPosition = firstCompletelyVisiblePosition
}

adapter.focusItemAtIndex(midPosition)
}
}
)

val helper: SnapHelper = PagerSnapHelper()
helper.attachToRecyclerView(recyclerView)

mapContainerViewModel.loiClicks.launchWhenStartedAndCollect {
val index = it?.let { adapter.getIndex(it) } ?: -1
if (index != -1) {
recyclerView.scrollToPosition(index)
adapter.focusItemAtIndex(index)
}
}
private fun setupBottomLoiCards(menuBinding: MenuButtonBinding) {
adapter.basemapLayoutBinding = binding
adapter.menuBinding = menuBinding
adapter.render()
}

private fun navigateToDataCollectionFragment(cardUiData: MapCardUiData) {
private fun navigateToDataCollectionFragment(cardUiData: DataCollectionEntryPointData) {
when (cardUiData) {
is MapCardUiData.LoiCardUiData ->
is DataCollectionEntryPointData.SelectedLoiSheetData ->
findNavController()
.navigate(
HomeScreenFragmentDirections.actionHomeScreenFragmentToDataCollectionFragment(
Expand All @@ -308,7 +258,7 @@ class HomeScreenMapContainerFragment : AbstractMapContainerFragment() {
"",
)
)
is MapCardUiData.AddLoiCardUiData ->
is DataCollectionEntryPointData.AdHocDataCollectionButtonData ->
findNavController()
.navigate(
HomeScreenFragmentDirections.actionHomeScreenFragmentToDataCollectionFragment(
Expand All @@ -326,13 +276,7 @@ class HomeScreenMapContainerFragment : AbstractMapContainerFragment() {
override fun onMapReady(map: MapFragment) {
mapContainerViewModel.mapLoiFeatures.launchWhenStartedAndCollect { map.setFeatures(it) }

adapter.setLoiCardFocusedListener {
when (it) {
is MapCardUiData.LoiCardUiData -> mapContainerViewModel.selectLocationOfInterest(it.loi.id)
is MapCardUiData.AddLoiCardUiData,
null -> mapContainerViewModel.selectLocationOfInterest(null)
}
}
adapter.setSelectedFeature { mapContainerViewModel.selectLocationOfInterest(it) }
}

override fun getMapViewModel(): BaseMapViewModel = mapContainerViewModel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import com.google.android.ground.system.PermissionsManager
import com.google.android.ground.system.SettingsManager
import com.google.android.ground.ui.common.BaseMapViewModel
import com.google.android.ground.ui.common.SharedViewModel
import com.google.android.ground.ui.home.mapcontainer.cards.MapCardUiData
import com.google.android.ground.ui.home.mapcontainer.jobs.DataCollectionEntryPointData
import com.google.android.ground.ui.map.Feature
import com.google.android.ground.ui.map.FeatureType
import com.google.android.ground.ui.map.isLocationOfInterest
Expand Down Expand Up @@ -110,8 +110,8 @@ internal constructor(
*/
private val loisInViewport: StateFlow<List<LocationOfInterest>>

/** [LocationOfInterest] clicked by the user. */
val loiClicks: MutableStateFlow<LocationOfInterest?> = MutableStateFlow(null)
/** [Feature] clicked by the user. */
val featureClicked: MutableStateFlow<Feature?> = MutableStateFlow(null)

/**
* List of [Job]s which allow LOIs to be added during field collection, populated only when zoomed
Expand Down Expand Up @@ -178,15 +178,22 @@ internal constructor(
}

/**
* Returns a flow of [MapCardUiData] associated with the active survey's LOIs and adhoc jobs for
* Returns a flow of [DataCollectionEntryPointData] associated with the active survey's LOIs and adhoc jobs for
* displaying the cards.
*/
fun getMapCardUiData(): Flow<Pair<List<MapCardUiData>, Int>> =
loisInViewport.combine(adHocLoiJobs) { lois, jobs ->
val loiCards = lois.map { MapCardUiData.LoiCardUiData(it) }
val jobCards = jobs.map { MapCardUiData.AddLoiCardUiData(it) }

Pair(loiCards + jobCards, lois.size)
fun getMapCardUiData(): Flow<Pair<DataCollectionEntryPointData.SelectedLoiSheetData?, List<DataCollectionEntryPointData.AdHocDataCollectionButtonData>>> =
combine(loisInViewport, featureClicked, adHocLoiJobs) { loisInView, feature, jobs ->
val loiCard =
loisInView
.filter { it.geometry == feature?.geometry }
.firstOrNull()
?.let { DataCollectionEntryPointData.SelectedLoiSheetData(it) }
if (loiCard == null && feature != null) {
// The feature is not in view anymore.
featureClicked.value = null
}
val jobCard = jobs.map { DataCollectionEntryPointData.AdHocDataCollectionButtonData(it) }
Pair(loiCard, jobCard)
}

private fun updatedLoiSelectedStates(
Expand All @@ -204,12 +211,7 @@ internal constructor(
* list of provided features is empty.
*/
fun onFeatureClicked(features: Set<Feature>) {
val geometry = features.map { it.geometry }.minByOrNull { it.area } ?: return
for (loi in loisInViewport.value) {
if (loi.geometry == geometry) {
loiClicks.value = loi
}
}
featureClicked.value = features.minByOrNull { it.geometry.area }
}

suspend fun updateDataSharingConsent(dataSharingTerms: Boolean) {
Expand Down Expand Up @@ -242,5 +244,8 @@ internal constructor(

fun selectLocationOfInterest(id: String?) {
selectedLoiIdFlow.value = id
if (id == null) {
featureClicked.value = null
}
}
}
Loading
Loading