Add widget picker search screen.

This adds the search screen and view model logic. 

It uses the same composable structure as the landing screen.

Bug: 408283627
Flag: EXEMPT independent module
Test: Unit tests
Change-Id: Ic83090be21b31a4f1b416284f78d5a05d5cd2cdc
This commit is contained in:
Shamali Patwa committed 2025-05-23 12:12:27 -07:00
1 parent e7e3a14e95
commit df07059bd4
8 files changed
+768 -2

No files matched your search

+9
View File
@@ -42,6 +42,10 @@ android_library {
static_libs: [
"dagger2",
"widget_picker_dagger_annotations",
"widget_picker_data_repositories",
"widget_picker_shared_data_types",
"widget_picker_domain_layer",
"widget_picker_ui",
],
}
@@ -163,10 +167,15 @@ android_library {
min_sdk_version: min_launcher3_sdk_version,
srcs: [
"src/com/android/launcher3/widgetpicker/ui/ViewModel.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/FullWidgetsCatalog.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/FullWidgetsCatalogViewModel.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/screens/landing/LandingScreen.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/screens/landing/LandingScreenSinglePane.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/screens/landing/LandingScreenTwoPane.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/screens/landing/LandingScreenViewModel.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/screens/search/SearchScreen.kt",
"src/com/android/launcher3/widgetpicker/ui/fullcatalog/screens/search/SearchScreenViewModel.kt",
"src/com/android/launcher3/widgetpicker/ui/WidgetPickerEventListeners.kt",
],
static_libs: [
"widget_picker_ui_components",
@@ -168,6 +168,12 @@ private object DragHandleDimens {
val dragHandleWidth = 32.dp
}
/** Default values for the [TitledBottomSheet] component. */
object TitledBottomSheetDefaults {
/** Animation duration for the bottom sheet to fully expand. */
const val SLIDE_IN_ANIMATION_DURATION: Long = 400L
}
/**
* Describes how should the default height of the bottom sheet look like (excluding the insets such
* as status bar).
@@ -53,6 +53,7 @@ import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
@@ -92,6 +93,7 @@ fun WidgetsSearchBar(
val interactionSource = remember { MutableInteractionSource() }
val focusRequester = remember { FocusRequester() }
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
val exitSearchMode = {
onSearch("")
@@ -114,7 +116,10 @@ fun WidgetsSearchBar(
singleLine = true,
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { onSearch(text) }),
keyboardActions = KeyboardActions(onSearch = {
keyboardController?.hide()
onSearch(text)
}),
interactionSource = interactionSource,
textStyle = WidgetsSearchBarDefaults.textStyle,
decorationBox =
@@ -214,7 +219,7 @@ private fun BackButton(onClick: () -> Unit) {
IconButton(colors = WidgetsSearchBarDefaults.iconButtonColors, onClick = onClick) {
Icon(
imageVector = Icons.AutoMirrored.Outlined.ArrowBack,
contentDescription = stringResource(R.string.widget_search_bar_clear_button_label),
contentDescription = stringResource(R.string.widget_search_bar_back_button_label),
)
}
}
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.widgetpicker.ui.fullcatalog
import androidx.compose.material3.windowsizeclass.WindowHeightSizeClass
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import com.android.launcher3.widgetpicker.WidgetPickerEventListeners
import com.android.launcher3.widgetpicker.ui.components.ModalBottomSheetHeightStyle
import com.android.launcher3.widgetpicker.ui.components.TitledBottomSheet
import com.android.launcher3.widgetpicker.ui.components.TitledBottomSheetDefaults
import com.android.launcher3.widgetpicker.ui.fullcatalog.FullWidgetsCatalogViewModel.Screen
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.landing.LandingScreen
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.search.SearchScreen
import com.android.launcher3.widgetpicker.ui.rememberViewModel
import com.android.launcher3.widgetpicker.ui.windowsizeclass.calculateWindowInfo
import javax.inject.Inject
/**
* A catalog of all widgets available on device.
*
* When opened, first shows a landing page that comprises of the featured widgets and the list of
* apps hosting widgets. User can enter search mode by tapping the search bar and see matching
* results.
*
*/
class FullWidgetsCatalog @Inject constructor(
private val viewModelFactory: FullWidgetsCatalogViewModel.Factory,
) {
@Composable
fun Content(
eventListeners: WidgetPickerEventListeners,
) {
val viewModel: FullWidgetsCatalogViewModel =
rememberViewModel(
animationDelay = TitledBottomSheetDefaults.SLIDE_IN_ANIMATION_DURATION
) {
viewModelFactory.create()
}
val windowInfo = LocalConfiguration.current.calculateWindowInfo()
val isCompactWidth =
windowInfo.windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact
val isCompactHeight =
windowInfo.windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact
TitledBottomSheet(
title = viewModel.title.takeIf { !isCompactHeight },
modifier = Modifier,
description = null,
heightStyle = ModalBottomSheetHeightStyle.FILL_HEIGHT,
showDragHandle = true,
onDismissRequest = { eventListeners.onClose() },
) {
when (viewModel.activeScreen) {
Screen.LANDING -> {
LandingScreen(
isCompact = isCompactWidth,
onEnterSearchMode = { viewModel.onActiveScreenChange(Screen.SEARCH) },
viewModel = viewModel.landingScreenViewModel,
)
}
Screen.SEARCH -> {
SearchScreen(
isCompact = isCompactWidth,
onExitSearchMode = { viewModel.onActiveScreenChange(Screen.LANDING) },
viewModel = viewModel.searchScreenViewModel,
)
}
}
}
}
}
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.widgetpicker.ui.fullcatalog
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.android.launcher3.widgetpicker.WidgetPickerHostInfo
import com.android.launcher3.widgetpicker.shared.model.WidgetHostInfo
import com.android.launcher3.widgetpicker.ui.ViewModel
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.landing.LandingScreenViewModel
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.search.SearchScreenViewModel
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/**
* Top-level view model for the widget picker view that shows a full catalog of widgets available
* on the device.
*/
class FullWidgetsCatalogViewModel @AssistedInject constructor(
landingScreenViewModelFactory: LandingScreenViewModel.Factory,
searchScreenViewModelFactory: SearchScreenViewModel.Factory,
@WidgetPickerHostInfo private val hostInfo: WidgetHostInfo,
) : ViewModel {
val landingScreenViewModel = landingScreenViewModelFactory.create()
val searchScreenViewModel = searchScreenViewModelFactory.create()
val title: String? = hostInfo.title
val description: String? = hostInfo.description
var activeScreen by mutableStateOf(Screen.LANDING)
private set
override suspend fun onInit() {
coroutineScope {
launch { landingScreenViewModel.onInit() }
launch { searchScreenViewModel.onInit() }
awaitCancellation()
}
}
fun onActiveScreenChange(screen: Screen) {
activeScreen = screen
}
@AssistedFactory
interface Factory {
fun create(): FullWidgetsCatalogViewModel
}
enum class Screen {
LANDING,
SEARCH
}
}
@@ -0,0 +1,218 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.widgetpicker.ui.fullcatalog.screens.search
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.android.launcher3.widgetpicker.R
import com.android.launcher3.widgetpicker.shared.model.WidgetAppId
import com.android.launcher3.widgetpicker.ui.components.AppHeaderDescriptionStyle
import com.android.launcher3.widgetpicker.ui.components.SinglePaneLayout
import com.android.launcher3.widgetpicker.ui.components.TwoPaneLayout
import com.android.launcher3.widgetpicker.ui.components.WidgetAppHeaderStyle
import com.android.launcher3.widgetpicker.ui.components.WidgetAppsList
import com.android.launcher3.widgetpicker.ui.components.WidgetsGrid
import com.android.launcher3.widgetpicker.ui.components.WidgetsSearchBar
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.landing.AppIconsState
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.landing.PreviewsState
/**
* Screen showing the search results in the widget picker when browsing the full widget catalog.
*/
@Composable
fun SearchScreen(
isCompact: Boolean,
onExitSearchMode: () -> Unit,
viewModel: SearchScreenViewModel,
) {
SearchScreen(
isCompact = isCompact,
input = viewModel.query,
resultsState = viewModel.resultsState,
selectedWidgetAppId = viewModel.selectedWidgetAppId,
appIconsState = viewModel.appIconsState,
widgetPreviewsState = viewModel.previewsState,
onSearch = viewModel::onQueryChange,
onSelectedWidgetAppToggle = viewModel::onSelectedWidgetAppToggle,
onExitSearchMode = onExitSearchMode,
)
}
@Composable
private fun SearchScreen(
isCompact: Boolean,
input: String,
resultsState: SearchResultsState,
selectedWidgetAppId: WidgetAppId?,
appIconsState: AppIconsState,
widgetPreviewsState: PreviewsState,
onSearch: (String) -> Unit,
onSelectedWidgetAppToggle: (id: WidgetAppId) -> Unit,
onExitSearchMode: () -> Unit,
) {
val searchBar: @Composable () -> Unit = {
WidgetsSearchBar(
text = input,
isSearching = true,
onSearch = onSearch,
onToggleSearchMode = { searchModeEnabled ->
if (!searchModeEnabled) {
onExitSearchMode()
}
},
modifier = Modifier.fillMaxWidth(),
)
}
if (isCompact) {
SearchScreenSinglePane(
searchBar = searchBar,
resultsState = resultsState,
selectedWidgetAppId = selectedWidgetAppId,
appIconsState = appIconsState,
widgetPreviewsState = widgetPreviewsState,
onSelectedWidgetAppChange = onSelectedWidgetAppToggle
)
} else {
SearchScreenTwoPane(
searchBar = searchBar,
resultsState = resultsState,
selectedWidgetAppId = selectedWidgetAppId,
appIconsState = appIconsState,
widgetPreviewsState = widgetPreviewsState,
onSelectedWidgetAppChange = onSelectedWidgetAppToggle
)
}
}
@Composable
private fun SearchScreenSinglePane(
searchBar: @Composable () -> Unit,
resultsState: SearchResultsState,
selectedWidgetAppId: WidgetAppId?,
appIconsState: AppIconsState,
widgetPreviewsState: PreviewsState,
onSelectedWidgetAppChange: (id: WidgetAppId) -> Unit
) {
SinglePaneLayout(
searchBar = searchBar,
content = {
Box(modifier = Modifier.fillMaxSize()) {
WidgetAppsList(
modifier = Modifier.fillMaxSize(),
widgetApps = resultsState.results,
selectedWidgetAppId = selectedWidgetAppId,
widgetAppHeaderStyle = WidgetAppHeaderStyle.EXPANDABLE,
headerDescriptionStyle = AppHeaderDescriptionStyle.COMBINED_WIDGETS_TITLE,
onWidgetAppClick = { widgetApp ->
onSelectedWidgetAppChange(widgetApp.id)
},
appIcons = appIconsState.icons,
widgetPreviews = widgetPreviewsState.previews
)
}
}
)
}
@Composable
fun SearchScreenTwoPane(
searchBar: @Composable () -> Unit,
resultsState: SearchResultsState,
selectedWidgetAppId: WidgetAppId?,
appIconsState: AppIconsState,
widgetPreviewsState: PreviewsState,
onSelectedWidgetAppChange: (id: WidgetAppId) -> Unit
) {
TwoPaneLayout(
searchBar = searchBar,
leftContent = {
Box(modifier = Modifier.fillMaxSize()) {
WidgetAppsList(
modifier = Modifier.fillMaxSize(),
widgetApps = resultsState.results,
selectedWidgetAppId = selectedWidgetAppId,
widgetAppHeaderStyle = WidgetAppHeaderStyle.CLICKABLE,
headerDescriptionStyle = AppHeaderDescriptionStyle.COMBINED_WIDGETS_TITLE,
appIcons = appIconsState.icons,
widgetPreviews = widgetPreviewsState.previews,
onWidgetAppClick = { widgetApp ->
onSelectedWidgetAppChange(widgetApp.id)
},
)
}
},
rightPaneTitle = rightPaneTitle(
resultsState = resultsState,
selectedWidgetAppId = selectedWidgetAppId,
),
rightContent = {
selectedWidgetAppId?.let { id ->
val selectedWidgets =
remember(id, resultsState) {
id.let { selectedId ->
resultsState.results.find {
it.id == selectedId
}?.widgetSizeGroups
} ?: listOf()
}
WidgetsGrid(
modifier = Modifier
.fillMaxWidth()
.wrapContentSize()
.verticalScroll(rememberScrollState()),
showAllWidgetDetails = true,
widgetSizeGroups = selectedWidgets,
previews = widgetPreviewsState.previews,
appIcons = appIconsState.icons
)
}
},
)
}
/**
* Title for the right pane that is updated when selected tab on left changes. When set, a talkback
* user can use four finger swipe down to switch to right pane.
*/
@Composable
private fun rightPaneTitle(
resultsState: SearchResultsState,
selectedWidgetAppId: WidgetAppId?
): String? {
val selectedAppName: CharSequence? =
selectedWidgetAppId?.let { selectedId ->
resultsState.results.find { it.id == selectedId }?.title
}
return if (selectedAppName != null) {
stringResource(
R.string.widget_picker_right_pane_accessibility_label,
selectedAppName
)
} else {
null
}
}
@@ -0,0 +1,155 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.widgetpicker.ui.fullcatalog.screens.search
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import com.android.launcher3.widgetpicker.domain.interactor.WidgetAppIconsInteractor
import com.android.launcher3.widgetpicker.domain.interactor.WidgetsInteractor
import com.android.launcher3.widgetpicker.shared.model.WidgetAppId
import com.android.launcher3.widgetpicker.ui.ViewModel
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.landing.AppIconsState
import com.android.launcher3.widgetpicker.ui.fullcatalog.screens.landing.PreviewsState
import com.android.launcher3.widgetpicker.ui.model.DisplayableWidgetApp
import com.android.launcher3.widgetpicker.ui.model.DisplayableWidgetApp.Companion.getWidgetIdsForApp
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
/**
* View model for the search screen that allows searching for all widgets in the full catalog view
* of the widget picker.
*/
class SearchScreenViewModel @AssistedInject constructor(
private val widgetsInteractor: WidgetsInteractor,
private val widgetAppIconsInteractor: WidgetAppIconsInteractor
) : ViewModel {
/** Data backing the results (widget apps & their widgets) that match the provided input. */
var resultsState by mutableStateOf(SearchResultsState())
private set
/** Current query that is input in search bar by the user. */
var query by mutableStateOf("")
private set
/** Data about all app icons shown on search screen. */
var appIconsState by mutableStateOf(AppIconsState())
private set
/**
* Id of the app that is currently selected / expanded in search results. When null, implies
* none of the apps is expanded.
*/
var selectedWidgetAppId by mutableStateOf<WidgetAppId?>(null)
private val _selectedWidgetAppWidgetIds = snapshotFlow {
selectedWidgetAppId?.let {
resultsState.results.getWidgetIdsForApp(it)
} ?: listOf()
}
/** Preview information about the widgets in the search results. */
var previewsState by mutableStateOf(PreviewsState())
private set
override suspend fun onInit() {
coroutineScope {
launch { initializeSearchResults() }
launch { initAppIcons() }
launch { initialWidgetPreviews() }
}
}
private suspend fun initializeSearchResults() {
snapshotFlow { query }.collectLatest { newInput ->
if (newInput.isEmpty()) {
resultsState = SearchResultsState()
} else {
widgetsInteractor.searchWidgetApps(query).collectLatest { matchedResults ->
resultsState = SearchResultsState(
results = matchedResults.map { DisplayableWidgetApp.fromWidgetApp(it) }
)
}
}
}
awaitCancellation()
}
private suspend fun initAppIcons() {
widgetAppIconsInteractor.getAllWidgetAppIcons().collect { result ->
appIconsState = AppIconsState(icons = result)
}
awaitCancellation()
}
private suspend fun initialWidgetPreviews() {
_selectedWidgetAppWidgetIds.collect { ids ->
previewsState =
PreviewsState(
previewsState.previews +
ids.associateWith { widgetsInteractor.getWidgetPreview(it) })
}
awaitCancellation()
}
/**
* Callback for when user types a search query and its changed. Updates the [query] state
* so that the search results can update as well.
*/
fun onQueryChange(query: String) {
this.query = query
}
/**
* Callback to handle the visibility toggle of a widget app in search results; e.g. when user
* clicks an app to expand or collapse.
*
* @param id id of the widget app that was tapped; if its same as last id that was tapped, the
* [selectedWidgetAppId] is reset to null (aka toggled); if its different, then the provided id
* is set as the [selectedWidgetAppId]. To clear the [selectedWidgetAppId] invoke this with
* `null`
*/
fun onSelectedWidgetAppToggle(id: WidgetAppId) {
selectedWidgetAppId = if (selectedWidgetAppId != id) {
id
} else {
null
}
}
/** A factory that should be injected whenever [SearchScreenViewModel] is required. */
@AssistedFactory
interface Factory {
fun create(): SearchScreenViewModel
}
}
/** Represents data that backs the list of widget apps (and their widgets) shown in the results. */
@Stable
@Immutable
data class SearchResultsState(
val results: List<DisplayableWidgetApp> = emptyList()
)
@@ -0,0 +1,212 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.widgetpicker.ui.fullcatalog.screens.search
import android.platform.test.rule.AllowedDevices
import android.platform.test.rule.DeviceProduct
import android.platform.test.rule.LimitDevicesRule
import androidx.activity.ComponentActivity
import androidx.compose.runtime.Composable
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.android.launcher3.widgetpicker.R
import com.android.launcher3.widgetpicker.TestUtils
import com.android.launcher3.widgetpicker.TestUtils.PERSONAL_TEST_APPS
import com.android.launcher3.widgetpicker.TestUtils.WORK_TEST_APPS
import com.android.launcher3.widgetpicker.TestUtils.workUser
import com.android.launcher3.widgetpicker.domain.interactor.WidgetAppIconsInteractor
import com.android.launcher3.widgetpicker.domain.interactor.WidgetsInteractor
import com.android.launcher3.widgetpicker.domain.usecase.FilterWidgetsForHostUseCase
import com.android.launcher3.widgetpicker.domain.usecase.GroupWidgetAppsByProfileUseCase
import com.android.launcher3.widgetpicker.repository.FakeWidgetAppIconsRepository
import com.android.launcher3.widgetpicker.repository.FakeWidgetUsersRepository
import com.android.launcher3.widgetpicker.repository.FakeWidgetsRepository
import com.android.launcher3.widgetpicker.shared.model.WidgetHostInfo
import com.android.launcher3.widgetpicker.shared.model.WidgetUserProfiles
import com.android.launcher3.widgetpicker.ui.rememberViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@AllowedDevices(allowed = [DeviceProduct.CF_TABLET])
class SearchScreenTest {
@get:Rule
val limitDevicesRule = LimitDevicesRule()
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@OptIn(ExperimentalCoroutinesApi::class)
private val testDispatcher = UnconfinedTestDispatcher()
private val testScope = TestScope(testDispatcher)
private val context = InstrumentationRegistry.getInstrumentation().context
private lateinit var viewModel: SearchScreenViewModel
private val widgetsRepository = FakeWidgetsRepository()
private val widgetAppIconsRepository = FakeWidgetAppIconsRepository()
private val widgetsUsersRepository = FakeWidgetUsersRepository()
private lateinit var searchBarHint: String
private lateinit var clearButtonContentDescription: String
@Before
fun setUp() {
viewModel = SearchScreenViewModel(
widgetsInteractor = WidgetsInteractor(
widgetsRepository = widgetsRepository,
widgetUsersRepository = widgetsUsersRepository,
filterWidgetsForHostUseCase = FilterWidgetsForHostUseCase(WidgetHostInfo()),
getWidgetAppsByProfileUseCase = GroupWidgetAppsByProfileUseCase(),
backgroundContext = testDispatcher,
),
widgetAppIconsInteractor = WidgetAppIconsInteractor(
widgetAppIconsRepository = widgetAppIconsRepository,
widgetsRepository = widgetsRepository,
backgroundContext = testDispatcher
),
)
searchBarHint = context.applicationContext.resources.getString(
R.string.widgets_search_bar_hint
)
clearButtonContentDescription =
context.applicationContext.resources.getString(R.string.widget_search_bar_clear_button_label)
widgetsRepository.seedWidgets(PERSONAL_TEST_APPS + WORK_TEST_APPS)
widgetsUsersRepository.seedUserProfiles(
WidgetUserProfiles(
personal = TestUtils.widgetUserProfilePersonal,
work = TestUtils.widgetUserProfileWork
),
workProfileUser = workUser
)
}
@Composable
private fun TestContent(isCompact: Boolean) {
val viewModel = rememberViewModel { viewModel }
SearchScreen(
isCompact = isCompact,
onExitSearchMode = {},
viewModel = viewModel,
)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun singlePane_showMatchingApps() = testScope.runTest {
composeTestRule.setContent {
TestContent(
isCompact = true
)
}
runCurrent()
composeTestRule.waitForIdle()
val testInputOne = "PersonalWidget"
composeTestRule.onNodeWithText(searchBarHint)
.performTextInput(testInputOne)
runCurrent()
composeTestRule.waitForIdle()
// has both apps
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[0].title!!.toString()))
.assertExists()
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[1].title!!.toString()))
.assertExists()
composeTestRule
.onNodeWithContentDescription(clearButtonContentDescription)
.performClick()
runCurrent()
composeTestRule.waitForIdle()
// change query
val testInputTwo = "PersonalWidget1A"
composeTestRule.onNodeWithText(searchBarHint).performTextInput(testInputTwo)
runCurrent()
composeTestRule.waitForIdle()
// has only app 1
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[0].title!!.toString()))
.assertExists()
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[1].title!!.toString()))
.assertDoesNotExist()
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun twoPane_showMatchingApps() = testScope.runTest {
composeTestRule.setContent {
TestContent(
isCompact = false
)
}
runCurrent()
composeTestRule.waitForIdle()
val testInputOne = "PersonalWidget"
composeTestRule.onNodeWithText(searchBarHint)
.performTextInput(testInputOne)
runCurrent()
composeTestRule.waitForIdle()
// has both apps
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[0].title!!.toString()))
.assertExists()
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[1].title!!.toString()))
.assertExists()
composeTestRule
.onNodeWithContentDescription(clearButtonContentDescription)
.performClick()
runCurrent()
composeTestRule.waitForIdle()
// change query
val testInputTwo = "PersonalWidget1A"
composeTestRule.onNodeWithText(searchBarHint).performTextInput(testInputTwo)
runCurrent()
composeTestRule.waitForIdle()
// has only app 1
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[0].title!!.toString()))
.assertExists()
composeTestRule.onNode(hasText(PERSONAL_TEST_APPS[1].title!!.toString()))
.assertDoesNotExist()
}
}