Merge branch 'development/6/implement-full-crud-for-locations-and-labels' into main, accepting all changes from the feature branch

This commit is contained in:
2025-09-05 12:48:28 +03:00
157 changed files with 3841 additions and 9741 deletions

View File

@@ -87,6 +87,10 @@ dependencies {
// [DEPENDENCY] Testing
testImplementation(Libs.junit)
testImplementation(Libs.kotestRunnerJunit5)
testImplementation(Libs.kotestAssertionsCore)
testImplementation(Libs.mockk)
testImplementation("app.cash.turbine:turbine:1.1.0")
androidTestImplementation(Libs.extJunit)
androidTestImplementation(Libs.espressoCore)
androidTestImplementation(platform(Libs.composeBom))

View File

@@ -1,7 +1,6 @@
// [PACKAGE] com.homebox.lens
// [FILE] MainActivity.kt
// [SEMANTICS] android, activity, compose, hilt
// [SEMANTICS] ui, activity, entrypoint
package com.homebox.lens
// [IMPORTS]
@@ -18,33 +17,26 @@ import androidx.compose.ui.tooling.preview.Preview
import com.homebox.lens.navigation.NavGraph
import com.homebox.lens.ui.theme.HomeboxLensTheme
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Activity('MainActivity')]
// [RELATION: Activity('MainActivity') -> [INHERITS_FROM] -> Class('ComponentActivity')]
// [RELATION: Activity('MainActivity') -> [DEPENDS_ON] -> Annotation('AndroidEntryPoint')]
/**
* [ENTITY: Activity('MainActivity')]
* [PURPOSE] Главная и единственная Activity в приложении.
* @summary Главная и единственная Activity в приложении.
*/
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
// [ENTITY: Function('onCreate')]
// [RELATION: Function('onCreate') -> [CALLS] -> Function('super.onCreate')]
// [RELATION: Function('onCreate') -> [CALLS] -> Function('setContent')]
// [RELATION: Function('onCreate') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('onCreate') -> [CALLS] -> Function('Surface')]
// [RELATION: Function('onCreate') -> [CALLS] -> Function('NavGraph')]
// [LIFECYCLE]
// [RELATION: Function('onCreate')] -> [CALLS] -> [Function('HomeboxLensTheme')]
// [RELATION: Function('onCreate')] -> [CALLS] -> [Function('NavGraph')]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.d("[DEBUG][LIFECYCLE][creating_activity] MainActivity created.")
setContent {
HomeboxLensTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
color = MaterialTheme.colorScheme.background
) {
NavGraph()
}
@@ -56,23 +48,16 @@ class MainActivity : ComponentActivity() {
// [END_ENTITY: Activity('MainActivity')]
// [ENTITY: Function('Greeting')]
// [RELATION: Function('Greeting') -> [CALLS] -> Function('Text')]
@Composable
fun Greeting(
name: String,
modifier: Modifier = Modifier,
) {
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier,
modifier = modifier
)
}
// [END_ENTITY: Function('Greeting')]
// [ENTITY: Function('GreetingPreview')]
// [RELATION: Function('GreetingPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('GreetingPreview') -> [CALLS] -> Function('Greeting')]
// [PREVIEW]
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
@@ -82,5 +67,4 @@ fun GreetingPreview() {
}
// [END_ENTITY: Function('GreetingPreview')]
// [END_CONTRACT]
// [END_FILE_MainActivity.kt]

View File

@@ -1,7 +1,6 @@
// [PACKAGE] com.homebox.lens
// [FILE] MainApplication.kt
// [SEMANTICS] android, application, hilt, timber
// [SEMANTICS] application, hilt, timber
package com.homebox.lens
// [IMPORTS]
@@ -10,30 +9,22 @@ import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Application('MainApplication')]
// [RELATION: Application('MainApplication') -> [INHERITS_FROM] -> Class('Application')]
// [RELATION: Application('MainApplication') -> [DEPENDS_ON] -> Annotation('HiltAndroidApp')]
/**
* [ENTITY: Application('MainApplication')]
* [PURPOSE] Точка входа в приложение. Инициализирует Hilt и Timber.
* @summary Точка входа в приложение. Инициализирует Hilt и Timber.
*/
@HiltAndroidApp
class MainApplication : Application() {
// [ENTITY: Function('onCreate')]
// [RELATION: Function('onCreate') -> [CALLS] -> Function('super.onCreate')]
// [RELATION: Function('onCreate') -> [CALLS] -> Function('Timber.plant')]
// [LIFECYCLE]
override fun onCreate() {
super.onCreate()
// [ACTION] Initialize Timber for logging
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
Timber.d("[DEBUG][INITIALIZATION][timber_planted] Timber DebugTree planted.")
}
}
// [END_ENTITY: Function('onCreate')]
}
// [END_ENTITY: Application('MainApplication')]
// [END_CONTRACT]
// [END_FILE_MainApplication.kt]

View File

@@ -9,74 +9,48 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.compose.runtime.collectAsState
import com.homebox.lens.domain.model.Item
import androidx.navigation.navArgument
import com.homebox.lens.ui.screen.dashboard.DashboardScreen
import com.homebox.lens.ui.screen.inventorylist.InventoryListScreen
import com.homebox.lens.ui.screen.inventorylist.InventoryListViewModel
import com.homebox.lens.ui.screen.itemdetails.ItemDetailsScreen
import com.homebox.lens.ui.screen.itemdetails.ItemDetailsViewModel
import com.homebox.lens.ui.screen.itemedit.ItemEditScreen
import com.homebox.lens.ui.screen.itemedit.ItemEditViewModel
import com.homebox.lens.ui.screen.labelslist.labelsListScreen
import com.homebox.lens.ui.screen.labelslist.LabelsListViewModel
import com.homebox.lens.ui.screen.labelslist.LabelsListScreen
import com.homebox.lens.ui.screen.locationedit.LocationEditScreen
import com.homebox.lens.ui.screen.locationslist.LocationsListScreen
import com.homebox.lens.ui.screen.search.SearchScreen
import com.homebox.lens.ui.screen.search.SearchViewModel
import com.homebox.lens.ui.screen.setup.SetupScreen
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('NavGraph')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('rememberNavController')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('currentBackStackEntryAsState')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('remember')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('NavGraph') -> [CREATES_INSTANCE_OF] -> Class('NavigationActions')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('NavHost')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('composable')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('SetupScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('DashboardScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('InventoryListScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('ItemDetailsScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('ItemEditScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('LabelsListScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('LocationsListScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('LocationEditScreen')]
// [RELATION: Function('NavGraph') -> [CALLS] -> Function('SearchScreen')]
// [RELATION: Function('NavGraph')] -> [DEPENDS_ON] -> [Framework('NavHostController')]
// [RELATION: Function('NavGraph')] -> [CREATES_INSTANCE_OF] -> [Class('NavigationActions')]
/**
* [CONTRACT]
* Определяет граф навигации для всего приложения с использованием Jetpack Compose Navigation.
* @summary Определяет граф навигации для всего приложения с использованием Jetpack Compose Navigation.
* @param navController Контроллер навигации.
* @see Screen
* @sideeffect Регистрирует все экраны и управляет состоянием навигации.
* @invariant Стартовый экран - `Screen.Setup`.
*/
@Composable
fun NavGraph(navController: NavHostController = rememberNavController()) {
// [STATE]
fun NavGraph(
navController: NavHostController = rememberNavController()
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
// [HELPER]
val navigationActions =
remember(navController) {
NavigationActions(navController)
}
val navigationActions = remember(navController) {
NavigationActions(navController)
}
// [ACTION]
NavHost(
navController = navController,
startDestination = Screen.Setup.route,
startDestination = Screen.Setup.route
) {
// [ENTITY: Composable('Screen.Setup.route')]
composable(route = Screen.Setup.route) {
SetupScreen(onSetupComplete = {
navController.navigate(Screen.Dashboard.route) {
@@ -84,113 +58,65 @@ fun NavGraph(navController: NavHostController = rememberNavController()) {
}
})
}
// [END_ENTITY: Composable('Screen.Setup.route')]
// [ENTITY: Composable('Screen.Dashboard.route')]
composable(route = Screen.Dashboard.route) {
DashboardScreen(
currentRoute = currentRoute,
navigationActions = navigationActions,
navigationActions = navigationActions
)
}
// [END_ENTITY: Composable('Screen.Dashboard.route')]
// [ENTITY: Composable('Screen.InventoryList.route')]
composable(route = Screen.InventoryList.route) { backStackEntry ->
val viewModel: InventoryListViewModel = hiltViewModel(backStackEntry)
composable(route = Screen.InventoryList.route) {
InventoryListScreen(
onItemClick = { item ->
// TODO: Navigate to item details
Timber.i("[UI] Item clicked: ${item.name}")
},
onNavigateBack = {
navController.popBackStack()
}
currentRoute = currentRoute,
navigationActions = navigationActions
)
}
// [END_ENTITY: Composable('Screen.InventoryList.route')]
// [ENTITY: Composable('Screen.ItemDetails.route')]
composable(route = Screen.ItemDetails.route) { backStackEntry ->
val viewModel: ItemDetailsViewModel = hiltViewModel(backStackEntry)
composable(route = Screen.ItemDetails.route) {
ItemDetailsScreen(
onNavigateBack = {
navController.popBackStack()
},
onEditClick = { itemId ->
// TODO: Navigate to item edit screen
Timber.i("[UI] Edit item clicked: $itemId")
}
currentRoute = currentRoute,
navigationActions = navigationActions
)
}
// [END_ENTITY: Composable('Screen.ItemDetails.route')]
// [ENTITY: Composable('Screen.ItemEdit.route')]
composable(route = Screen.ItemEdit.route) { backStackEntry ->
val viewModel: ItemEditViewModel = hiltViewModel(backStackEntry)
composable(
route = Screen.ItemEdit.route,
arguments = listOf(navArgument("itemId") { nullable = true })
) { backStackEntry ->
val itemId = backStackEntry.arguments?.getString("itemId")
ItemEditScreen(
onNavigateBack = {
navController.popBackStack()
}
currentRoute = currentRoute,
navigationActions = navigationActions,
itemId = itemId,
onSaveSuccess = { navController.popBackStack() }
)
}
// [END_ENTITY: Composable('Screen.ItemEdit.route')]
// [ENTITY: Composable('Screen.LabelsList.route')]
composable(Screen.LabelsList.route) { backStackEntry ->
val viewModel: LabelsListViewModel = hiltViewModel(backStackEntry)
val uiState by viewModel.uiState.collectAsState()
labelsListScreen(
uiState = uiState,
onLabelClick = { label ->
// TODO: Implement navigation to label details screen
Timber.i("[UI] Label clicked: ${label.name}")
},
onAddClick = {
// TODO: Implement navigation to add new label screen
Timber.i("[UI] Add new label clicked")
},
onNavigateBack = {
navController.popBackStack()
}
)
composable(Screen.LabelsList.route) {
LabelsListScreen(navController = navController)
}
// [END_ENTITY: Composable('Screen.LabelsList.route')]
// [ENTITY: Composable('Screen.LocationsList.route')]
composable(route = Screen.LocationsList.route) {
LocationsListScreen(
currentRoute = currentRoute,
navigationActions = navigationActions,
onLocationClick = { locationId ->
// TODO: Navigate to a pre-filtered inventory list screen
// [AI_NOTE]: Navigate to a pre-filtered inventory list screen
navController.navigate(Screen.InventoryList.route)
},
onAddNewLocationClick = {
navController.navigate(Screen.LocationEdit.createRoute("new"))
},
)
}
// [END_ENTITY: Composable('Screen.LocationsList.route')]
// [ENTITY: Composable('Screen.LocationEdit.route')]
composable(route = Screen.LocationEdit.route) { backStackEntry ->
val locationId = backStackEntry.arguments?.getString("locationId")
LocationEditScreen(
locationId = locationId,
)
}
// [END_ENTITY: Composable('Screen.LocationEdit.route')]
// [ENTITY: Composable('Screen.Search.route')]
composable(route = Screen.Search.route) { backStackEntry ->
val viewModel: SearchViewModel = hiltViewModel(backStackEntry)
SearchScreen(
onNavigateBack = {
navController.popBackStack()
},
onItemClick = { item ->
// TODO: Navigate to item details
Timber.i("[UI] Search result item clicked: ${item.name}")
}
)
}
// [END_ENTITY: Composable('Screen.Search.route')]
composable(route = Screen.LocationEdit.route) { backStackEntry ->
val locationId = backStackEntry.arguments?.getString("locationId")
LocationEditScreen(
locationId = locationId
)
}
composable(route = Screen.Search.route) {
SearchScreen(
currentRoute = currentRoute,
navigationActions = navigationActions
)
}
}
}
// [END_ENTITY: Function('NavGraph')]
// [END_CONTRACT]
// [END_FILE_NavGraph.kt]

View File

@@ -5,32 +5,26 @@ package com.homebox.lens.navigation
// [IMPORTS]
import androidx.navigation.NavHostController
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Class('NavigationActions')]
// [RELATION: Class('NavigationActions') -> [DEPENDS_ON] -> Class('NavHostController')]
// [RELATION: Class('NavigationActions')] -> [DEPENDS_ON] -> [Framework('NavHostController')]
/**
* [CONTRACT]
* @summary Класс-обертка над NavHostController для предоставления типизированных навигационных действий.
* @param navController Контроллер Jetpack Navigation.
* @invariant Все навигационные действия должны использовать предоставленный navController.
*/
class NavigationActions(private val navController: NavHostController) {
// [ENTITY: Function('navigateToDashboard')]
// [RELATION: Function('navigateToDashboard') -> [CALLS] -> Function('navController.navigate')]
// [RELATION: Function('navigateToDashboard') -> [CALLS] -> Function('Screen.Dashboard.route')]
// [RELATION: Function('navigateToDashboard') -> [CALLS] -> Function('popUpTo')]
// [ACTION]
/**
* [CONTRACT]
* @summary Навигация на главный экран.
* @sideeffect Очищает back stack до главного экрана, чтобы избежать циклов.
*/
fun navigateToDashboard() {
Timber.i("[INFO][ACTION][navigate_to_dashboard] Navigating to Dashboard.")
navController.navigate(Screen.Dashboard.route) {
// Используем popUpTo для удаления всех экранов до dashboard из back stack
// Это предотвращает создание большой стопки экранов при навигации через drawer
popUpTo(navController.graph.startDestinationId)
launchSingleTop = true
}
@@ -38,10 +32,8 @@ class NavigationActions(private val navController: NavHostController) {
// [END_ENTITY: Function('navigateToDashboard')]
// [ENTITY: Function('navigateToLocations')]
// [RELATION: Function('navigateToLocations') -> [CALLS] -> Function('navController.navigate')]
// [RELATION: Function('navigateToLocations') -> [CALLS] -> Function('Screen.LocationsList.route')]
// [ACTION]
fun navigateToLocations() {
Timber.i("[INFO][ACTION][navigate_to_locations] Navigating to Locations.")
navController.navigate(Screen.LocationsList.route) {
launchSingleTop = true
}
@@ -49,10 +41,8 @@ class NavigationActions(private val navController: NavHostController) {
// [END_ENTITY: Function('navigateToLocations')]
// [ENTITY: Function('navigateToLabels')]
// [RELATION: Function('navigateToLabels') -> [CALLS] -> Function('navController.navigate')]
// [RELATION: Function('navigateToLabels') -> [CALLS] -> Function('Screen.LabelsList.route')]
// [ACTION]
fun navigateToLabels() {
Timber.i("[INFO][ACTION][navigate_to_labels] Navigating to Labels.")
navController.navigate(Screen.LabelsList.route) {
launchSingleTop = true
}
@@ -60,10 +50,8 @@ class NavigationActions(private val navController: NavHostController) {
// [END_ENTITY: Function('navigateToLabels')]
// [ENTITY: Function('navigateToSearch')]
// [RELATION: Function('navigateToSearch') -> [CALLS] -> Function('navController.navigate')]
// [RELATION: Function('navigateToSearch') -> [CALLS] -> Function('Screen.Search.route')]
// [ACTION]
fun navigateToSearch() {
Timber.i("[INFO][ACTION][navigate_to_search] Navigating to Search.")
navController.navigate(Screen.Search.route) {
launchSingleTop = true
}
@@ -71,39 +59,31 @@ class NavigationActions(private val navController: NavHostController) {
// [END_ENTITY: Function('navigateToSearch')]
// [ENTITY: Function('navigateToInventoryListWithLabel')]
// [RELATION: Function('navigateToInventoryListWithLabel') -> [CALLS] -> Function('Screen.InventoryList.withFilter')]
// [RELATION: Function('navigateToInventoryListWithLabel') -> [CALLS] -> Function('navController.navigate')]
// [ACTION]
fun navigateToInventoryListWithLabel(labelId: String) {
Timber.i("[INFO][ACTION][navigate_to_inventory_with_label] Navigating to Inventory with label: %s", labelId)
val route = Screen.InventoryList.withFilter("label", labelId)
navController.navigate(route)
}
// [END_ENTITY: Function('navigateToInventoryListWithLabel')]
// [ENTITY: Function('navigateToInventoryListWithLocation')]
// [RELATION: Function('navigateToInventoryListWithLocation') -> [CALLS] -> Function('Screen.InventoryList.withFilter')]
// [RELATION: Function('navigateToInventoryListWithLocation') -> [CALLS] -> Function('navController.navigate')]
// [ACTION]
fun navigateToInventoryListWithLocation(locationId: String) {
Timber.i("[INFO][ACTION][navigate_to_inventory_with_location] Navigating to Inventory with location: %s", locationId)
val route = Screen.InventoryList.withFilter("location", locationId)
navController.navigate(route)
}
// [END_ENTITY: Function('navigateToInventoryListWithLocation')]
// [ENTITY: Function('navigateToCreateItem')]
// [RELATION: Function('navigateToCreateItem') -> [CALLS] -> Function('Screen.ItemEdit.createRoute')]
// [RELATION: Function('navigateToCreateItem') -> [CALLS] -> Function('navController.navigate')]
// [ACTION]
fun navigateToCreateItem() {
Timber.i("[INFO][ACTION][navigate_to_create_item] Navigating to Create Item.")
navController.navigate(Screen.ItemEdit.createRoute("new"))
}
// [END_ENTITY: Function('navigateToCreateItem')]
// [ENTITY: Function('navigateToLogout')]
// [RELATION: Function('navigateToLogout') -> [CALLS] -> Function('navController.navigate')]
// [RELATION: Function('navigateToLogout') -> [CALLS] -> Function('popUpTo')]
// [ACTION]
fun navigateToLogout() {
Timber.i("[INFO][ACTION][navigate_to_logout] Navigating to Logout.")
navController.navigate(Screen.Setup.route) {
popUpTo(Screen.Dashboard.route) { inclusive = true }
}
@@ -111,13 +91,11 @@ class NavigationActions(private val navController: NavHostController) {
// [END_ENTITY: Function('navigateToLogout')]
// [ENTITY: Function('navigateBack')]
// [RELATION: Function('navigateBack') -> [CALLS] -> Function('navController.popBackStack')]
// [ACTION]
fun navigateBack() {
Timber.i("[INFO][ACTION][navigate_back] Navigating back.")
navController.popBackStack()
}
// [END_ENTITY: Function('navigateBack')]
}
// [END_ENTITY: Class('NavigationActions')]
// [END_CONTRACT]
// [END_FILE_NavigationActions.kt]
// [END_FILE_NavigationActions.kt]

View File

@@ -3,136 +3,106 @@
// [SEMANTICS] navigation, routes, sealed_class
package com.homebox.lens.navigation
// [IMPORTS]
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: SealedClass('Screen')]
/**
* [CONTRACT]
* Запечатанный класс для определения маршрутов навигации в приложении.
* Обеспечивает типобезопасность при навигации.
* @property route Строковый идентификатор маршрута.
* @summary Запечатанный класс для определения маршрутов навигации в приложении.
* @description Обеспечивает типобезопасность при навигации.
* @param route Строковый идентификатор маршрута.
*/
sealed class Screen(val route: String) {
// [ENTITY: DataObject('Setup')]
// [ENTITY: Object('Setup')]
data object Setup : Screen("setup_screen")
// [END_ENTITY: DataObject('Setup')]
// [END_ENTITY: Object('Setup')]
// [ENTITY: DataObject('Dashboard')]
// [ENTITY: Object('Dashboard')]
data object Dashboard : Screen("dashboard_screen")
// [END_ENTITY: DataObject('Dashboard')]
// [END_ENTITY: Object('Dashboard')]
// [ENTITY: DataObject('InventoryList')]
// [ENTITY: Object('InventoryList')]
data object InventoryList : Screen("inventory_list_screen") {
// [ENTITY: Function('withFilter')]
/**
* [CONTRACT]
* Создает маршрут для экрана списка инвентаря с параметром фильтра.
* @summary Создает маршрут для экрана списка инвентаря с параметром фильтра.
* @param key Ключ фильтра (например, "label" или "location").
* @param value Значение фильтра (например, ID метки или местоположения).
* @return Строку полного маршрута с query-параметром.
* @throws IllegalArgumentException если ключ или значение пустые.
* @sideeffect [ARCH-IMPLICATION] NavGraph должен быть настроен для приема этого опционального query-параметра (например, 'navArgument("label") { nullable = true }').
*/
fun withFilter(
key: String,
value: String,
): String {
// [PRECONDITION]
require(key.isNotBlank()) { "[PRECONDITION_FAILED] Filter key cannot be blank." }
require(value.isNotBlank()) { "[PRECONDITION_FAILED] Filter value cannot be blank." }
// [ACTION]
fun withFilter(key: String, value: String): String {
require(key.isNotBlank()) { "Filter key cannot be blank." }
require(value.isNotBlank()) { "Filter value cannot be blank." }
val constructedRoute = "inventory_list_screen?$key=$value"
// [POSTCONDITION]
check(constructedRoute.contains("?$key=$value")) { "[POSTCONDITION_FAILED] Route must contain the filter query." }
check(constructedRoute.contains("?$key=$value")) { "Route must contain the filter query." }
return constructedRoute
}
// [END_ENTITY: Function('withFilter')]
}
// [END_ENTITY: DataObject('InventoryList')]
// [END_ENTITY: Object('InventoryList')]
// [ENTITY: DataObject('ItemDetails')]
// [ENTITY: Object('ItemDetails')]
data object ItemDetails : Screen("item_details_screen/{itemId}") {
// [ENTITY: Function('createRoute')]
/**
* [CONTRACT]
* Создает маршрут для экрана деталей элемента с указанным ID.
* @summary Создает маршрут для экрана деталей элемента с указанным ID.
* @param itemId ID элемента для отображения.
* @return Строку полного маршрута.
* @throws IllegalArgumentException если itemId пустой.
*/
fun createRoute(itemId: String): String {
// [PRECONDITION]
require(itemId.isNotBlank()) { "[PRECONDITION_FAILED] itemId не может быть пустым." }
// [ACTION]
require(itemId.isNotBlank()) { "itemId не может быть пустым." }
val route = "item_details_screen/$itemId"
// [POSTCONDITION]
check(route.endsWith(itemId)) { "[POSTCONDITION_FAILED] Маршрут должен заканчиваться на itemId." }
check(route.endsWith(itemId)) { "Маршрут должен заканчиваться на itemId." }
return route
}
// [END_ENTITY: Function('createRoute')]
}
// [END_ENTITY: DataObject('ItemDetails')]
// [END_ENTITY: Object('ItemDetails')]
// [ENTITY: DataObject('ItemEdit')]
data object ItemEdit : Screen("item_edit_screen/{itemId}") {
// [ENTITY: Object('ItemEdit')]
data object ItemEdit : Screen("item_edit_screen?itemId={itemId}") {
// [ENTITY: Function('createRoute')]
/**
* [CONTRACT]
* Создает маршрут для экрана редактирования элемента с указанным ID.
* @param itemId ID элемента для редактирования.
* @summary Создает маршрут для экрана редактирования элемента с указанным ID.
* @param itemId ID элемента для редактирования. Null, если создается новый элемент.
* @return Строку полного маршрута.
* @throws IllegalArgumentException если itemId пустой.
*/
fun createRoute(itemId: String): String {
// [PRECONDITION]
require(itemId.isNotBlank()) { "[PRECONDITION_FAILED] itemId не может быть пустым." }
// [ACTION]
val route = "item_edit_screen/$itemId"
// [POSTCONDITION]
check(route.endsWith(itemId)) { "[POSTCONDITION_FAILED] Маршрут должен заканчиваться на itemId." }
return route
fun createRoute(itemId: String? = null): String {
return itemId?.let { "item_edit_screen?itemId=$it" } ?: "item_edit_screen"
}
// [END_ENTITY: Function('createRoute')]
}
// [END_ENTITY: DataObject('ItemEdit')]
// [END_ENTITY: Object('ItemEdit')]
// [ENTITY: DataObject('LabelsList')]
// [ENTITY: Object('LabelsList')]
data object LabelsList : Screen("labels_list_screen")
// [END_ENTITY: DataObject('LabelsList')]
// [END_ENTITY: Object('LabelsList')]
// [ENTITY: DataObject('LocationsList')]
// [ENTITY: Object('LocationsList')]
data object LocationsList : Screen("locations_list_screen")
// [END_ENTITY: DataObject('LocationsList')]
// [END_ENTITY: Object('LocationsList')]
// [ENTITY: DataObject('LocationEdit')]
// [ENTITY: Object('LocationEdit')]
data object LocationEdit : Screen("location_edit_screen/{locationId}") {
// [ENTITY: Function('createRoute')]
/**
* [CONTRACT]
* Создает маршрут для экрана редактирования местоположения с указанным ID.
* @summary Создает маршрут для экрана редактирования местоположения с указанным ID.
* @param locationId ID местоположения для редактирования.
* @return Строку полного маршрута.
* @throws IllegalArgumentException если locationId пустой.
*/
fun createRoute(locationId: String): String {
// [PRECONDITION]
require(locationId.isNotBlank()) { "[PRECONDITION_FAILED] locationId не может быть пустым." }
// [ACTION]
require(locationId.isNotBlank()) { "locationId не может быть пустым." }
val route = "location_edit_screen/$locationId"
// [POSTCONDITION]
check(route.endsWith(locationId)) { "[POSTCONDITION_FAILED] Маршрут должен заканчиваться на locationId." }
check(route.endsWith(locationId)) { "Маршрут должен заканчиваться на locationId." }
return route
}
// [END_ENTITY: Function('createRoute')]
}
// [END_ENTITY: DataObject('LocationEdit')]
// [END_ENTITY: Object('LocationEdit')]
// [ENTITY: DataObject('Search')]
// [ENTITY: Object('Search')]
data object Search : Screen("search_screen")
// [END_ENTITY: DataObject('Search')]
// [END_ENTITY: Object('Search')]
}
// [END_ENTITY: SealedClass('Screen')]
// [END_CONTRACT]
// [END_FILE_Screen.kt]
// [END_FILE_Screen.kt]

View File

@@ -27,25 +27,9 @@ import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.navigation.Screen
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('AppDrawerContent')]
// [RELATION: Function('AppDrawerContent') -> [DEPENDS_ON] -> Class('NavigationActions')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('ModalDrawerSheet')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Spacer')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Button')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Divider')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('NavigationDrawerItem')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Screen.Dashboard.route')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Screen.LocationsList.route')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Screen.LabelsList.route')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Screen.Search.route')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Screen.ItemEdit.createRoute')]
// [RELATION: Function('AppDrawerContent') -> [CALLS] -> Function('Screen.Setup.route')]
// [RELATION: Function('AppDrawerContent')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
/**
* [CONTRACT]
* @summary Контент для бокового навигационного меню (Drawer).
* @param currentRoute Текущий маршрут для подсветки активного элемента.
* @param navigationActions Объект с навигационными действиями.
@@ -55,7 +39,7 @@ import com.homebox.lens.navigation.Screen
internal fun AppDrawerContent(
currentRoute: String?,
navigationActions: NavigationActions,
onCloseDrawer: () -> Unit,
onCloseDrawer: () -> Unit
) {
ModalDrawerSheet {
Spacer(Modifier.height(12.dp))
@@ -64,10 +48,9 @@ internal fun AppDrawerContent(
navigationActions.navigateToCreateItem()
onCloseDrawer()
},
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
@@ -81,7 +64,7 @@ internal fun AppDrawerContent(
onClick = {
navigationActions.navigateToDashboard()
onCloseDrawer()
},
}
)
NavigationDrawerItem(
label = { Text(stringResource(id = R.string.nav_locations)) },
@@ -89,7 +72,7 @@ internal fun AppDrawerContent(
onClick = {
navigationActions.navigateToLocations()
onCloseDrawer()
},
}
)
NavigationDrawerItem(
label = { Text(stringResource(id = R.string.nav_labels)) },
@@ -97,7 +80,7 @@ internal fun AppDrawerContent(
onClick = {
navigationActions.navigateToLabels()
onCloseDrawer()
},
}
)
NavigationDrawerItem(
label = { Text(stringResource(id = R.string.search)) },
@@ -105,9 +88,9 @@ internal fun AppDrawerContent(
onClick = {
navigationActions.navigateToSearch()
onCloseDrawer()
},
}
)
// TODO: Add Profile and Tools items
// [AI_NOTE]: Add Profile and Tools items
Divider()
NavigationDrawerItem(
label = { Text(stringResource(id = R.string.logout)) },
@@ -115,10 +98,9 @@ internal fun AppDrawerContent(
onClick = {
navigationActions.navigateToLogout()
onCloseDrawer()
},
}
)
}
}
// [END_ENTITY: Function('AppDrawerContent')]
// [END_CONTRACT]
// [END_FILE_AppDrawer.kt]
// [END_FILE_AppDrawer.kt]

View File

@@ -17,21 +17,10 @@ import com.homebox.lens.navigation.NavigationActions
import kotlinx.coroutines.launch
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('MainScaffold')]
// [RELATION: Function('MainScaffold') -> [DEPENDS_ON] -> Class('NavigationActions')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('rememberDrawerState')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('rememberCoroutineScope')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('ModalNavigationDrawer')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('AppDrawerContent')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('Scaffold')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('TopAppBar')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('Text')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('MainScaffold') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('MainScaffold')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('MainScaffold')] -> [CALLS] -> [Function('AppDrawerContent')]
/**
* [CONTRACT]
* @summary Общая обертка для экранов, включающая Scaffold и Navigation Drawer.
* @param topBarTitle Заголовок для TopAppBar.
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
@@ -48,22 +37,20 @@ fun MainScaffold(
currentRoute: String?,
navigationActions: NavigationActions,
topBarActions: @Composable () -> Unit = {},
content: @Composable (PaddingValues) -> Unit,
content: @Composable (PaddingValues) -> Unit
) {
// [STATE]
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
// [CORE-LOGIC]
ModalNavigationDrawer(
drawerState = drawerState,
drawerContent = {
AppDrawerContent(
currentRoute = currentRoute,
navigationActions = navigationActions,
onCloseDrawer = { scope.launch { drawerState.close() } },
onCloseDrawer = { scope.launch { drawerState.close() } }
)
},
}
) {
Scaffold(
topBar = {
@@ -73,19 +60,17 @@ fun MainScaffold(
IconButton(onClick = { scope.launch { drawerState.open() } }) {
Icon(
Icons.Default.Menu,
contentDescription = stringResource(id = R.string.cd_open_navigation_drawer),
contentDescription = stringResource(id = R.string.cd_open_navigation_drawer)
)
}
},
actions = { topBarActions() },
actions = { topBarActions() }
)
},
}
) { paddingValues ->
// [ACTION]
content(paddingValues)
}
}
}
// [END_ENTITY: Function('MainScaffold')]
// [END_CONTRACT]
// [END_FILE_MainScaffold.kt]

View File

@@ -32,19 +32,11 @@ import com.homebox.lens.ui.theme.HomeboxLensTheme
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('DashboardScreen')]
// [RELATION: Function('DashboardScreen') -> [DEPENDS_ON] -> Class('DashboardViewModel')]
// [RELATION: Function('DashboardScreen') -> [DEPENDS_ON] -> Class('NavigationActions')]
// [RELATION: Function('DashboardScreen') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('DashboardScreen') -> [CALLS] -> Function('collectAsState')]
// [RELATION: Function('DashboardScreen') -> [CALLS] -> Function('MainScaffold')]
// [RELATION: Function('DashboardScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('DashboardScreen') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('DashboardScreen') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('DashboardScreen') -> [CALLS] -> Function('DashboardContent')]
// [RELATION: Function('DashboardScreen')] -> [DEPENDS_ON] -> [ViewModel('DashboardViewModel')]
// [RELATION: Function('DashboardScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('DashboardScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* [CONTRACT]
* @summary Главная Composable-функция для экрана "Панель управления".
* @param viewModel ViewModel для этого экрана, предоставляется через Hilt.
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
@@ -55,11 +47,9 @@ import timber.log.Timber
fun DashboardScreen(
viewModel: DashboardViewModel = hiltViewModel(),
currentRoute: String?,
navigationActions: NavigationActions,
navigationActions: NavigationActions
) {
// [STATE]
val uiState by viewModel.uiState.collectAsState()
// [UI_COMPONENT]
MainScaffold(
topBarTitle = stringResource(id = R.string.dashboard_title),
currentRoute = currentRoute,
@@ -68,41 +58,30 @@ fun DashboardScreen(
IconButton(onClick = { navigationActions.navigateToSearch() }) {
Icon(
Icons.Default.Search,
contentDescription = stringResource(id = R.string.cd_scan_qr_code), // TODO: Rename string resource
contentDescription = stringResource(id = R.string.cd_scan_qr_code) // [AI_NOTE]: Rename string resource
)
}
},
}
) { paddingValues ->
DashboardContent(
modifier = Modifier.padding(paddingValues),
uiState = uiState,
onLocationClick = { location ->
Timber.i("[ACTION] Location chip clicked: ${location.id}. Navigating...")
Timber.i("[INFO][ACTION][navigate_to_inventory_with_location] Location chip clicked: ${location.id}. Navigating...")
navigationActions.navigateToInventoryListWithLocation(location.id)
},
onLabelClick = { label ->
Timber.i("[ACTION] Label chip clicked: ${label.id}. Navigating...")
Timber.i("[INFO][ACTION][navigate_to_inventory_with_label] Label chip clicked: ${label.id}. Navigating...")
navigationActions.navigateToInventoryListWithLabel(label.id)
},
}
)
}
}
// [END_ENTITY: Function('DashboardScreen')]
// [ENTITY: Function('DashboardContent')]
// [RELATION: Function('DashboardContent') -> [DEPENDS_ON] -> SealedInterface('DashboardUiState')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('Box')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('CircularProgressIndicator')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('MaterialTheme.colorScheme.error')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('LazyColumn')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('Spacer')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('StatisticsSection')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('RecentlyAddedSection')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('LocationsSection')]
// [RELATION: Function('DashboardContent') -> [CALLS] -> Function('LabelsSection')]
// [RELATION: Function('DashboardContent')] -> [CONSUMES_STATE] -> [SealedInterface('DashboardUiState')]
/**
* [CONTRACT]
* @summary Отображает основной контент экрана в зависимости от uiState.
* @param modifier Модификатор для стилизации.
* @param uiState Текущее состояние UI экрана.
@@ -114,9 +93,8 @@ private fun DashboardContent(
modifier: Modifier = Modifier,
uiState: DashboardUiState,
onLocationClick: (LocationOutCount) -> Unit,
onLabelClick: (LabelOut) -> Unit,
onLabelClick: (LabelOut) -> Unit
) {
// [CORE-LOGIC]
when (uiState) {
is DashboardUiState.Loading -> {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
@@ -128,17 +106,16 @@ private fun DashboardContent(
Text(
text = uiState.message,
color = MaterialTheme.colorScheme.error,
textAlign = TextAlign.Center,
textAlign = TextAlign.Center
)
}
}
is DashboardUiState.Success -> {
LazyColumn(
modifier =
modifier
.fillMaxSize()
.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(24.dp),
modifier = modifier
.fillMaxSize()
.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(24.dp)
) {
item { Spacer(modifier = Modifier.height(8.dp)) }
item { StatisticsSection(statistics = uiState.statistics) }
@@ -153,17 +130,8 @@ private fun DashboardContent(
// [END_ENTITY: Function('DashboardContent')]
// [ENTITY: Function('StatisticsSection')]
// [RELATION: Function('StatisticsSection') -> [DEPENDS_ON] -> Class('GroupStatistics')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('Column')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('Text')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('MaterialTheme.typography.titleMedium')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('Card')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('LazyVerticalGrid')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('GridCells.Fixed')]
// [RELATION: Function('StatisticsSection') -> [CALLS] -> Function('StatisticCard')]
// [RELATION: Function('StatisticsSection')] -> [DEPENDS_ON] -> [DataClass('GroupStatistics')]
/**
* [CONTRACT]
* @summary Секция для отображения общей статистики.
* @param statistics Объект со статистическими данными.
*/
@@ -172,43 +140,22 @@ private fun StatisticsSection(statistics: GroupStatistics) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(id = R.string.dashboard_section_quick_stats),
style = MaterialTheme.typography.titleMedium,
style = MaterialTheme.typography.titleMedium
)
Card {
LazyVerticalGrid(
columns = GridCells.Fixed(2),
modifier =
Modifier
.height(120.dp)
.fillMaxWidth()
.padding(16.dp),
modifier = Modifier
.height(120.dp)
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
item {
StatisticCard(
title = stringResource(id = R.string.dashboard_stat_total_items),
value = statistics.items.toString(),
)
}
item {
StatisticCard(
title = stringResource(id = R.string.dashboard_stat_total_value),
value = statistics.totalValue.toString(),
)
}
item {
StatisticCard(
title = stringResource(id = R.string.dashboard_stat_total_labels),
value = statistics.labels.toString(),
)
}
item {
StatisticCard(
title = stringResource(id = R.string.dashboard_stat_total_locations),
value = statistics.locations.toString(),
)
}
item { StatisticCard(title = stringResource(id = R.string.dashboard_stat_total_items), value = statistics.items.toString()) }
item { StatisticCard(title = stringResource(id = R.string.dashboard_stat_total_value), value = statistics.totalValue.toString()) }
item { StatisticCard(title = stringResource(id = R.string.dashboard_stat_total_labels), value = statistics.labels.toString()) }
item { StatisticCard(title = stringResource(id = R.string.dashboard_stat_total_locations), value = statistics.locations.toString()) }
}
}
}
@@ -216,21 +163,13 @@ private fun StatisticsSection(statistics: GroupStatistics) {
// [END_ENTITY: Function('StatisticsSection')]
// [ENTITY: Function('StatisticCard')]
// [RELATION: Function('StatisticCard') -> [CALLS] -> Function('Column')]
// [RELATION: Function('StatisticCard') -> [CALLS] -> Function('Text')]
// [RELATION: Function('StatisticCard') -> [CALLS] -> Function('MaterialTheme.typography.labelMedium')]
// [RELATION: Function('StatisticCard') -> [CALLS] -> Function('MaterialTheme.typography.headlineSmall')]
/**
* [CONTRACT]
* @summary Карточка для отображения одного статистического показателя.
* @param title Название показателя.
* @param value Значение показателя.
*/
@Composable
private fun StatisticCard(
title: String,
value: String,
) {
private fun StatisticCard(title: String, value: String) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Text(text = title, style = MaterialTheme.typography.labelMedium, textAlign = TextAlign.Center)
Text(text = value, style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center)
@@ -239,15 +178,8 @@ private fun StatisticCard(
// [END_ENTITY: Function('StatisticCard')]
// [ENTITY: Function('RecentlyAddedSection')]
// [RELATION: Function('RecentlyAddedSection') -> [DEPENDS_ON] -> Class('ItemSummary')]
// [RELATION: Function('RecentlyAddedSection') -> [CALLS] -> Function('Column')]
// [RELATION: Function('RecentlyAddedSection') -> [CALLS] -> Function('Text')]
// [RELATION: Function('RecentlyAddedSection') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('RecentlyAddedSection') -> [CALLS] -> Function('MaterialTheme.typography.titleMedium')]
// [RELATION: Function('RecentlyAddedSection') -> [CALLS] -> Function('LazyRow')]
// [RELATION: Function('RecentlyAddedSection') -> [CALLS] -> Function('ItemCard')]
// [RELATION: Function('RecentlyAddedSection')] -> [DEPENDS_ON] -> [DataClass('ItemSummary')]
/**
* [CONTRACT]
* @summary Секция для отображения недавно добавленных элементов.
* @param items Список элементов для отображения.
*/
@@ -256,17 +188,16 @@ private fun RecentlyAddedSection(items: List<ItemSummary>) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(id = R.string.dashboard_section_recently_added),
style = MaterialTheme.typography.titleMedium,
style = MaterialTheme.typography.titleMedium
)
if (items.isEmpty()) {
Text(
text = stringResource(id = R.string.items_not_found),
style = MaterialTheme.typography.bodyMedium,
modifier =
Modifier
.fillMaxWidth()
.padding(vertical = 16.dp),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 16.dp),
textAlign = TextAlign.Center
)
} else {
LazyRow(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
@@ -280,16 +211,8 @@ private fun RecentlyAddedSection(items: List<ItemSummary>) {
// [END_ENTITY: Function('RecentlyAddedSection')]
// [ENTITY: Function('ItemCard')]
// [RELATION: Function('ItemCard') -> [DEPENDS_ON] -> Class('ItemSummary')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('Card')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('Column')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('Spacer')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('Text')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('MaterialTheme.typography.titleSmall')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('MaterialTheme.typography.bodySmall')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('ItemCard')] -> [DEPENDS_ON] -> [DataClass('ItemSummary')]
/**
* [CONTRACT]
* @summary Карточка для отображения краткой информации об элементе.
* @param item Элемент для отображения.
*/
@@ -297,50 +220,33 @@ private fun RecentlyAddedSection(items: List<ItemSummary>) {
private fun ItemCard(item: ItemSummary) {
Card(modifier = Modifier.width(150.dp)) {
Column(modifier = Modifier.padding(8.dp)) {
// TODO: Add image here from item.image
Spacer(
modifier =
Modifier
.height(80.dp)
.fillMaxWidth()
.background(MaterialTheme.colorScheme.secondaryContainer),
)
// [AI_NOTE]: Add image here from item.image
Spacer(modifier = Modifier
.height(80.dp)
.fillMaxWidth()
.background(MaterialTheme.colorScheme.secondaryContainer))
Spacer(modifier = Modifier.height(8.dp))
Text(text = item.name, style = MaterialTheme.typography.titleSmall, maxLines = 1)
Text(
text = item.location?.name ?: stringResource(id = R.string.no_location),
style = MaterialTheme.typography.bodySmall,
maxLines = 1,
)
Text(text = item.location?.name ?: stringResource(id = R.string.no_location), style = MaterialTheme.typography.bodySmall, maxLines = 1)
}
}
}
// [END_ENTITY: Function('ItemCard')]
// [ENTITY: Function('LocationsSection')]
// [RELATION: Function('LocationsSection') -> [DEPENDS_ON] -> Class('LocationOutCount')]
// [RELATION: Function('LocationsSection') -> [CALLS] -> Function('Column')]
// [RELATION: Function('LocationsSection') -> [CALLS] -> Function('Text')]
// [RELATION: Function('LocationsSection') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LocationsSection') -> [CALLS] -> Function('MaterialTheme.typography.titleMedium')]
// [RELATION: Function('LocationsSection') -> [CALLS] -> Function('FlowRow')]
// [RELATION: Function('LocationsSection') -> [CALLS] -> Function('SuggestionChip')]
// [RELATION: Function('LocationsSection')] -> [DEPENDS_ON] -> [DataClass('LocationOutCount')]
/**
* [CONTRACT]
* @summary Секция для отображения местоположений в виде чипсов.
* @param locations Список местоположений.
* @param onLocationClick Лямбда-обработчик нажатия на местоположение.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun LocationsSection(
locations: List<LocationOutCount>,
onLocationClick: (LocationOutCount) -> Unit,
) {
private fun LocationsSection(locations: List<LocationOutCount>, onLocationClick: (LocationOutCount) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(id = R.string.dashboard_section_locations),
style = MaterialTheme.typography.titleMedium,
style = MaterialTheme.typography.titleMedium
)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -348,7 +254,7 @@ private fun LocationsSection(
locations.forEach { location ->
SuggestionChip(
onClick = { onLocationClick(location) },
label = { Text(stringResource(id = R.string.location_chip_label, location.name, location.itemCount)) },
label = { Text(stringResource(id = R.string.location_chip_label, location.name, location.itemCount)) }
)
}
}
@@ -357,29 +263,19 @@ private fun LocationsSection(
// [END_ENTITY: Function('LocationsSection')]
// [ENTITY: Function('LabelsSection')]
// [RELATION: Function('LabelsSection') -> [DEPENDS_ON] -> Class('LabelOut')]
// [RELATION: Function('LabelsSection') -> [CALLS] -> Function('Column')]
// [RELATION: Function('LabelsSection') -> [CALLS] -> Function('Text')]
// [RELATION: Function('LabelsSection') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LabelsSection') -> [CALLS] -> Function('MaterialTheme.typography.titleMedium')]
// [RELATION: Function('LabelsSection') -> [CALLS] -> Function('FlowRow')]
// [RELATION: Function('LabelsSection') -> [CALLS] -> Function('SuggestionChip')]
// [RELATION: Function('LabelsSection')] -> [DEPENDS_ON] -> [DataClass('LabelOut')]
/**
* [CONTRACT]
* @summary Секция для отображения меток в виде чипсов.
* @param labels Список меток.
* @param onLabelClick Лямбда-обработчик нажатия на метку.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun LabelsSection(
labels: List<LabelOut>,
onLabelClick: (LabelOut) -> Unit,
) {
private fun LabelsSection(labels: List<LabelOut>, onLabelClick: (LabelOut) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(id = R.string.dashboard_section_labels),
style = MaterialTheme.typography.titleMedium,
style = MaterialTheme.typography.titleMedium
)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -387,7 +283,7 @@ private fun LabelsSection(
labels.forEach { label ->
SuggestionChip(
onClick = { onLabelClick(label) },
label = { Text(label.name) },
label = { Text(label.name) }
)
}
}
@@ -396,97 +292,42 @@ private fun LabelsSection(
// [END_ENTITY: Function('LabelsSection')]
// [ENTITY: Function('DashboardContentSuccessPreview')]
// [RELATION: Function('DashboardContentSuccessPreview') -> [CALLS] -> Function('DashboardUiState.Success')]
// [RELATION: Function('DashboardContentSuccessPreview') -> [CALLS] -> Function('GroupStatistics')]
// [RELATION: Function('DashboardContentSuccessPreview') -> [CALLS] -> Function('LocationOutCount')]
// [RELATION: Function('DashboardContentSuccessPreview') -> [CALLS] -> Function('LabelOut')]
// [RELATION: Function('DashboardContentSuccessPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('DashboardContentSuccessPreview') -> [CALLS] -> Function('DashboardContent')]
// [PREVIEW]
@Preview(showBackground = true, name = "Dashboard Success State")
@Composable
fun DashboardContentSuccessPreview() {
val previewState =
DashboardUiState.Success(
statistics =
GroupStatistics(
items = 123,
totalValue = 9999.99,
locations = 5,
labels = 8,
),
locations =
listOf(
LocationOutCount(
id = "1",
name = "Office",
color = "#FF0000",
isArchived = false,
itemCount = 10,
createdAt = "",
updatedAt = "",
),
LocationOutCount(
id = "2",
name = "Garage",
color = "#00FF00",
isArchived = false,
itemCount = 5,
createdAt = "",
updatedAt = "",
),
LocationOutCount(
id = "3",
name = "Living Room",
color = "#0000FF",
isArchived = false,
itemCount = 15,
createdAt = "",
updatedAt = "",
),
LocationOutCount(
id = "4",
name = "Kitchen",
color = "#FFFF00",
isArchived = false,
itemCount = 20,
createdAt = "",
updatedAt = "",
),
LocationOutCount(
id = "5",
name = "Basement",
color = "#00FFFF",
isArchived = false,
itemCount = 3,
createdAt = "",
updatedAt = "",
),
),
labels =
listOf(
LabelOut(id = "1", name = "electronics", color = "#FF0000", isArchived = false, createdAt = "", updatedAt = ""),
LabelOut(id = "2", name = "important", color = "#00FF00", isArchived = false, createdAt = "", updatedAt = ""),
LabelOut(id = "3", name = "seasonal", color = "#0000FF", isArchived = false, createdAt = "", updatedAt = ""),
LabelOut(id = "4", name = "hobby", color = "#FFFF00", isArchived = false, createdAt = "", updatedAt = ""),
),
recentlyAddedItems = emptyList(),
)
val previewState = DashboardUiState.Success(
statistics = GroupStatistics(
items = 123,
totalValue = 9999.99,
locations = 5,
labels = 8
),
locations = listOf(
LocationOutCount(id="1", name="Office", color = "#FF0000", isArchived = false, itemCount = 10, createdAt = "", updatedAt = ""),
LocationOutCount(id="2", name="Garage", color = "#00FF00", isArchived = false, itemCount = 5, createdAt = "", updatedAt = ""),
LocationOutCount(id="3",name="Living Room", color = "#0000FF", isArchived = false, itemCount = 15, createdAt = "", updatedAt = ""),
LocationOutCount(id="4",name="Kitchen", color = "#FFFF00", isArchived = false, itemCount = 20, createdAt = "", updatedAt = ""),
LocationOutCount(id="5",name="Basement", color = "#00FFFF", isArchived = false, itemCount = 3, createdAt = "", updatedAt = "")
),
labels = listOf(
LabelOut(id="1", name="electronics", color = "#FF0000", isArchived = false, createdAt = "", updatedAt = ""),
LabelOut(id="2", name="important", color = "#00FF00", isArchived = false, createdAt = "", updatedAt = ""),
LabelOut(id="3", name="seasonal", color = "#0000FF", isArchived = false, createdAt = "", updatedAt = ""),
LabelOut(id="4", name="hobby", color = "#FFFF00", isArchived = false, createdAt = "", updatedAt = "")
),
recentlyAddedItems = emptyList()
)
HomeboxLensTheme {
DashboardContent(
uiState = previewState,
onLocationClick = {},
onLabelClick = {},
onLabelClick = {}
)
}
}
// [END_ENTITY: Function('DashboardContentSuccessPreview')]
// [ENTITY: Function('DashboardContentLoadingPreview')]
// [RELATION: Function('DashboardContentLoadingPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('DashboardContentLoadingPreview') -> [CALLS] -> Function('DashboardContent')]
// [RELATION: Function('DashboardContentLoadingPreview') -> [CALLS] -> Function('DashboardUiState.Loading')]
// [PREVIEW]
@Preview(showBackground = true, name = "Dashboard Loading State")
@Composable
fun DashboardContentLoadingPreview() {
@@ -494,18 +335,13 @@ fun DashboardContentLoadingPreview() {
DashboardContent(
uiState = DashboardUiState.Loading,
onLocationClick = {},
onLabelClick = {},
onLabelClick = {}
)
}
}
// [END_ENTITY: Function('DashboardContentLoadingPreview')]
// [ENTITY: Function('DashboardContentErrorPreview')]
// [RELATION: Function('DashboardContentErrorPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('DashboardContentErrorPreview') -> [CALLS] -> Function('DashboardContent')]
// [RELATION: Function('DashboardContentErrorPreview') -> [CALLS] -> Function('DashboardUiState.Error')]
// [RELATION: Function('DashboardContentErrorPreview') -> [CALLS] -> Function('stringResource')]
// [PREVIEW]
@Preview(showBackground = true, name = "Dashboard Error State")
@Composable
fun DashboardContentErrorPreview() {
@@ -513,10 +349,9 @@ fun DashboardContentErrorPreview() {
DashboardContent(
uiState = DashboardUiState.Error(stringResource(id = R.string.error_loading_failed)),
onLocationClick = {},
onLabelClick = {},
onLabelClick = {}
)
}
}
// [END_ENTITY: Function('DashboardContentErrorPreview')]
// [END_CONTRACT]
// [END_FILE_DashboardScreen.kt]
// [END_FILE_DashboardScreen.kt]

View File

@@ -1,62 +1,55 @@
// [PACKAGE] com.homebox.lens.ui.screen.dashboard
// [FILE] DashboardUiState.kt
// [SEMANTICS] ui, state, dashboard
package com.homebox.lens.ui.screen.dashboard
// [IMPORTS]
import com.homebox.lens.domain.model.GroupStatistics
import com.homebox.lens.domain.model.ItemSummary
import com.homebox.lens.domain.model.LabelOut
import com.homebox.lens.domain.model.LocationOutCount
import com.homebox.lens.domain.model.ItemSummary
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: SealedInterface('DashboardUiState')]
/**
* [CONTRACT]
* Определяет все возможные состояния для экрана "Дэшборд".
* @summary Определяет все возможные состояния для экрана "Дэшборд".
* @invariant В любой момент времени экран может находиться только в одном из этих состояний.
*/
sealed interface DashboardUiState {
// [ENTITY: DataClass('Success')]
// [RELATION: DataClass('Success') -> [DEPENDS_ON] -> Class('GroupStatistics')]
// [RELATION: DataClass('Success') -> [DEPENDS_ON] -> Class('LocationOutCount')]
// [RELATION: DataClass('Success') -> [DEPENDS_ON] -> Class('LabelOut')]
// [RELATION: DataClass('Success') -> [DEPENDS_ON] -> Class('ItemSummary')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('GroupStatistics')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('LocationOutCount')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('LabelOut')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('ItemSummary')]
/**
* [CONTRACT]
* Состояние успешной загрузки данных.
* @property statistics Статистика по инвентарю.
* @property locations Список локаций со счетчиками.
* @property labels Список всех меток.
* @property recentlyAddedItems Список недавно добавленных товаров.
* @summary Состояние успешной загрузки данных.
* @param statistics Статистика по инвентарю.
* @param locations Список локаций со счетчиками.
* @param labels Список всех меток.
* @param recentlyAddedItems Список недавно добавленных товаров.
*/
data class Success(
val statistics: GroupStatistics,
val locations: List<LocationOutCount>,
val labels: List<LabelOut>,
val recentlyAddedItems: List<ItemSummary>,
val recentlyAddedItems: List<ItemSummary>
) : DashboardUiState
// [END_ENTITY: DataClass('Success')]
// [ENTITY: DataClass('Error')]
/**
* [CONTRACT]
* Состояние ошибки во время загрузки данных.
* @property message Человекочитаемое сообщение об ошибке.
* @summary Состояние ошибки во время загрузки данных.
* @param message Человекочитаемое сообщение об ошибке.
*/
data class Error(val message: String) : DashboardUiState
// [END_ENTITY: DataClass('Error')]
// [ENTITY: DataObject('Loading')]
// [ENTITY: Object('Loading')]
/**
* [CONTRACT]
* Состояние, когда данные для экрана загружаются.
* @summary Состояние, когда данные для экрана загружаются.
*/
object Loading : DashboardUiState
// [END_ENTITY: DataObject('Loading')]
data object Loading : DashboardUiState
// [END_ENTITY: Object('Loading')]
}
// [END_ENTITY: SealedInterface('DashboardUiState')]
// [END_CONTRACT]
// [END_FILE_DashboardUiState.kt]
// [END_FILE_DashboardUiState.kt]

View File

@@ -17,94 +17,69 @@ import timber.log.Timber
import javax.inject.Inject
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('DashboardViewModel')]
// [RELATION: ViewModel('DashboardViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('DashboardViewModel') -> [DEPENDS_ON] -> Annotation('HiltViewModel')]
// [RELATION: ViewModel('DashboardViewModel') -> [DEPENDS_ON] -> Class('GetStatisticsUseCase')]
// [RELATION: ViewModel('DashboardViewModel') -> [DEPENDS_ON] -> Class('GetAllLocationsUseCase')]
// [RELATION: ViewModel('DashboardViewModel') -> [DEPENDS_ON] -> Class('GetAllLabelsUseCase')]
// [RELATION: ViewModel('DashboardViewModel') -> [DEPENDS_ON] -> Class('GetRecentlyAddedItemsUseCase')]
// [RELATION: ViewModel('DashboardViewModel')] -> [DEPENDS_ON] -> [UseCase('GetStatisticsUseCase')]
// [RELATION: ViewModel('DashboardViewModel')] -> [DEPENDS_ON] -> [UseCase('GetAllLocationsUseCase')]
// [RELATION: ViewModel('DashboardViewModel')] -> [DEPENDS_ON] -> [UseCase('GetAllLabelsUseCase')]
// [RELATION: ViewModel('DashboardViewModel')] -> [DEPENDS_ON] -> [UseCase('GetRecentlyAddedItemsUseCase')]
// [RELATION: ViewModel('DashboardViewModel')] -> [EMITS_STATE] -> [SealedInterface('DashboardUiState')]
/**
* [CONTRACT]
* @summary ViewModel для главного экрана (Dashboard).
* @description Оркестрирует загрузку данных для Dashboard, используя строгую модель состояний
* (`DashboardUiState`), и обрабатывает параллельные запросы без состояний гонки.
* @invariant `uiState` всегда является одним из состояний, определенных в `DashboardUiState`.
*/
@HiltViewModel
class DashboardViewModel
@Inject
constructor(
private val getStatisticsUseCase: GetStatisticsUseCase,
private val getAllLocationsUseCase: GetAllLocationsUseCase,
private val getAllLabelsUseCase: GetAllLabelsUseCase,
private val getRecentlyAddedItemsUseCase: GetRecentlyAddedItemsUseCase,
) : ViewModel() {
// [STATE]
private val _uiState = MutableStateFlow<DashboardUiState>(DashboardUiState.Loading)
class DashboardViewModel @Inject constructor(
private val getStatisticsUseCase: GetStatisticsUseCase,
private val getAllLocationsUseCase: GetAllLocationsUseCase,
private val getAllLabelsUseCase: GetAllLabelsUseCase,
private val getRecentlyAddedItemsUseCase: GetRecentlyAddedItemsUseCase
) : ViewModel() {
// [FIX] Добавлен получатель (receiver) `_uiState` для вызова asStateFlow().
// [REASON] `asStateFlow()` является функцией-расширением для `MutableStateFlow` и
// должна вызываться на его экземпляре, чтобы создать публичную, неизменяемую версию потока.
val uiState = _uiState.asStateFlow()
private val _uiState = MutableStateFlow<DashboardUiState>(DashboardUiState.Loading)
val uiState = _uiState.asStateFlow()
// [LIFECYCLE_HANDLER]
init {
loadDashboardData()
}
init {
loadDashboardData()
}
// [ENTITY: Function('loadDashboardData')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('viewModelScope.launch')]
// [RELATION: Function('loadDashboardData') -> [WRITES_TO] -> Property('_uiState')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('Timber.i')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('flow')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('getStatisticsUseCase')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('getAllLocationsUseCase')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('getAllLabelsUseCase')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('getRecentlyAddedItemsUseCase')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('combine')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('catch')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('Timber.e')]
// [RELATION: Function('loadDashboardData') -> [CALLS] -> Function('collect')]
/**
* [CONTRACT]
* @summary Загружает все необходимые данные для экрана Dashboard.
* @description Выполняет UseCase'ы параллельно и обновляет UI, переключая его
* между состояниями `Loading`, `Success` и `Error` из `DashboardUiState`.
* @sideeffect Асинхронно обновляет `_uiState` одним из состояний `DashboardUiState`.
*/
fun loadDashboardData() {
viewModelScope.launch {
_uiState.value = DashboardUiState.Loading
Timber.i("[ACTION] Starting dashboard data collection.")
// [ENTITY: Function('loadDashboardData')]
/**
* @summary Загружает все необходимые данные для экрана Dashboard.
* @description Выполняет UseCase'ы параллельно и обновляет UI, переключая его
* между состояниями `Loading`, `Success` и `Error` из `DashboardUiState`.
* @sideeffect Асинхронно обновляет `_uiState` одним из состояний `DashboardUiState`.
*/
fun loadDashboardData() {
viewModelScope.launch {
_uiState.value = DashboardUiState.Loading
Timber.i("[INFO][ENTRYPOINT][loading_dashboard_data] Starting dashboard data collection.")
val statsFlow = flow { emit(getStatisticsUseCase()) }
val locationsFlow = flow { emit(getAllLocationsUseCase()) }
val labelsFlow = flow { emit(getAllLabelsUseCase()) }
val recentItemsFlow = getRecentlyAddedItemsUseCase(limit = 10)
val statsFlow = flow { emit(getStatisticsUseCase()) }
val locationsFlow = flow { emit(getAllLocationsUseCase()) }
val labelsFlow = flow { emit(getAllLabelsUseCase()) }
val recentItemsFlow = getRecentlyAddedItemsUseCase(limit = 10)
combine(statsFlow, locationsFlow, labelsFlow, recentItemsFlow) { stats, locations, labels, recentItems ->
DashboardUiState.Success(
statistics = stats,
locations = locations,
labels = labels,
recentlyAddedItems = recentItems,
)
}.catch { exception ->
Timber.e(exception, "[ERROR] Failed to load dashboard data. State -> Error.")
_uiState.value =
DashboardUiState.Error(
message = exception.message ?: "Could not load dashboard data.",
)
}.collect { successState ->
Timber.i("[SUCCESS] Dashboard data loaded successfully. State -> Success.")
_uiState.value = successState
}
combine(statsFlow, locationsFlow, labelsFlow, recentItemsFlow) { stats, locations, labels, recentItems ->
DashboardUiState.Success(
statistics = stats,
locations = locations,
labels = labels,
recentlyAddedItems = recentItems
)
}.catch { exception ->
Timber.e(exception, "[ERROR][EXCEPTION][loading_failed] Failed to load dashboard data. State -> Error.")
_uiState.value = DashboardUiState.Error(
message = exception.message ?: "Could not load dashboard data."
)
}.collect { successState ->
Timber.i("[INFO][SUCCESS][dashboard_data_loaded] Dashboard data loaded successfully. State -> Success.")
_uiState.value = successState
}
}
// [END_ENTITY: Function('loadDashboardData')]
}
// [END_ENTITY: Function('loadDashboardData')]
}
// [END_ENTITY: ViewModel('DashboardViewModel')]
// [END_CONTRACT]
// [END_FILE_DashboardViewModel.kt]
// [END_FILE_DashboardViewModel.kt]

View File

@@ -1,219 +1,39 @@
// [PACKAGE] com.homebox.lens.ui.screen.inventorylist
// [FILE] InventoryListScreen.kt
// [SEMANTICS] ui, screen, inventory, list, compose
// [SEMANTICS] ui, screen, inventory, list
package com.homebox.lens.ui.screen.inventorylist
// [IMPORTS]
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
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.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.homebox.lens.R
import com.homebox.lens.domain.model.Item
import timber.log.Timber
import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.ui.common.MainScaffold
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('InventoryListScreen')]
// [RELATION: Function('InventoryListScreen') -> [DEPENDS_ON] -> Class('InventoryListViewModel')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('collectAsState')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('Scaffold')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('TopAppBar')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('Text')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('FloatingActionButton')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('SearchBar')]
// [RELATION: Function('InventoryListScreen') -> [CALLS] -> Function('InventoryListContent')]
// [RELATION: Function('InventoryListScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('InventoryListScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* [MAIN-CONTRACT]
* Экран для отображения списка инвентарных позиций.
*
* Реализует спецификацию `screen_inventory_list`. Позволяет просматривать,
* искать и синхронизировать инвентарь.
*
* @param onItemClick Обработчик нажатия на элемент инвентаря.
* @param onNavigateBack Обработчик для возврата на предыдущий экран.
* @summary Composable-функция для экрана "Список инвентаря".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InventoryListScreen(
viewModel: InventoryListViewModel = hiltViewModel(),
onItemClick: (Item) -> Unit,
onNavigateBack: () -> Unit
currentRoute: String?,
navigationActions: NavigationActions
) {
// [STATE]
val uiState by viewModel.uiState.collectAsState()
// [ACTION]
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(id = R.string.inventory_list_title)) }, // Corrected string resource name
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.content_desc_navigate_back)
)
}
}
)
},
floatingActionButton = {
FloatingActionButton(onClick = {
Timber.i("[INFO][ACTION][ui_interaction] Sync inventory triggered.")
viewModel.onSyncClicked()
}) {
Icon(
imageVector = Icons.Filled.Refresh,
contentDescription = stringResource(id = R.string.content_desc_sync_inventory)
)
}
}
) { innerPadding ->
// [DELEGATES]
Column(modifier = Modifier.padding(innerPadding)) {
SearchBar(
query = uiState.searchQuery,
onQueryChange = viewModel::onSearchQueryChanged
)
InventoryListContent(
isLoading = uiState.isLoading,
items = uiState.items,
onItemClick = onItemClick
)
}
MainScaffold(
topBarTitle = stringResource(id = R.string.inventory_list_title),
currentRoute = currentRoute,
navigationActions = navigationActions
) {
// [AI_NOTE]: Implement Inventory List Screen UI
Text(text = "Inventory List Screen")
}
}
// [END_ENTITY: Function('InventoryListScreen')]
// [ENTITY: Function('SearchBar')]
// [RELATION: Function('SearchBar') -> [CALLS] -> Function('TextField')]
// [RELATION: Function('SearchBar') -> [CALLS] -> Function('Text')]
// [RELATION: Function('SearchBar') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('SearchBar') -> [CALLS] -> Function('Icon')]
/**
* [CONTRACT]
* Поле для ввода поискового запроса.
*/
@Composable
private fun SearchBar(query: String, onQueryChange: (String) -> Unit) {
TextField(
value = query,
onValueChange = onQueryChange,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
placeholder = { Text(stringResource(id = R.string.search)) }, // Corrected string resource name
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) }
)
}
// [END_ENTITY: Function('SearchBar')]
// [ENTITY: Function('InventoryListContent')]
// [RELATION: Function('InventoryListContent') -> [CALLS] -> Function('Box')]
// [RELATION: Function('InventoryListContent') -> [CALLS] -> Function('CircularProgressIndicator')]
// [RELATION: Function('InventoryListContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('InventoryListContent') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('InventoryListContent') -> [CALLS] -> Function('LazyColumn')]
// [RELATION: Function('InventoryListContent') -> [CALLS] -> Function('ItemCard')]
/**
* [CONTRACT]
* Основной контент: индикатор загрузки или список предметов.
*/
@Composable
private fun InventoryListContent(
isLoading: Boolean,
items: List<Item>,
onItemClick: (Item) -> Unit
) {
Box(modifier = Modifier.fillMaxSize()) {
if (isLoading) {
// [STATE]
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
} else if (items.isEmpty()) {
// [FALLBACK]
Text(
text = stringResource(id = R.string.items_not_found),
modifier = Modifier.align(Alignment.Center)
)
} else {
// [CORE-LOGIC]
LazyColumn {
items(items, key = { it.id }) { item ->
ItemCard(item = item, onClick = {
Timber.i("[INFO][ACTION][ui_interaction] Item clicked: ${item.name}")
onItemClick(item)
})
}
}
}
}
}
// [END_ENTITY: Function('InventoryListContent')]
// [ENTITY: Function('ItemCard')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('Card')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('Column')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('Text')]
// [RELATION: Function('ItemCard') -> [CALLS] -> Function('clickable')]
/**
* [CONTRACT]
* Карточка для отображения одного элемента инвентаря.
*/
@Composable
private fun ItemCard(
item: Item,
onClick: () -> Unit
) {
// [PRECONDITION]
require(item.name.isNotBlank()) { "Item name cannot be blank." }
// [CORE-LOGIC]
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 4.dp)
.clickable(onClick = onClick)
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(text = item.name, style = androidx.compose.material3.MaterialTheme.typography.titleMedium)
Text(text = "Quantity: ${item.quantity.toString()}", style = androidx.compose.material3.MaterialTheme.typography.bodySmall)
item.location?.let {
Text(text = "Location: ${it.name}", style = androidx.compose.material3.MaterialTheme.typography.bodySmall)
}
}
}
}
// [END_ENTITY: Function('ItemCard')]
// [END_CONTRACT]
// [END_FILE_InventoryListScreen.kt]
// [END_FILE_InventoryListScreen.kt]

View File

@@ -1,53 +1,21 @@
// [PACKAGE] com.homebox.lens.ui.screen.inventorylist
// [FILE] InventoryListViewModel.kt
// [SEMANTICS] ui_logic, inventory_list, viewmodel
// [SEMANTICS] ui, viewmodel, inventory_list
package com.homebox.lens.ui.screen.inventorylist
// [IMPORTS]
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.homebox.lens.domain.model.Item
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('InventoryListViewModel')]
// [RELATION: ViewModel('InventoryListViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('InventoryListViewModel') -> [DEPENDS_ON] -> Annotation('HiltViewModel')]
/**
* [CONTRACT]
* @summary ViewModel for the InventoryListScreen.
* @summary ViewModel for the inventory list screen.
*/
@HiltViewModel
class InventoryListViewModel
@Inject
constructor() : ViewModel() {
// [STATE]
private val _uiState = MutableStateFlow(InventoryListUiState())
val uiState: StateFlow<InventoryListUiState> = _uiState.asStateFlow()
fun onSyncClicked() {
// TODO: Implement sync logic
}
fun onSearchQueryChanged(query: String) {
// TODO: Implement search query change logic
}
}
class InventoryListViewModel @Inject constructor() : ViewModel() {
// [AI_NOTE]: Implement UI state
}
// [END_ENTITY: ViewModel('InventoryListViewModel')]
// [END_CONTRACT]
// [END_FILE_InventoryListViewModel.kt]
// [CONTRACT]
// [ENTITY: DataClass('InventoryListUiState')]
// [RELATION: DataClass('InventoryListUiState') -> [DEPENDS_ON] -> Class('Item')]
data class InventoryListUiState(
val searchQuery: String = "",
val isLoading: Boolean = false,
val items: List<Item> = emptyList()
)
// [END_ENTITY: DataClass('InventoryListUiState')]
// [END_FILE_InventoryListViewModel.kt]

View File

@@ -1,208 +1,39 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemdetails
// [FILE] ItemDetailsScreen.kt
// [SEMANTICS] ui, screen, item, details, compose
// [SEMANTICS] ui, screen, item, details
package com.homebox.lens.ui.screen.itemdetails
// [IMPORTS]
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
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.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.homebox.lens.R
import com.homebox.lens.domain.model.Item
import timber.log.Timber
import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.ui.common.MainScaffold
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('ItemDetailsScreen')]
// [RELATION: Function('ItemDetailsScreen') -> [DEPENDS_ON] -> Class('ItemDetailsViewModel')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('collectAsState')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('Scaffold')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('TopAppBar')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('Text')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('ItemDetailsScreen') -> [CALLS] -> Function('ItemDetailsContent')]
// [RELATION: Function('ItemDetailsScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('ItemDetailsScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* [MAIN-CONTRACT]
* Экран для отображения детальной информации о товаре.
*
* Реализует спецификацию `screen_item_details`.
*
* @param onNavigateBack Обработчик для возврата на предыдущий экран.
* @param onEditClick Обработчик нажатия на кнопку редактирования.
* @summary Composable-функция для экрана "Детали элемента".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemDetailsScreen(
viewModel: ItemDetailsViewModel = hiltViewModel(),
onNavigateBack: () -> Unit,
onEditClick: (Int) -> Unit
currentRoute: String?,
navigationActions: NavigationActions
) {
// [STATE]
val uiState by viewModel.uiState.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = { Text(uiState.item?.name ?: stringResource(id = R.string.item_details_title)) }, // Corrected string resource name
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(id = R.string.content_desc_navigate_back))
}
},
actions = {
IconButton(onClick = {
uiState.item?.id?.let {
Timber.i("[INFO][ACTION][ui_interaction] Edit item clicked: id=$it")
onEditClick(it.toInt())
}
}) {
Icon(Icons.Default.Edit, contentDescription = stringResource(id = R.string.content_desc_edit_item))
}
IconButton(onClick = {
Timber.w("[WARN][ACTION][ui_interaction] Delete item clicked: id=${uiState.item?.id}")
viewModel.deleteItem()
// После удаления нужно навигироваться назад
onNavigateBack()
}) {
Icon(Icons.Default.Delete, contentDescription = stringResource(id = R.string.content_desc_delete_item))
}
}
)
}
) { innerPadding ->
ItemDetailsContent(
modifier = Modifier.padding(innerPadding),
isLoading = uiState.isLoading,
item = uiState.item
)
MainScaffold(
topBarTitle = stringResource(id = R.string.item_details_title),
currentRoute = currentRoute,
navigationActions = navigationActions
) {
// [AI_NOTE]: Implement Item Details Screen UI
Text(text = "Item Details Screen")
}
}
// [END_ENTITY: Function('ItemDetailsScreen')]
// [ENTITY: Function('ItemDetailsContent')]
// [RELATION: Function('ItemDetailsContent') -> [DEPENDS_ON] -> Class('Item')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('Box')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('CircularProgressIndicator')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('Column')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('verticalScroll')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('rememberScrollState')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('DetailsSection')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('InfoRow')]
// [RELATION: Function('ItemDetailsContent') -> [CALLS] -> Function('AssistChip')]
/**
* [CONTRACT]
* Отображает контент экрана: индикатор загрузки или детали товара.
*/
@Composable
private fun ItemDetailsContent(
modifier: Modifier = Modifier,
isLoading: Boolean,
item: Item?
) {
Box(modifier = modifier.fillMaxSize()) {
when {
isLoading -> {
// [STATE]
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
item == null -> {
// [FALLBACK]
Text(stringResource(id = R.string.items_not_found), modifier = Modifier.align(Alignment.Center))
}
else -> {
// [CORE-LOGIC]
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// TODO: ImageCarousel
// Text("Image Carousel Placeholder")
DetailsSection(title = stringResource(id = R.string.section_title_description)) {
Text(text = item.description ?: stringResource(id = R.string.placeholder_no_description))
}
DetailsSection(title = stringResource(id = R.string.section_title_details)) {
InfoRow(label = stringResource(id = R.string.label_quantity), value = item.quantity.toString())
item.location?.let {
InfoRow(label = stringResource(id = R.string.label_location), value = it.name)
}
}
if (item.labels.isNotEmpty()) {
DetailsSection(title = stringResource(id = R.string.section_title_labels)) {
// TODO: Use FlowRow for better layout
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
item.labels.forEach { label ->
AssistChip(onClick = { /* No-op */ }, label = { Text(label.name) })
}
}
}
}
// TODO: CustomFieldsGrid
}
}
}
}
}
// [END_ENTITY: Function('ItemDetailsContent')]
// [ENTITY: Function('DetailsSection')]
// [RELATION: Function('DetailsSection') -> [CALLS] -> Function('Column')]
// [RELATION: Function('DetailsSection') -> [CALLS] -> Function('Text')]
// [RELATION: Function('DetailsSection') -> [CALLS] -> Function('MaterialTheme.typography.titleMedium')]
// [RELATION: Function('DetailsSection') -> [CALLS] -> Function('Divider')]
/**
* [CONTRACT]
* Секция с заголовком и контентом.
*/
@Composable
private fun DetailsSection(title: String, content: @Composable ColumnScope.() -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(text = title, style = MaterialTheme.typography.titleMedium)
Divider()
content()
}
}
// [END_ENTITY: Function('DetailsSection')]
// [ENTITY: Function('InfoRow')]
// [RELATION: Function('InfoRow') -> [CALLS] -> Function('Row')]
// [RELATION: Function('InfoRow') -> [CALLS] -> Function('Text')]
// [RELATION: Function('InfoRow') -> [CALLS] -> Function('MaterialTheme.typography.bodyLarge')]
/**
* [CONTRACT]
* Строка для отображения пары "метка: значение".
*/
@Composable
private fun InfoRow(label: String, value: String) {
Row {
Text(text = "$label: ", style = MaterialTheme.typography.bodyLarge)
Text(text = value, style = MaterialTheme.typography.bodyLarge)
}
}
// [END_ENTITY: Function('InfoRow')]
// [END_CONTRACT]
// [END_FILE_ItemDetailsScreen.kt]
// [END_FILE_ItemDetailsScreen.kt]

View File

@@ -1,43 +1,21 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemdetails
// [FILE] ItemDetailsViewModel.kt
// [SEMANTICS] ui, viewmodel, item_details
package com.homebox.lens.ui.screen.itemdetails
// [IMPORTS]
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import com.homebox.lens.domain.model.Item
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('ItemDetailsViewModel')]
// [RELATION: ViewModel('ItemDetailsViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('ItemDetailsViewModel') -> [DEPENDS_ON] -> Annotation('HiltViewModel')]
/**
* [CONTRACT]
* @summary ViewModel for the ItemDetailsScreen.
* @summary ViewModel for the item details screen.
*/
@HiltViewModel
class ItemDetailsViewModel
@Inject
constructor() : ViewModel() {
// [STATE]
// TODO: Implement UI state
val uiState = MutableStateFlow(ItemDetailsUiState()).asStateFlow()
fun deleteItem() {
// TODO: Implement delete item logic
}
}
class ItemDetailsViewModel @Inject constructor() : ViewModel() {
// [AI_NOTE]: Implement UI state
}
// [END_ENTITY: ViewModel('ItemDetailsViewModel')]
// [END_CONTRACT]
// [END_FILE_ItemDetailsViewModel.kt]
// Placeholder for ItemDetailsUiState to resolve compilation errors
data class ItemDetailsUiState(
val item: Item? = null,
val isLoading: Boolean = false
)

View File

@@ -1,162 +1,139 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemedit
// [FILE] ItemEditScreen.kt
// [SEMANTICS] ui, screen, item, edit, create, compose
// [SEMANTICS] ui, screen, item, edit
package com.homebox.lens.ui.screen.itemedit
// [IMPORTS]
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Done
import androidx.compose.material3.*
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.homebox.lens.R
import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.ui.common.MainScaffold
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('ItemEditScreen')]
// [RELATION: Function('ItemEditScreen') -> [DEPENDS_ON] -> Class('ItemEditViewModel')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('collectAsState')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('LaunchedEffect')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('Timber.i')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('Scaffold')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('TopAppBar')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('Text')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('ItemEditScreen') -> [CALLS] -> Function('ItemEditContent')]
// [RELATION: Function('ItemEditScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('ItemEditScreen')] -> [DEPENDS_ON] -> [ViewModel('ItemEditViewModel')]
// [RELATION: Function('ItemEditScreen')] -> [CONSUMES_STATE] -> [DataClass('ItemEditUiState')]
// [RELATION: Function('ItemEditScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* [MAIN-CONTRACT]
* Экран для создания или редактирования товара.
*
* Реализует спецификацию `screen_item_edit`.
*
* @param onNavigateBack Обработчик для возврата на предыдущий экран после сохранения или отмены.
* @summary Composable-функция для экрана "Редактирование элемента".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
* @param itemId ID элемента для редактирования. Null, если создается новый элемент.
* @param viewModel ViewModel для управления состоянием экрана.
* @param onSaveSuccess Callback, вызываемый после успешного сохранения товара.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemEditScreen(
viewModel: ItemEditViewModel = hiltViewModel(),
onNavigateBack: () -> Unit
currentRoute: String?,
navigationActions: NavigationActions,
itemId: String?,
viewModel: ItemEditViewModel = viewModel(),
onSaveSuccess: () -> Unit
) {
// [STATE]
val uiState by viewModel.uiState.collectAsState()
val snackbarHostState = remember { SnackbarHostState() }
// [SIDE-EFFECT]
LaunchedEffect(uiState.isSaved) {
if (uiState.isSaved) {
Timber.i("[INFO][SIDE_EFFECT][navigation] Item saved, navigating back.")
onNavigateBack()
LaunchedEffect(itemId) {
Timber.i("[INFO][ENTRYPOINT][item_edit_screen_init] Initializing ItemEditScreen for item ID: %s", itemId)
viewModel.loadItem(itemId)
}
LaunchedEffect(uiState.error) {
uiState.error?.let {
snackbarHostState.showSnackbar(it)
Timber.e("[ERROR][UI_ERROR][item_edit_error] Displaying error: %s", it)
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(id = if (uiState.isEditing) R.string.item_edit_title else R.string.item_edit_title_create)) }, // Corrected string resource names
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(id = R.string.content_desc_navigate_back))
}
},
actions = {
IconButton(onClick = {
Timber.i("[INFO][ACTION][ui_interaction] Save item clicked.")
viewModel.saveItem()
}) {
Icon(Icons.Default.Done, contentDescription = stringResource(id = R.string.content_desc_save_item))
LaunchedEffect(Unit) {
viewModel.saveCompleted.collect {
Timber.i("[INFO][ACTION][save_completed_callback] Item save completed. Triggering onSaveSuccess.")
onSaveSuccess()
}
}
MainScaffold(
topBarTitle = stringResource(id = R.string.item_edit_title),
currentRoute = currentRoute,
navigationActions = navigationActions
) {
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
floatingActionButton = {
FloatingActionButton(onClick = {
Timber.i("[INFO][ACTION][save_button_click] Save button clicked.")
viewModel.saveItem()
}) {
Icon(Icons.Filled.Save, contentDescription = stringResource(R.string.save_item))
}
}
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(it)
.padding(16.dp)
) {
if (uiState.isLoading) {
CircularProgressIndicator(modifier = Modifier.fillMaxWidth())
} else {
uiState.item?.let { item ->
OutlinedTextField(
value = item.name,
onValueChange = { viewModel.updateName(it) },
label = { Text(stringResource(R.string.item_name)) },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = item.description ?: "",
onValueChange = { viewModel.updateDescription(it) },
label = { Text(stringResource(R.string.item_description)) },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = item.quantity.toString(),
onValueChange = { viewModel.updateQuantity(it.toIntOrNull() ?: 0) },
label = { Text(stringResource(R.string.item_quantity)) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
modifier = Modifier.fillMaxWidth()
)
// Add more fields as needed
}
}
)
}
}
) { innerPadding ->
ItemEditContent(
modifier = Modifier.padding(innerPadding),
state = uiState,
onNameChange = { viewModel.onNameChange(it) },
onDescriptionChange = { viewModel.onDescriptionChange(it) },
onQuantityChange = { viewModel.onQuantityChange(it) }
)
}
}
// [END_ENTITY: Function('ItemEditScreen')]
// [ENTITY: Function('ItemEditContent')]
// [RELATION: Function('ItemEditContent') -> [DEPENDS_ON] -> Class('ItemEditUiState')]
// [RELATION: Function('ItemEditContent') -> [CALLS] -> Function('Column')]
// [RELATION: Function('ItemEditContent') -> [CALLS] -> Function('verticalScroll')]
// [RELATION: Function('ItemEditContent') -> [CALLS] -> Function('rememberScrollState')]
// [RELATION: Function('ItemEditContent') -> [CALLS] -> Function('OutlinedTextField')]
// [RELATION: Function('ItemEditContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('ItemEditContent') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('ItemEditContent') -> [CALLS] -> Function('MaterialTheme.colorScheme.error')]
/**
* [CONTRACT]
* Отображает форму для редактирования данных товара.
*/
@Composable
private fun ItemEditContent(
modifier: Modifier = Modifier,
state: ItemEditUiState,
onNameChange: (String) -> Unit,
onDescriptionChange: (String) -> Unit,
onQuantityChange: (String) -> Unit
) {
// [CORE-LOGIC]
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
OutlinedTextField(
value = state.name,
onValueChange = onNameChange,
label = { Text(stringResource(id = R.string.label_name)) },
modifier = Modifier.fillMaxWidth(),
isError = state.nameError != null
)
state.nameError?.let {
Text(text = stringResource(id = it), color = MaterialTheme.colorScheme.error)
}
OutlinedTextField(
value = state.description,
onValueChange = onDescriptionChange,
label = { Text(stringResource(id = R.string.label_description)) },
modifier = Modifier.fillMaxWidth(),
minLines = 3
)
OutlinedTextField(
value = state.quantity,
onValueChange = onQuantityChange,
label = { Text(stringResource(id = R.string.label_quantity)) },
modifier = Modifier.fillMaxWidth(),
isError = state.quantityError != null
)
state.quantityError?.let {
Text(text = stringResource(id = it), color = MaterialTheme.colorScheme.error)
}
// TODO: Location Dropdown
// TODO: Labels ChipGroup
// TODO: ImagePicker
}
}
// [END_ENTITY: Function('ItemEditContent')]
// [END_CONTRACT]
// [END_FILE_ItemEditScreen.kt]
// [END_FILE_ItemEditScreen.kt]

View File

@@ -1,59 +1,214 @@
// [PACKAGE] com.homebox.lens.ui.screen.itemedit
// [FILE] ItemEditViewModel.kt
// [SEMANTICS] ui, viewmodel, item_edit
package com.homebox.lens.ui.screen.itemedit
// [IMPORTS]
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.homebox.lens.domain.model.Item
import com.homebox.lens.domain.model.ItemCreate
import com.homebox.lens.domain.model.Label
import com.homebox.lens.domain.model.Location
import com.homebox.lens.domain.usecase.CreateItemUseCase
import com.homebox.lens.domain.usecase.GetItemDetailsUseCase
import com.homebox.lens.domain.usecase.UpdateItemUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('ItemEditViewModel')]
// [RELATION: ViewModel('ItemEditViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('ItemEditViewModel') -> [DEPENDS_ON] -> Annotation('HiltViewModel')]
// [ENTITY: DataClass('ItemEditUiState')]
/**
* [CONTRACT]
* @summary ViewModel for the ItemEditScreen.
* @summary UI state for the item edit screen.
* @param item The item being edited, or null if creating a new item.
* @param isLoading Whether data is currently being loaded or saved.
* @param error An error message if an operation failed.
*/
data class ItemEditUiState(
val item: Item? = null,
val isLoading: Boolean = false,
val error: String? = null
)
// [END_ENTITY: DataClass('ItemEditUiState')]
// [ENTITY: ViewModel('ItemEditViewModel')]
// [RELATION: ViewModel('ItemEditViewModel')] -> [DEPENDS_ON] -> [UseCase('CreateItemUseCase')]
// [RELATION: ViewModel('ItemEditViewModel')] -> [DEPENDS_ON] -> [UseCase('UpdateItemUseCase')]
// [RELATION: ViewModel('ItemEditViewModel')] -> [DEPENDS_ON] -> [UseCase('GetItemDetailsUseCase')]
// [RELATION: ViewModel('ItemEditViewModel')] -> [EMITS_STATE] -> [DataClass('ItemEditUiState')]
/**
* @summary ViewModel for the item edit screen.
*/
@HiltViewModel
class ItemEditViewModel
@Inject
constructor() : ViewModel() {
// [STATE]
// TODO: Implement UI state
val uiState = MutableStateFlow(ItemEditUiState()).asStateFlow()
class ItemEditViewModel @Inject constructor(
private val createItemUseCase: CreateItemUseCase,
private val updateItemUseCase: UpdateItemUseCase,
private val getItemDetailsUseCase: GetItemDetailsUseCase
) : ViewModel() {
fun saveItem() {
// TODO: Implement save item logic
}
private val _uiState = MutableStateFlow(ItemEditUiState())
val uiState: StateFlow<ItemEditUiState> = _uiState.asStateFlow()
fun onNameChange(name: String) {
// TODO: Implement name change logic
}
private val _saveCompleted = MutableSharedFlow<Unit>()
val saveCompleted: SharedFlow<Unit> = _saveCompleted.asSharedFlow()
fun onDescriptionChange(description: String) {
// TODO: Implement description change logic
}
fun onQuantityChange(quantity: String) {
// TODO: Implement quantity change logic
// [ENTITY: Function('loadItem')]
/**
* @summary Loads item details for editing or prepares for new item creation.
* @param itemId The ID of the item to load. If null, a new item is being created.
* @sideeffect Updates `_uiState` with loading, success, or error states.
*/
fun loadItem(itemId: String?) {
Timber.i("[INFO][ENTRYPOINT][loading_item] Attempting to load item with ID: %s", itemId)
viewModelScope.launch {
_uiState.value = _uiState.value.copy(isLoading = true, error = null)
if (itemId == null) {
Timber.i("[INFO][ACTION][new_item_preparation] Preparing for new item creation.")
_uiState.value = _uiState.value.copy(isLoading = false, item = Item(id = "", name = "", description = null, quantity = 0, image = null, location = null, labels = emptyList(), value = null, createdAt = null))
} else {
try {
Timber.i("[INFO][ACTION][fetching_item_details] Fetching details for item ID: %s", itemId)
val itemOut = getItemDetailsUseCase(itemId)
Timber.d("[DEBUG][ACTION][mapping_item_out_to_item] Mapping ItemOut to Item for UI state.")
val item = Item(
id = itemOut.id,
name = itemOut.name,
description = itemOut.description,
quantity = itemOut.quantity,
image = itemOut.images.firstOrNull()?.path, // Assuming first image is the main one
location = itemOut.location?.let { Location(it.id, it.name) }, // Simplified mapping
labels = itemOut.labels.map { Label(it.id, it.name) }, // Simplified mapping
value = itemOut.value?.toBigDecimal(),
createdAt = itemOut.createdAt
)
_uiState.value = _uiState.value.copy(isLoading = false, item = item)
Timber.i("[INFO][ACTION][item_details_fetched] Successfully fetched item details for ID: %s", itemId)
} catch (e: Exception) {
Timber.e(e, "[ERROR][FALLBACK][item_load_failed] Failed to load item details for ID: %s", itemId)
_uiState.value = _uiState.value.copy(isLoading = false, error = e.localizedMessage)
}
}
}
}
// [END_ENTITY: ViewModel('ItemEditViewModel')]
// [END_CONTRACT]
// [END_FILE_ItemEditViewModel.kt]
// [END_ENTITY: Function('loadItem')]
// Placeholder for ItemEditUiState to resolve compilation errors
data class ItemEditUiState(
val isSaved: Boolean = false,
val isEditing: Boolean = false,
val name: String = "",
val description: String = "",
val quantity: String = "",
val nameError: Int? = null,
val quantityError: Int? = null
)
// [ENTITY: Function('saveItem')]
/**
* @summary Saves the current item, either creating a new one or updating an existing one.
* @sideeffect Updates `_uiState` with loading, success, or error states. Calls `createItemUseCase` or `updateItemUseCase`.
* @throws IllegalStateException if `uiState.value.item` is null when attempting to save.
*/
fun saveItem() {
Timber.i("[INFO][ENTRYPOINT][saving_item] Attempting to save item.")
viewModelScope.launch {
val currentItem = _uiState.value.item
require(currentItem != null) { "[CONTRACT_VIOLATION][PRECONDITION][item_not_present] Cannot save a null item." }
_uiState.value = _uiState.value.copy(isLoading = true, error = null)
try {
if (currentItem.id.isBlank()) {
Timber.i("[INFO][ACTION][creating_new_item] Creating new item: %s", currentItem.name)
val createdItemSummary = createItemUseCase(ItemCreate(
name = currentItem.name,
description = currentItem.description,
quantity = currentItem.quantity,
assetId = null,
notes = null,
serialNumber = null,
value = null,
purchasePrice = null,
purchaseDate = null,
warrantyUntil = null,
locationId = currentItem.location?.id,
parentId = null,
labelIds = currentItem.labels.map { it.id }
))
Timber.d("[DEBUG][ACTION][mapping_item_summary_to_item] Mapping ItemSummary to Item for UI state.")
val createdItem = Item(
id = createdItemSummary.id,
name = createdItemSummary.name,
description = null, // ItemSummary does not have description
quantity = 0, // ItemSummary does not have quantity
image = null, // ItemSummary does not have image
location = null, // ItemSummary does not have location
labels = emptyList(), // ItemSummary does not have labels
value = null, // ItemSummary does not have value
createdAt = null // ItemSummary does not have createdAt
)
_uiState.value = _uiState.value.copy(isLoading = false, item = createdItem)
Timber.i("[INFO][ACTION][new_item_created] Successfully created new item with ID: %s", createdItem.id)
_saveCompleted.emit(Unit)
} else {
Timber.i("[INFO][ACTION][updating_existing_item] Updating existing item with ID: %s", currentItem.id)
val updatedItemOut = updateItemUseCase(currentItem)
Timber.d("[DEBUG][ACTION][mapping_item_out_to_item] Mapping ItemOut to Item for UI state.")
val updatedItem = Item(
id = updatedItemOut.id,
name = updatedItemOut.name,
description = updatedItemOut.description,
quantity = updatedItemOut.quantity,
image = updatedItemOut.images.firstOrNull()?.path,
location = updatedItemOut.location?.let { Location(it.id, it.name) },
labels = updatedItemOut.labels.map { Label(it.id, it.name) },
value = updatedItemOut.value.toBigDecimal(),
createdAt = updatedItemOut.createdAt
)
_uiState.value = _uiState.value.copy(isLoading = false, item = updatedItem)
Timber.i("[INFO][ACTION][item_updated] Successfully updated item with ID: %s", updatedItem.id)
_saveCompleted.emit(Unit)
}
} catch (e: Exception) {
Timber.e(e, "[ERROR][FALLBACK][item_save_failed] Failed to save item.")
_uiState.value = _uiState.value.copy(isLoading = false, error = e.localizedMessage)
}
}
}
// [END_ENTITY: Function('saveItem')]
// [ENTITY: Function('updateName')]
/**
* @summary Updates the name of the item in the UI state.
* @param newName The new name for the item.
* @sideeffect Updates the `item` in `_uiState`.
*/
fun updateName(newName: String) {
Timber.d("[DEBUG][ACTION][updating_item_name] Updating item name to: %s", newName)
_uiState.value = _uiState.value.copy(item = _uiState.value.item?.copy(name = newName))
}
// [END_ENTITY: Function('updateName')]
// [ENTITY: Function('updateDescription')]
/**
* @summary Updates the description of the item in the UI state.
* @param newDescription The new description for the item.
* @sideeffect Updates the `item` in `_uiState`.
*/
fun updateDescription(newDescription: String) {
Timber.d("[DEBUG][ACTION][updating_item_description] Updating item description to: %s", newDescription)
_uiState.value = _uiState.value.copy(item = _uiState.value.item?.copy(description = newDescription))
}
// [END_ENTITY: Function('updateDescription')]
// [ENTITY: Function('updateQuantity')]
/**
* @summary Updates the quantity of the item in the UI state.
* @param newQuantity The new quantity for the item.
* @sideeffect Updates the `item` in `_uiState`.
*/
fun updateQuantity(newQuantity: Int) {
Timber.d("[DEBUG][ACTION][updating_item_quantity] Updating item quantity to: %d", newQuantity)
_uiState.value = _uiState.value.copy(item = _uiState.value.item?.copy(quantity = newQuantity))
}
// [END_ENTITY: Function('updateQuantity')]
}
// [END_ENTITY: ViewModel('ItemEditViewModel')]
// [END_FILE_ItemEditViewModel.kt]

View File

@@ -1,14 +1,15 @@
// [PACKAGE]com.homebox.lens.ui.screen.labelslist
// [FILE]LabelsListScreen.kt
// [SEMANTICS]ui, screen, labels, list, compose
// [PACKAGE] com.homebox.lens.ui.screen.labelslist
// [FILE] LabelsListScreen.kt
// [SEMANTICS] ui, labels_list, state_management, compose, dialog
package com.homebox.lens.ui.screen.labelslist
// [IMPORTS]
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
@@ -16,105 +17,118 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Label
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.homebox.lens.R
import com.homebox.lens.domain.model.Label
import com.homebox.lens.ui.screen.labelslist.LabelsListUiState
import com.homebox.lens.navigation.Screen
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('LabelsListScreen')]
// [RELATION: Function('LabelsListScreen') -> [DEPENDS_ON] -> SealedInterface('LabelsListUiState')]
// [RELATION: Function('LabelsListScreen') -> [CREATES_INSTANCE_OF] -> Class('Scaffold')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('LabelsListContent')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('Text')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('FloatingActionButton')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('Column')]
// [RELATION: Function('LabelsListScreen') -> [CALLS] -> Function('CircularProgressIndicator')]
// [RELATION: Function('LabelsListScreen')] -> [DEPENDS_ON] -> [ViewModel('LabelsListViewModel')]
// [RELATION: Function('LabelsListScreen')] -> [DEPENDS_ON] -> [Framework('NavController')]
/**
* [MAIN-CONTRACT]
* Экран для отображения списка всех меток.
*
* Этот Composable является точкой входа для UI, определенного в спецификации `screen_labels_list`.
* Он получает состояние от [LabelsListViewModel] и отображает его, делегируя обработку
* пользовательских событий в ViewModel.
*
* @param uiState Текущее состояние UI для экрана списка меток.
* @param onLabelClick Функция обратного вызова для обработки нажатия на метку.
* @param onAddClick Функция обратного вызова для обработки нажатия на кнопку добавления метки.
* @param onNavigateBack Функция обратного вызова для навигации назад.
* @summary Отображает экран со списком всех меток.
* @param navController Контроллер навигации для перемещения между экранами.
* @param viewModel ViewModel, предоставляющая состояние UI для экрана меток.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun labelsListScreen(
uiState: LabelsListUiState,
onLabelClick: (Label) -> Unit,
onAddClick: () -> Unit,
onNavigateBack: () -> Unit,
fun LabelsListScreen(
navController: NavController,
viewModel: LabelsListViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(id = R.string.screen_title_labels)) },
title = { Text(text = stringResource(id = R.string.screen_title_labels)) },
navigationIcon = {
IconButton(onClick = onNavigateBack) {
IconButton(onClick = {
Timber.i("[INFO][ACTION][navigate_up] Navigate up initiated.")
navController.navigateUp()
}) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.content_desc_navigate_back)
)
}
},
}
)
},
floatingActionButton = {
FloatingActionButton(onClick = onAddClick) {
FloatingActionButton(onClick = {
Timber.i("[INFO][ACTION][show_create_dialog] FAB clicked: Initiate create new label flow.")
viewModel.onShowCreateDialog()
}) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = stringResource(id = R.string.content_desc_add_label)
imageVector = Icons.Default.Add,
contentDescription = stringResource(id = R.string.content_desc_create_label)
)
}
}
) { innerPadding ->
Box(modifier = Modifier.padding(innerPadding)) {
when (uiState) {
is LabelsListUiState.Loading -> {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator()
}
) { paddingValues ->
val currentState = uiState
if (currentState is LabelsListUiState.Success && currentState.isShowingCreateDialog) {
CreateLabelDialog(
onConfirm = { labelName ->
viewModel.createLabel(labelName)
},
onDismiss = {
viewModel.onDismissCreateDialog()
}
is LabelsListUiState.Success -> {
LabelsListContent(
uiState = uiState,
onLabelClick = onLabelClick
)
)
}
Box(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
contentAlignment = Alignment.Center
) {
when (currentState) {
is LabelsListUiState.Loading -> {
CircularProgressIndicator()
}
is LabelsListUiState.Error -> {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = uiState.message)
Text(text = currentState.message)
}
is LabelsListUiState.Success -> {
if (currentState.labels.isEmpty()) {
Text(text = stringResource(id = R.string.labels_list_empty))
} else {
LabelsList(
labels = currentState.labels,
onLabelClick = { label ->
Timber.i("[INFO][ACTION][navigate_to_inventory] Label clicked: ${label.id}. Navigating to inventory list.")
val route = Screen.InventoryList.withFilter("label", label.id)
navController.navigate(route)
}
)
}
}
}
@@ -123,81 +137,100 @@ fun labelsListScreen(
}
// [END_ENTITY: Function('LabelsListScreen')]
// [ENTITY: Function('LabelsListContent')]
// [RELATION: Function('LabelsListContent') -> [CALLS] -> Function('LabelListItem')]
// [RELATION: Function('LabelsListContent') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LabelsListContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('LabelsListContent') -> [CALLS] -> Function('Column')]
// [RELATION: Function('LabelsListContent') -> [CALLS] -> Function('LazyColumn')]
// [ENTITY: Function('LabelsList')]
// [RELATION: Function('LabelsList')] -> [DEPENDS_ON] -> [DataClass('Label')]
/**
* [CONTRACT]
* Отображает основной контент экрана: список меток.
*
* @param uiState Состояние успеха, содержащее список меток.
* @param onLabelClick Обработчик нажатия на элемент списка.
* @sideeffect Отсутствуют.
* @summary Composable-функция для отображения списка меток.
* @param labels Список объектов `Label` для отображения.
* @param onLabelClick Лямбда-функция, вызываемая при нажатии на элемент списка.
* @param modifier Модификатор для настройки внешнего вида.
*/
@Composable
private fun LabelsListContent(
uiState: LabelsListUiState.Success,
onLabelClick: (Label) -> Unit
private fun LabelsList(
labels: List<Label>,
onLabelClick: (Label) -> Unit,
modifier: Modifier = Modifier
) {
if (uiState.labels.isEmpty()) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = stringResource(id = R.string.no_labels_found))
}
} else {
LazyColumn {
items(uiState.labels, key = { it.id }) { label ->
LabelListItem(
label = label,
onClick = {
Timber.i("[INFO][ACTION][ui_interaction] Label clicked: ${label.name}")
onLabelClick(label)
}
)
}
LazyColumn(
modifier = modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(labels, key = { it.id }) { label ->
LabelListItem(
label = label,
onClick = { onLabelClick(label) }
)
}
}
}
// [END_ENTITY: Function('LabelsListContent')]
// [END_ENTITY: Function('LabelsList')]
// [ENTITY: Function('LabelListItem')]
// [RELATION: Function('LabelListItem') -> [CALLS] -> Function('ListItem')]
// [RELATION: Function('LabelListItem') -> [CALLS] -> Function('Text')]
// [RELATION: Function('LabelListItem') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('LabelListItem')] -> [DEPENDS_ON] -> [DataClass('Label')]
/**
* [CONTRACT]
* Отображает один элемент в списке меток.
*
* @param label Метка для отображения.
* @param onClick Обработчик нажатия на элемент.
* @sideeffect Отсутствуют.
* @summary Composable-функция для отображения одного элемента в списке меток.
* @param label Объект `Label`, который нужно отобразить.
* @param onClick Лямбда-функция, вызываемая при нажатии на элемент.
*/
@Composable
private fun LabelListItem(
label: Label,
onClick: () -> Unit
) {
// [PRECONDITION]
require(label.name.isNotBlank()) { "Label name cannot be blank." }
// [CORE-LOGIC]
ListItem(
headlineContent = { Text(label.name) },
headlineContent = { Text(text = label.name) },
leadingContent = {
Icon(
imageVector = Icons.AutoMirrored.Filled.Label,
contentDescription = null // Декоративный элемент
contentDescription = stringResource(id = R.string.content_desc_label_icon)
)
},
modifier = Modifier.clickable(onClick = onClick)
)
}
// [END_ENTITY: Function('LabelListItem')]
// [END_CONTRACT]
// [ENTITY: Function('CreateLabelDialog')]
/**
* @summary Диалоговое окно для создания новой метки.
* @param onConfirm Лямбда-функция, вызываемая при подтверждении создания с именем метки.
* @param onDismiss Лямбда-функция, вызываемая при закрытии диалога.
*/
@Composable
private fun CreateLabelDialog(
onConfirm: (String) -> Unit,
onDismiss: () -> Unit
) {
var text by remember { mutableStateOf("") }
val isConfirmEnabled = text.isNotBlank()
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(text = stringResource(R.string.dialog_title_create_label)) },
text = {
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text(stringResource(R.string.dialog_field_label_name)) },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
},
confirmButton = {
TextButton(
onClick = { onConfirm(text) },
enabled = isConfirmEnabled
) {
Text(stringResource(R.string.dialog_button_create))
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.dialog_button_cancel))
}
}
)
}
// [END_ENTITY: Function('CreateLabelDialog')]
// [END_FILE_LabelsListScreen.kt]

View File

@@ -1,53 +1,48 @@
// [PACKAGE]com.homebox.lens.ui.screen.labelslist
// [FILE]LabelsListUiState.kt
// [SEMANTICS]ui_state, sealed_interface, contract
// [PACKAGE] com.homebox.lens.ui.screen.labelslist
// [FILE] LabelsListUiState.kt
// [SEMANTICS] ui_state, sealed_interface, contract
package com.homebox.lens.ui.screen.labelslist
// [IMPORTS]
import com.homebox.lens.domain.model.Label
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: SealedInterface('LabelsListUiState')]
/**
* [CONTRACT]
* @summary Определяет все возможные состояния для UI экрана со списком меток.
* @description Использование sealed-интерфейса позволяет исчерпывающе обрабатывать все состояния в Composable-функциях.
*/
sealed interface LabelsListUiState {
// [ENTITY: DataClass('Success')]
// [RELATION: DataClass('Success') -> [IMPLEMENTS] -> SealedInterface('LabelsListUiState')]
// [RELATION: DataClass('Success') -> [DEPENDS_ON] -> DataStructure('Label')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('Label')]
/**
* @summary Состояние успеха, содержит список меток и состояние диалога.
* @property labels Список меток для отображения.
* @property isShowingCreateDialog Флаг, показывающий, должен ли быть отображен диалог создания метки.
* @param labels Список меток для отображения.
* @param isShowingCreateDialog Флаг, показывающий, должен ли быть отображен диалог создания метки.
* @invariant labels не может быть null.
*/
data class Success(
val labels: List<Label>,
val isShowingCreateDialog: Boolean = false
) : LabelsListUiState
// [END_ENTITY: DataClass('Success')]
// [ENTITY: DataClass('Error')]
// [RELATION: DataClass('Error') -> [IMPLEMENTS] -> SealedInterface('LabelsListUiState')]
/**
* @summary Состояние ошибки.
* @property message Текст ошибки для отображения пользователю, или `null` при отсутствии ошибки.
* @param message Текст ошибки для отображения пользователю.
* @invariant message не может быть пустой.
*/
data class Error(
val message: String
) : LabelsListUiState
data class Error(val message: String) : LabelsListUiState
// [END_ENTITY: DataClass('Error')]
// [ENTITY: Object('Loading')]
// [RELATION: Object('Loading') -> [IMPLEMENTS] -> SealedInterface('LabelsListUiState')]
/**
* @summary Состояние загрузки данных.
* @description Указывает, что идет процесс загрузки меток.
*/
object Loading : LabelsListUiState
data object Loading : LabelsListUiState
// [END_ENTITY: Object('Loading')]
}
// [END_ENTITY: SealedInterface('LabelsListUiState')]
// [END_CONTRACT]
// [END_FILE_LabelsListUiState.kt]

View File

@@ -17,154 +17,115 @@ import timber.log.Timber
import javax.inject.Inject
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('LabelsListViewModel')]
// [RELATION: ViewModel('LabelsListViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('LabelsListViewModel') -> [DEPENDS_ON] -> Annotation('HiltViewModel')]
// [RELATION: ViewModel('LabelsListViewModel') -> [DEPENDS_ON] -> Class('GetAllLabelsUseCase')]
// [RELATION: ViewModel('LabelsListViewModel')] -> [DEPENDS_ON] -> [UseCase('GetAllLabelsUseCase')]
// [RELATION: ViewModel('LabelsListViewModel')] -> [EMITS_STATE] -> [SealedInterface('LabelsListUiState')]
/**
* [CONTRACT]
* @summary ViewModel для экрана со списком меток.
* @description Управляет состоянием экрана, загружает список меток, обрабатывает ошибки и управляет диалогом создания новой метки.
* @invariant `uiState` всегда является одним из состояний, определенных в `LabelsListUiState`.
*/
@HiltViewModel
class LabelsListViewModel
@Inject
constructor(
private val getAllLabelsUseCase: GetAllLabelsUseCase,
) : ViewModel() {
// [STATE]
private val _uiState = MutableStateFlow<LabelsListUiState>(LabelsListUiState.Loading)
val uiState = _uiState.asStateFlow()
class LabelsListViewModel @Inject constructor(
private val getAllLabelsUseCase: GetAllLabelsUseCase
) : ViewModel() {
// [INIT]
init {
loadLabels()
}
private val _uiState = MutableStateFlow<LabelsListUiState>(LabelsListUiState.Loading)
val uiState = _uiState.asStateFlow()
// [ENTITY: Function('loadLabels')]
// [RELATION: Function('loadLabels') -> [CALLS] -> Function('viewModelScope.launch')]
// [RELATION: Function('loadLabels') -> [WRITES_TO] -> Property('_uiState')]
// [RELATION: Function('loadLabels') -> [CALLS] -> Function('Timber.i')]
// [RELATION: Function('loadLabels') -> [CALLS] -> Function('runCatching')]
// [RELATION: Function('loadLabels') -> [CALLS] -> Function('getAllLabelsUseCase')]
// [RELATION: Function('loadLabels') -> [CALLS] -> Function('result.fold')]
// [RELATION: Function('loadLabels') -> [CALLS] -> Function('Timber.e')]
// [RELATION: Function('loadLabels') -> [CREATES_INSTANCE_OF] -> Class('Label')]
/**
* [CONTRACT]
* @summary Загружает список меток.
* @description Выполняет `GetAllLabelsUseCase` и обновляет UI, переключая его
* между состояниями `Loading`, `Success` и `Error`.
* @sideeffect Асинхронно обновляет `_uiState`.
*/
// [ACTION]
fun loadLabels() {
viewModelScope.launch {
_uiState.value = LabelsListUiState.Loading
Timber.i("[ACTION] Starting labels list load. State -> Loading.")
init {
loadLabels()
}
// [CORE-LOGIC]
val result =
runCatching {
getAllLabelsUseCase()
// [ENTITY: Function('loadLabels')]
/**
* @summary Загружает список меток.
* @description Выполняет `GetAllLabelsUseCase` и обновляет UI, переключая его
* между состояниями `Loading`, `Success` и `Error`.
* @sideeffect Асинхронно обновляет `_uiState`.
*/
fun loadLabels() {
viewModelScope.launch {
_uiState.value = LabelsListUiState.Loading
Timber.i("[INFO][ENTRYPOINT][loading_labels] Starting labels list load. State -> Loading.")
val result = runCatching {
getAllLabelsUseCase()
}
result.fold(
onSuccess = { labelOuts ->
Timber.i("[INFO][SUCCESS][labels_loaded] Labels loaded successfully. Count: ${labelOuts.size}. State -> Success.")
val labels = labelOuts.map { labelOut ->
Label(
id = labelOut.id,
name = labelOut.name
)
}
// [RESULT_HANDLER]
result.fold(
onSuccess = { labelOuts ->
Timber.i("[SUCCESS] Labels loaded successfully. Count: ${labelOuts.size}. State -> Success.")
// [DATA-FLOW] Map List<LabelOut> to List<Label> for the UI state.
// The 'Label' model for the UI is simpler and only contains 'id' and 'name'.
val labels =
labelOuts.map { labelOut ->
Label(
id = labelOut.id,
name = labelOut.name,
)
}
_uiState.value = LabelsListUiState.Success(labels, isShowingCreateDialog = false)
},
onFailure = { exception ->
Timber.e(exception, "[ERROR] Failed to load labels. State -> Error.")
_uiState.value =
LabelsListUiState.Error(
message = exception.message ?: "Could not load labels.",
)
},
)
}
}
// [END_ENTITY: Function('loadLabels')]
// [ENTITY: Function('onShowCreateDialog')]
// [RELATION: Function('onShowCreateDialog') -> [CALLS] -> Function('Timber.i')]
// [RELATION: Function('onShowCreateDialog') -> [CALLS] -> Function('_uiState.update')]
/**
* [CONTRACT]
* @summary Инициирует отображение диалога для создания метки.
* @description Обновляет состояние `uiState`, устанавливая `isShowingCreateDialog` в `true`.
* @sideeffect Обновляет `_uiState`.
*/
// [ACTION]
fun onShowCreateDialog() {
Timber.i("[ACTION] Show create label dialog requested.")
if (_uiState.value is LabelsListUiState.Success) {
_uiState.update {
(it as LabelsListUiState.Success).copy(isShowingCreateDialog = true)
_uiState.value = LabelsListUiState.Success(labels, isShowingCreateDialog = false)
},
onFailure = { exception ->
Timber.e(exception, "[ERROR][EXCEPTION][loading_failed] Failed to load labels. State -> Error.")
_uiState.value = LabelsListUiState.Error(
message = exception.message ?: "Could not load labels."
)
}
}
}
// [END_ENTITY: Function('onShowCreateDialog')]
// [ENTITY: Function('onDismissCreateDialog')]
// [RELATION: Function('onDismissCreateDialog') -> [CALLS] -> Function('Timber.i')]
// [RELATION: Function('onDismissCreateDialog') -> [CALLS] -> Function('_uiState.update')]
/**
* [CONTRACT]
* @summary Скрывает диалог создания метки.
* @description Обновляет состояние `uiState`, устанавливая `isShowingCreateDialog` в `false`..
* @sideeffect Обновляет `_uiState`.
*/
// [ACTION]
fun onDismissCreateDialog() {
Timber.i("[ACTION] Dismiss create label dialog requested.")
if (_uiState.value is LabelsListUiState.Success) {
_uiState.update {
(it as LabelsListUiState.Success).copy(isShowingCreateDialog = false)
}
}
}
// [END_ENTITY: Function('onDismissCreateDialog')]
// [ENTITY: Function('createLabel')]
// [RELATION: Function('createLabel') -> [CALLS] -> Function('require')]
// [RELATION: Function('createLabel') -> [CALLS] -> Function('Timber.i')]
// [RELATION: Function('createLabel') -> [CALLS] -> Function('onDismissCreateDialog')]
/**
* [CONTRACT]
* @summary Создает новую метку. [MVP_SCOPE] ЗАГЛУШКА.
* @description В текущей реализации (План Б, Этап 1), эта функция только логирует действие
* и скрывает диалог. Реальная логика сохранения будет добавлена на следующем этапе.
* @param name Название новой метки.
* @precondition `name` не должен быть пустым.
* @sideeffect Логирует действие, обновляет `_uiState`, чтобы скрыть диалог.
*/
// [ACTION]
fun createLabel(name: String) {
// [PRECONDITION]
require(name.isNotBlank()) { "[CONTRACT_VIOLATION] Label name cannot be blank." }
Timber.i("[ACTION] Create label called with name: '$name'. [STUBBED]")
// [CORE-LOGIC] - Заглушка. Здесь будет вызов CreateLabelUseCase.
// [POSTCONDITION] Скрываем диалог после "создания".
onDismissCreateDialog()
// [REFACTORING_NOTE] На следующем этапе нужно добавить вызов UseCase и обновить список.
)
}
}
// [END_ENTITY: Function('loadLabels')]
// [ENTITY: Function('onShowCreateDialog')]
/**
* @summary Инициирует отображение диалога для создания метки.
* @description Обновляет состояние `uiState`, устанавливая `isShowingCreateDialog` в `true`.
* @sideeffect Обновляет `_uiState`.
*/
fun onShowCreateDialog() {
Timber.i("[INFO][ACTION][show_create_dialog] Show create label dialog requested.")
if (_uiState.value is LabelsListUiState.Success) {
_uiState.update {
(it as LabelsListUiState.Success).copy(isShowingCreateDialog = true)
}
}
}
// [END_ENTITY: Function('onShowCreateDialog')]
// [ENTITY: Function('onDismissCreateDialog')]
/**
* @summary Скрывает диалог создания метки.
* @description Обновляет состояние `uiState`, устанавливая `isShowingCreateDialog` в `false`.
* @sideeffect Обновляет `_uiState`.
*/
fun onDismissCreateDialog() {
Timber.i("[INFO][ACTION][dismiss_create_dialog] Dismiss create label dialog requested.")
if (_uiState.value is LabelsListUiState.Success) {
_uiState.update {
(it as LabelsListUiState.Success).copy(isShowingCreateDialog = false)
}
}
}
// [END_ENTITY: Function('onDismissCreateDialog')]
// [ENTITY: Function('createLabel')]
/**
* @summary Создает новую метку. [MVP_SCOPE] ЗАГЛУШКА.
* @description В текущей реализации (План Б, Этап 1), эта функция только логирует действие
* и скрывает диалог. Реальная логика сохранения будет добавлена на следующем этапе.
* @param name Название новой метки.
* @precondition `name` не должен быть пустым.
* @sideeffect Логирует действие, обновляет `_uiState`, чтобы скрыть диалог.
*/
fun createLabel(name: String) {
require(name.isNotBlank()) { "[CONTRACT_VIOLATION] Label name cannot be blank." }
Timber.i("[INFO][ACTION][create_label] Create label called with name: '$name'. [STUBBED]")
// [AI_NOTE]: Здесь будет вызов CreateLabelUseCase.
onDismissCreateDialog()
}
// [END_ENTITY: Function('createLabel')]
}
// [END_ENTITY: ViewModel('LabelsListViewModel')]
// [END_CONTRACT]
// [END_FILE_LabelsListViewModel.kt]

View File

@@ -17,38 +17,32 @@ import androidx.compose.ui.res.stringResource
import com.homebox.lens.R
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('LocationEditScreen')]
// [RELATION: Function('LocationEditScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LocationEditScreen') -> [CALLS] -> Function('Scaffold')]
// [RELATION: Function('LocationEditScreen') -> [CALLS] -> Function('Box')]
// [RELATION: Function('LocationEditScreen') -> [CALLS] -> Function('Text')]
/**
* [CONTRACT]
* @summary Composable-функция для экрана "Редактирование местоположения".
* @param locationId ID местоположения для редактирования или "new" для создания.
*/
@Composable
fun LocationEditScreen(locationId: String?) {
val title =
if (locationId == "new") {
stringResource(id = R.string.location_edit_title_create)
} else {
stringResource(id = R.string.location_edit_title_edit)
}
fun LocationEditScreen(
locationId: String?
) {
val title = if (locationId == "new") {
stringResource(id = R.string.location_edit_title_create)
} else {
stringResource(id = R.string.location_edit_title_edit)
}
Scaffold { paddingValues ->
Box(
modifier =
Modifier
.fillMaxSize()
.padding(paddingValues),
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
contentAlignment = Alignment.Center
) {
Text(text = "TODO: Location Edit Screen for ID: $locationId")
// [AI_NOTE]: Implement Location Edit Screen UI
Text(text = "Location Edit Screen for ID: $locationId")
}
}
}
// [END_ENTITY: Function('LocationEditScreen')]
// [END_CONTRACT]
// [END_FILE_LocationEditScreen.kt]
// [END_FILE_LocationEditScreen.kt]

View File

@@ -51,20 +51,11 @@ import com.homebox.lens.ui.common.MainScaffold
import com.homebox.lens.ui.theme.HomeboxLensTheme
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('LocationsListScreen')]
// [RELATION: Function('LocationsListScreen') -> [DEPENDS_ON] -> Class('NavigationActions')]
// [RELATION: Function('LocationsListScreen') -> [DEPENDS_ON] -> Class('LocationsListViewModel')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('collectAsState')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('MainScaffold')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('Scaffold')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('FloatingActionButton')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('LocationsListScreen') -> [CALLS] -> Function('LocationsListContent')]
// [RELATION: Function('LocationsListScreen')] -> [DEPENDS_ON] -> [ViewModel('LocationsListViewModel')]
// [RELATION: Function('LocationsListScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('LocationsListScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* [CONTRACT]
* @summary Composable-функция для экрана "Список местоположений".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
@@ -78,16 +69,14 @@ fun LocationsListScreen(
navigationActions: NavigationActions,
onLocationClick: (String) -> Unit,
onAddNewLocationClick: () -> Unit,
viewModel: LocationsListViewModel = hiltViewModel(),
viewModel: LocationsListViewModel = hiltViewModel()
) {
// [STATE]
val uiState by viewModel.uiState.collectAsState()
// [UI_COMPONENT]
MainScaffold(
topBarTitle = stringResource(id = R.string.locations_list_title),
currentRoute = currentRoute,
navigationActions = navigationActions,
navigationActions = navigationActions
) { paddingValues ->
Scaffold(
modifier = Modifier.padding(paddingValues),
@@ -95,17 +84,17 @@ fun LocationsListScreen(
FloatingActionButton(onClick = onAddNewLocationClick) {
Icon(
Icons.Default.Add,
contentDescription = stringResource(id = R.string.cd_add_new_location),
contentDescription = stringResource(id = R.string.cd_add_new_location)
)
}
},
}
) { innerPadding ->
LocationsListContent(
modifier = Modifier.padding(innerPadding),
uiState = uiState,
onLocationClick = onLocationClick,
onEditLocation = { /* TODO */ },
onDeleteLocation = { /* TODO */ },
onEditLocation = { /* [AI_NOTE]: Implement onEditLocation */ },
onDeleteLocation = { /* [AI_NOTE]: Implement onDeleteLocation */ }
)
}
}
@@ -113,16 +102,8 @@ fun LocationsListScreen(
// [END_ENTITY: Function('LocationsListScreen')]
// [ENTITY: Function('LocationsListContent')]
// [RELATION: Function('LocationsListContent') -> [DEPENDS_ON] -> SealedInterface('LocationsListUiState')]
// [RELATION: Function('LocationsListContent') -> [CALLS] -> Function('Box')]
// [RELATION: Function('LocationsListContent') -> [CALLS] -> Function('CircularProgressIndicator')]
// [RELATION: Function('LocationsListContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('LocationsListContent') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LocationsListContent') -> [CALLS] -> Function('MaterialTheme.colorScheme.error')]
// [RELATION: Function('LocationsListContent') -> [CALLS] -> Function('LazyColumn')]
// [RELATION: Function('LocationsListContent') -> [CALLS] -> Function('LocationCard')]
// [RELATION: Function('LocationsListContent')] -> [CONSUMES_STATE] -> [SealedInterface('LocationsListUiState')]
/**
* [CONTRACT]
* @summary Отображает основной контент экрана в зависимости от `uiState`.
* @param modifier Модификатор для стилизации.
* @param uiState Текущее состояние UI.
@@ -136,7 +117,7 @@ private fun LocationsListContent(
uiState: LocationsListUiState,
onLocationClick: (String) -> Unit,
onEditLocation: (String) -> Unit,
onDeleteLocation: (String) -> Unit,
onDeleteLocation: (String) -> Unit
) {
Box(modifier = modifier.fillMaxSize()) {
when (uiState) {
@@ -148,10 +129,9 @@ private fun LocationsListContent(
text = uiState.message,
color = MaterialTheme.colorScheme.error,
textAlign = TextAlign.Center,
modifier =
Modifier
.align(Alignment.Center)
.padding(16.dp),
modifier = Modifier
.align(Alignment.Center)
.padding(16.dp)
)
}
is LocationsListUiState.Success -> {
@@ -159,22 +139,21 @@ private fun LocationsListContent(
Text(
text = stringResource(id = R.string.locations_not_found),
textAlign = TextAlign.Center,
modifier =
Modifier
.align(Alignment.Center)
.padding(16.dp),
modifier = Modifier
.align(Alignment.Center)
.padding(16.dp)
)
} else {
LazyColumn(
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
items(uiState.locations, key = { it.id }) { location ->
LocationCard(
location = location,
onClick = { onLocationClick(location.id) },
onEditClick = { onEditLocation(location.id) },
onDeleteClick = { onDeleteLocation(location.id) },
onDeleteClick = { onDeleteLocation(location.id) }
)
}
}
@@ -186,25 +165,8 @@ private fun LocationsListContent(
// [END_ENTITY: Function('LocationsListContent')]
// [ENTITY: Function('LocationCard')]
// [RELATION: Function('LocationCard') -> [DEPENDS_ON] -> Class('LocationOutCount')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('remember')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('mutableStateOf')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('Card')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('clickable')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('Row')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('Column')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('Text')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('MaterialTheme.typography.titleMedium')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('MaterialTheme.typography.bodyMedium')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('Spacer')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('Box')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('DropdownMenu')]
// [RELATION: Function('LocationCard') -> [CALLS] -> Function('DropdownMenuItem')]
// [RELATION: Function('LocationCard')] -> [DEPENDS_ON] -> [DataClass('LocationOutCount')]
/**
* [CONTRACT]
* @summary Карточка для отображения одного местоположения.
* @param location Данные о местоположении.
* @param onClick Лямбда-обработчик нажатия на карточку.
@@ -216,26 +178,25 @@ private fun LocationCard(
location: LocationOutCount,
onClick: () -> Unit,
onEditClick: () -> Unit,
onDeleteClick: () -> Unit,
onDeleteClick: () -> Unit
) {
var menuExpanded by remember { mutableStateOf(false) }
Card(
modifier =
Modifier
.fillMaxWidth()
.clickable(onClick = onClick),
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
) {
Row(
modifier = Modifier.padding(start = 16.dp, end = 8.dp, top = 16.dp, bottom = 16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text(text = location.name, style = MaterialTheme.typography.titleMedium)
Text(
text = stringResource(id = R.string.item_count, location.itemCount),
style = MaterialTheme.typography.bodyMedium,
style = MaterialTheme.typography.bodyMedium
)
}
Spacer(Modifier.width(16.dp))
@@ -245,21 +206,21 @@ private fun LocationCard(
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false },
onDismissRequest = { menuExpanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(id = R.string.edit)) },
onClick = {
menuExpanded = false
onEditClick()
},
}
)
DropdownMenuItem(
text = { Text(stringResource(id = R.string.delete)) },
onClick = {
menuExpanded = false
onDeleteClick()
},
}
)
}
}
@@ -269,36 +230,26 @@ private fun LocationCard(
// [END_ENTITY: Function('LocationCard')]
// [ENTITY: Function('LocationsListSuccessPreview')]
// [RELATION: Function('LocationsListSuccessPreview') -> [CALLS] -> Function('LocationOutCount')]
// [RELATION: Function('LocationsListSuccessPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('LocationsListSuccessPreview') -> [CALLS] -> Function('LocationsListContent')]
// [RELATION: Function('LocationsListSuccessPreview') -> [CALLS] -> Function('LocationsListUiState.Success')]
// [PREVIEW]
@Preview(showBackground = true, name = "Locations List Success")
@Composable
fun LocationsListSuccessPreview() {
val previewLocations =
listOf(
LocationOutCount("1", "Garage", "#FF0000", false, 12, "", ""),
LocationOutCount("2", "Kitchen", "#00FF00", false, 5, "", ""),
LocationOutCount("3", "Office", "#0000FF", false, 23, "", ""),
)
val previewLocations = listOf(
LocationOutCount("1", "Garage", "#FF0000", false, 12, "", ""),
LocationOutCount("2", "Kitchen", "#00FF00", false, 5, "", ""),
LocationOutCount("3", "Office", "#0000FF", false, 23, "", "")
)
HomeboxLensTheme {
LocationsListContent(
uiState = LocationsListUiState.Success(previewLocations),
onLocationClick = {},
onEditLocation = {},
onDeleteLocation = {},
onDeleteLocation = {}
)
}
}
// [END_ENTITY: Function('LocationsListSuccessPreview')]
// [ENTITY: Function('LocationsListEmptyPreview')]
// [RELATION: Function('LocationsListEmptyPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('LocationsListEmptyPreview') -> [CALLS] -> Function('LocationsListContent')]
// [RELATION: Function('LocationsListEmptyPreview') -> [CALLS] -> Function('LocationsListUiState.Success')]
// [PREVIEW]
@Preview(showBackground = true, name = "Locations List Empty")
@Composable
fun LocationsListEmptyPreview() {
@@ -307,17 +258,13 @@ fun LocationsListEmptyPreview() {
uiState = LocationsListUiState.Success(emptyList()),
onLocationClick = {},
onEditLocation = {},
onDeleteLocation = {},
onDeleteLocation = {}
)
}
}
// [END_ENTITY: Function('LocationsListEmptyPreview')]
// [ENTITY: Function('LocationsListLoadingPreview')]
// [RELATION: Function('LocationsListLoadingPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('LocationsListLoadingPreview') -> [CALLS] -> Function('LocationsListContent')]
// [RELATION: Function('LocationsListLoadingPreview') -> [CALLS] -> Function('LocationsListUiState.Loading')]
// [PREVIEW]
@Preview(showBackground = true, name = "Locations List Loading")
@Composable
fun LocationsListLoadingPreview() {
@@ -326,18 +273,13 @@ fun LocationsListLoadingPreview() {
uiState = LocationsListUiState.Loading,
onLocationClick = {},
onEditLocation = {},
onDeleteLocation = {},
onDeleteLocation = {}
)
}
}
// [END_ENTITY: Function('LocationsListLoadingPreview')]
// [ENTITY: Function('LocationsListErrorPreview')]
// [RELATION: Function('LocationsListErrorPreview') -> [CALLS] -> Function('HomeboxLensTheme')]
// [RELATION: Function('LocationsListErrorPreview') -> [CALLS] -> Function('LocationsListContent')]
// [RELATION: Function('LocationsListErrorPreview') -> [CALLS] -> Function('LocationsListUiState.Error')]
// [RELATION: Function('LocationsListErrorPreview') -> [CALLS] -> Function('stringResource')]
// [PREVIEW]
@Preview(showBackground = true, name = "Locations List Error")
@Composable
fun LocationsListErrorPreview() {
@@ -346,10 +288,9 @@ fun LocationsListErrorPreview() {
uiState = LocationsListUiState.Error("Failed to load locations. Please try again."),
onLocationClick = {},
onEditLocation = {},
onDeleteLocation = {},
onDeleteLocation = {}
)
}
}
// [END_ENTITY: Function('LocationsListErrorPreview')]
// [END_CONTRACT]
// [END_FILE_LocationsListScreen.kt]
// [END_FILE_LocationsListScreen.kt]

View File

@@ -8,18 +8,15 @@ package com.homebox.lens.ui.screen.locationslist
import com.homebox.lens.domain.model.LocationOutCount
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: SealedInterface('LocationsListUiState')]
/**
* [CONTRACT]
* @summary Определяет возможные состояния UI для экрана списка местоположений.
* @see LocationsListViewModel
*/
sealed interface LocationsListUiState {
// [ENTITY: DataClass('Success')]
// [RELATION: DataClass('Success') -> [DEPENDS_ON] -> Class('LocationOutCount')]
// [RELATION: DataClass('Success')] -> [DEPENDS_ON] -> [DataClass('LocationOutCount')]
/**
* [STATE]
* @summary Состояние успешной загрузки данных.
* @param locations Список местоположений для отображения.
*/
@@ -28,21 +25,18 @@ sealed interface LocationsListUiState {
// [ENTITY: DataClass('Error')]
/**
* [STATE]
* @summary Состояние ошибки.
* @param message Сообщение об ошибке.
*/
data class Error(val message: String) : LocationsListUiState
// [END_ENTITY: DataClass('Error')]
// [ENTITY: DataObject('Loading')]
// [ENTITY: Object('Loading')]
/**
* [STATE]
* @summary Состояние загрузки данных.
*/
object Loading : LocationsListUiState
// [END_ENTITY: DataObject('Loading')]
// [END_ENTITY: Object('Loading')]
}
// [END_ENTITY: SealedInterface('LocationsListUiState')]
// [END_CONTRACT]
// [END_FILE_LocationsListUiState.kt]
// [END_FILE_LocationsListUiState.kt]

View File

@@ -13,58 +13,52 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('LocationsListViewModel')]
// [RELATION: ViewModel('LocationsListViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('LocationsListViewModel') -> [DEPENDS_ON] -> Annotation('HiltViewModel')]
// [RELATION: ViewModel('LocationsListViewModel') -> [DEPENDS_ON] -> Class('GetAllLocationsUseCase')]
// [RELATION: ViewModel('LocationsListViewModel')] -> [DEPENDS_ON] -> [UseCase('GetAllLocationsUseCase')]
// [RELATION: ViewModel('LocationsListViewModel')] -> [EMITS_STATE] -> [SealedInterface('LocationsListUiState')]
/**
* [CONTRACT]
* @summary ViewModel для экрана списка местоположений.
* @param getAllLocationsUseCase Use case для получения всех местоположений.
* @property uiState Поток, содержащий текущее состояние UI.
* @invariant `uiState` всегда отражает результат последней операции загрузки.
*/
@HiltViewModel
class LocationsListViewModel
@Inject
constructor(
private val getAllLocationsUseCase: GetAllLocationsUseCase,
) : ViewModel() {
// [STATE]
private val _uiState = MutableStateFlow<LocationsListUiState>(LocationsListUiState.Loading)
val uiState: StateFlow<LocationsListUiState> = _uiState.asStateFlow()
class LocationsListViewModel @Inject constructor(
private val getAllLocationsUseCase: GetAllLocationsUseCase
) : ViewModel() {
// [INITIALIZER]
init {
loadLocations()
}
private val _uiState = MutableStateFlow<LocationsListUiState>(LocationsListUiState.Loading)
val uiState: StateFlow<LocationsListUiState> = _uiState.asStateFlow()
// [ENTITY: Function('loadLocations')]
// [RELATION: Function('loadLocations') -> [CALLS] -> Function('viewModelScope.launch')]
// [RELATION: Function('loadLocations') -> [WRITES_TO] -> Property('_uiState')]
// [RELATION: Function('loadLocations') -> [CALLS] -> Function('getAllLocationsUseCase')]
/**
* [CONTRACT]
* @summary Загружает список местоположений из репозитория.
* @sideeffect Обновляет `_uiState` в зависимости от результата: Loading -> Success/Error.
*/
fun loadLocations() {
viewModelScope.launch {
_uiState.value = LocationsListUiState.Loading
try {
val locations = getAllLocationsUseCase()
_uiState.value = LocationsListUiState.Success(locations)
} catch (e: Exception) {
_uiState.value = LocationsListUiState.Error(e.message ?: "Unknown error")
}
init {
loadLocations()
}
// [ENTITY: Function('loadLocations')]
/**
* @summary Загружает список местоположений из репозитория.
* @sideeffect Обновляет `_uiState` в зависимости от результата: Loading -> Success/Error.
*/
fun loadLocations() {
Timber.d("[DEBUG][ENTRYPOINT][loading_locations] Starting to load locations.")
viewModelScope.launch {
_uiState.value = LocationsListUiState.Loading
try {
Timber.d("[DEBUG][ACTION][fetching_locations] Fetching locations from use case.")
val locations = getAllLocationsUseCase()
_uiState.value = LocationsListUiState.Success(locations)
Timber.d("[DEBUG][SUCCESS][locations_loaded] Successfully loaded locations.")
} catch (e: Exception) {
Timber.e(e, "[ERROR][EXCEPTION][loading_failed] Failed to load locations.")
_uiState.value = LocationsListUiState.Error(e.message ?: "Unknown error")
}
}
// [END_ENTITY: Function('loadLocations')]
}
// [END_ENTITY: Function('loadLocations')]
}
// [END_ENTITY: ViewModel('LocationsListViewModel')]
// [END_CONTRACT]
// [END_FILE_LocationsListViewModel.kt]

View File

@@ -1,129 +1,39 @@
// [PACKAGE] com.homebox.lens.ui.screen.search
// [FILE] SearchScreen.kt
// [SEMANTICS] ui, screen, search, compose
// [SEMANTICS] ui, screen, search
package com.homebox.lens.ui.screen.search
// [IMPORTS]
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.homebox.lens.R
import com.homebox.lens.domain.model.Item
import com.homebox.lens.navigation.NavigationActions
import com.homebox.lens.ui.common.MainScaffold
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('SearchScreen')]
// [RELATION: Function('SearchScreen') -> [DEPENDS_ON] -> Class('SearchViewModel')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('collectAsState')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('Scaffold')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('TopAppBar')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('TextField')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('Text')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('IconButton')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('Icon')]
// [RELATION: Function('SearchScreen') -> [CALLS] -> Function('SearchContent')]
// [RELATION: Function('SearchScreen')] -> [DEPENDS_ON] -> [Class('NavigationActions')]
// [RELATION: Function('SearchScreen')] -> [CALLS] -> [Function('MainScaffold')]
/**
* [MAIN-CONTRACT]
* Специализированный экран для поиска товаров.
*
* Реализует спецификацию `screen_search`.
*
* @param onNavigateBack Обработчик для возврата на предыдущий экран.
* @param onItemClick Обработчик нажатия на найденный товар.
* @summary Composable-функция для экрана "Поиск".
* @param currentRoute Текущий маршрут для подсветки активного элемента в Drawer.
* @param navigationActions Объект с навигационными действиями.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchScreen(
viewModel: SearchViewModel = hiltViewModel(),
onNavigateBack: () -> Unit,
onItemClick: (Item) -> Unit
currentRoute: String?,
navigationActions: NavigationActions
) {
// [STATE]
val uiState by viewModel.uiState.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = {
TextField(
value = uiState.searchQuery,
onValueChange = viewModel::onSearchQueryChanged,
placeholder = { Text(stringResource(R.string.placeholder_search_items)) },
modifier = Modifier.fillMaxWidth()
)
},
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.content_desc_navigate_back))
}
}
)
}
) { innerPadding ->
SearchContent(
modifier = Modifier.padding(innerPadding),
isLoading = uiState.isLoading,
results = uiState.results,
onItemClick = onItemClick
)
MainScaffold(
topBarTitle = stringResource(id = R.string.search_title),
currentRoute = currentRoute,
navigationActions = navigationActions
) {
// [AI_NOTE]: Implement Search Screen UI
Text(text = "Search Screen")
}
}
// [END_ENTITY: Function('SearchScreen')]
// [ENTITY: Function('SearchContent')]
// [RELATION: Function('SearchContent') -> [CALLS] -> Function('CircularProgressIndicator')]
// [RELATION: Function('SearchContent') -> [CALLS] -> Function('LazyColumn')]
// [RELATION: Function('SearchContent') -> [CALLS] -> Function('ListItem')]
// [RELATION: Function('SearchContent') -> [CALLS] -> Function('Text')]
// [RELATION: Function('SearchContent') -> [CALLS] -> Function('clickable')]
/**
* [CONTRACT]
* Отображает основной контент экрана: фильтры и результаты поиска.
*/
@Composable
private fun SearchContent(
modifier: Modifier = Modifier,
isLoading: Boolean,
results: List<Item>,
onItemClick: (Item) -> Unit
) {
Column(modifier = modifier.fillMaxSize()) {
// [SECTION] FILTERS
// TODO: Implement FilterSection with chips for locations/labels
// Spacer(modifier = Modifier.height(8.dp))
// [SECTION] RESULTS
Box(modifier = Modifier.weight(1f)) {
if (isLoading) {
// [STATE]
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
} else {
// [CORE-LOGIC]
LazyColumn {
items(results, key = { it.id }) { item ->
ListItem(
headlineContent = { Text(item.name) },
supportingContent = { Text(item.location?.name ?: "") },
modifier = Modifier.then(Modifier.clickable { onItemClick(item) })
)
}
}
}
}
}
}
// [END_ENTITY: Function('SearchContent')]
// [END_CONTRACT]
// [END_FILE_SearchScreen.kt]

View File

@@ -1,44 +1,21 @@
// [PACKAGE] com.homebox.lens.ui.screen.search
// [FILE] SearchViewModel.kt
// [SEMANTICS] ui_logic, search, viewmodel
// [SEMANTICS] ui, viewmodel, search
package com.homebox.lens.ui.screen.search
// [IMPORTS]
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('SearchViewModel')]
// [RELATION: ViewModel('SearchViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('SearchViewModel') -> [DEPENDS_ON] -> Annotation('HiltAndroidApp')]
/**
* [CONTRACT]
* @summary ViewModel for the SearchScreen.
* @summary ViewModel for the search screen.
*/
@HiltViewModel
class SearchViewModel
@Inject
constructor() : ViewModel() {
// [STATE]
// TODO: Implement UI state
val uiState = MutableStateFlow(SearchUiState()).asStateFlow()
fun onSearchQueryChanged(query: String) {
// TODO: Implement search query change logic
}
}
class SearchViewModel @Inject constructor() : ViewModel() {
// [AI_NOTE]: Implement UI state
}
// [END_ENTITY: ViewModel('SearchViewModel')]
// [END_CONTRACT]
// [END_FILE_SearchViewModel.kt]
// Placeholder for SearchUiState to resolve compilation errors
data class SearchUiState(
val searchQuery: String = "",
val isLoading: Boolean = false,
val results: List<com.homebox.lens.domain.model.Item> = emptyList()
)

View File

@@ -1,126 +1,141 @@
// [PACKAGE] com.homebox.lens.ui.screen.setup
// [FILE] SetupScreen.kt
// [SEMANTICS] ui, screen, setup, login, compose
// [SEMANTICS] ui, screen, setup, compose
@file:OptIn(ExperimentalMaterial3Api::class)
package com.homebox.lens.ui.screen.setup
// [IMPORTS]
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.homebox.lens.R
import timber.log.Timber
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Function('SetupScreen')]
// [RELATION: Function('SetupScreen') -> [DEPENDS_ON] -> Class('SetupViewModel')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('hiltViewModel')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('collectAsState')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('LaunchedEffect')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('Timber.i')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('Box')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('Column')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('Text')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('stringResource')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('MaterialTheme.typography.headlineMedium')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('OutlinedTextField')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('KeyboardOptions')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('KeyboardType.Uri')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('PasswordVisualTransformation')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('CircularProgressIndicator')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('Button')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('MaterialTheme.colorScheme.error')]
// [RELATION: Function('SetupScreen') -> [CALLS] -> Function('MaterialTheme.typography.bodyMedium')]
// [RELATION: Function('SetupScreen')] -> [DEPENDS_ON] -> [ViewModel('SetupViewModel')]
// [RELATION: Function('SetupScreen')] -> [CALLS] -> [Function('SetupScreenContent')]
/**
* [MAIN-CONTRACT]
* Экран для начальной настройки соединения с сервером Homebox.
*
* @param onSetupComplete Обработчик, вызываемый после успешной настройки и входа.
* @summary Главная Composable-функция для экрана настройки соединения с сервером.
* @param viewModel ViewModel для этого экрана, предоставляется через Hilt.
* @param onSetupComplete Лямбда, вызываемая после успешной настройки и входа.
* @sideeffect Вызывает `onSetupComplete` при изменении `uiState.isSetupComplete`.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SetupScreen(
viewModel: SetupViewModel = hiltViewModel(),
onSetupComplete: () -> Unit
) {
// [STATE]
val uiState by viewModel.uiState.collectAsState()
// [SIDE-EFFECT]
LaunchedEffect(uiState.isSetupComplete) {
if (uiState.isSetupComplete) {
Timber.i("[INFO][SIDE_EFFECT][navigation] Setup complete, navigating to main screen.")
onSetupComplete()
}
if (uiState.isSetupComplete) {
onSetupComplete()
}
// [CORE-LOGIC]
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
SetupScreenContent(
uiState = uiState,
onServerUrlChange = viewModel::onServerUrlChange,
onUsernameChange = viewModel::onUsernameChange,
onPasswordChange = viewModel::onPasswordChange,
onConnectClick = viewModel::connect
)
}
// [END_ENTITY: Function('SetupScreen')]
// [ENTITY: Function('SetupScreenContent')]
// [RELATION: Function('SetupScreenContent')] -> [CONSUMES_STATE] -> [DataClass('SetupUiState')]
/**
* @summary Отображает контент экрана настройки: поля ввода и кнопку.
* @param uiState Текущее состояние UI.
* @param onServerUrlChange Лямбда-обработчик изменения URL сервера.
* @param onUsernameChange Лямбда-обработчик изменения имени пользователя.
* @param onPasswordChange Лямбда-обработчик изменения пароля.
* @param onConnectClick Лямбда-обработчик нажатия на кнопку "Подключиться".
*/
@Composable
private fun SetupScreenContent(
uiState: SetupUiState,
onServerUrlChange: (String) -> Unit,
onUsernameChange: (String) -> Unit,
onPasswordChange: (String) -> Unit,
onConnectClick: () -> Unit
) {
Scaffold(
topBar = {
TopAppBar(title = { Text(stringResource(id = R.string.setup_title)) })
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxWidth()
.padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = stringResource(id = R.string.screen_title_setup), style = MaterialTheme.typography.headlineMedium)
OutlinedTextField(
value = uiState.serverUrl,
onValueChange = viewModel::onServerUrlChange,
onValueChange = onServerUrlChange,
label = { Text(stringResource(id = R.string.setup_server_url_label)) },
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
isError = uiState.error != null
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = uiState.password, // Changed from uiState.apiKey to uiState.password
onValueChange = viewModel::onPasswordChange, // Changed from viewModel::onApiKeyChange to viewModel::onPasswordChange
label = { Text(stringResource(id = R.string.setup_password_label)) }, // Changed from label_api_key to setup_password_label
modifier = Modifier.fillMaxWidth(),
visualTransformation = PasswordVisualTransformation(),
isError = uiState.error != null
value = uiState.username,
onValueChange = onUsernameChange,
label = { Text(stringResource(id = R.string.setup_username_label)) },
modifier = Modifier.fillMaxWidth()
)
if (uiState.isLoading) {
// [STATE]
CircularProgressIndicator()
} else {
// [ACTION]
Button(
onClick = {
Timber.i("[INFO][ACTION][ui_interaction] Login button clicked.")
viewModel.connect() // Changed from viewModel.login() to viewModel.connect()
},
modifier = Modifier.fillMaxWidth()
) {
Text(text = stringResource(id = R.string.setup_connect_button)) // Changed from button_connect to setup_connect_button
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = uiState.password,
onValueChange = onPasswordChange,
label = { Text(stringResource(id = R.string.setup_password_label)) },
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = onConnectClick,
enabled = !uiState.isLoading,
modifier = Modifier.fillMaxWidth()
) {
if (uiState.isLoading) {
CircularProgressIndicator(modifier = Modifier.size(24.dp))
} else {
Text(stringResource(id = R.string.setup_connect_button))
}
}
uiState.error?.let {
// [FALLBACK]
Text(
text = it,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(8.dp))
Text(text = it, color = MaterialTheme.colorScheme.error)
}
}
}
}
// [END_ENTITY: Function('SetupScreen')]
// [END_CONTRACT]
// [END_FILE_SetupScreen.kt]
// [END_ENTITY: Function('SetupScreenContent')]
// [ENTITY: Function('SetupScreenPreview')]
@Preview(showBackground = true)
@Composable
fun SetupScreenPreview() {
SetupScreenContent(
uiState = SetupUiState(error = "Failed to connect"),
onServerUrlChange = {},
onUsernameChange = {},
onPasswordChange = {},
onConnectClick = {}
)
}
// [END_ENTITY: Function('SetupScreenPreview')]
// [END_FILE_SetupScreen.kt]

View File

@@ -4,22 +4,16 @@
package com.homebox.lens.ui.screen.setup
// [IMPORTS]
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: DataClass('SetupUiState')]
/**
* [ENTITY: DataClass('SetupUiState')]
* [CONTRACT]
* Неизменяемая модель данных, представляющая полное состояние экрана настройки (Setup Screen).
* Использование `data class` предоставляет метод `copy()` для легкого создания новых состояний.
* @property serverUrl URL-адрес сервера Homebox.
* @property username Имя пользователя для входа.
* @property password Пароль пользователя.
* @property isLoading Флаг, указывающий, выполняется ли в данный момент сетевой запрос.
* @property error Сообщение об ошибке для отображения пользователю, или `null` при отсутствии ошибки.
* @property isSetupComplete Флаг, указывающий на успешное завершение настройки и входа.
* @summary Неизменяемая модель данных, представляющая полное состояние экрана настройки (Setup Screen).
* @description Использование `data class` предоставляет метод `copy()` для легкого создания новых состояний.
* @param serverUrl URL-адрес сервера Homebox.
* @param username Имя пользователя для входа.
* @param password Пароль пользователя.
* @param isLoading Флаг, указывающий, выполняется ли в данный момент сетевой запрос.
* @param error Сообщение об ошибке для отображения пользователю, или `null` при отсутствии ошибки.
* @param isSetupComplete Флаг, указывающий на успешное завершение настройки и входа.
*/
data class SetupUiState(
val serverUrl: String = "",
@@ -27,8 +21,7 @@ data class SetupUiState(
val password: String = "",
val isLoading: Boolean = false,
val error: String? = null,
val isSetupComplete: Boolean = false,
val isSetupComplete: Boolean = false
)
// [END_ENTITY: DataClass('SetupUiState')]
// [END_CONTRACT]
// [END_FILE_SetupUiState.kt]

View File

@@ -14,159 +14,100 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: ViewModel('SetupViewModel')]
// [RELATION: ViewModel('SetupViewModel') -> [INHERITS_FROM] -> Class('ViewModel')]
// [RELATION: ViewModel('SetupViewModel') -> [DEPENDS_ON] -> Annotation('HiltViewModel')]
// [RELATION: ViewModel('SetupViewModel') -> [DEPENDS_ON] -> Class('CredentialsRepository')]
// [RELATION: ViewModel('SetupViewModel') -> [DEPENDS_ON] -> Class('LoginUseCase')]
// [RELATION: ViewModel('SetupViewModel')] -> [DEPENDS_ON] -> [Repository('CredentialsRepository')]
// [RELATION: ViewModel('SetupViewModel')] -> [DEPENDS_ON] -> [UseCase('LoginUseCase')]
// [RELATION: ViewModel('SetupViewModel')] -> [EMITS_STATE] -> [DataClass('SetupUiState')]
/**
* [CONTRACT]
* ViewModel для экрана первоначальной настройки (Setup).
* Отвечает за:
* 1. Загрузку и сохранение учетных данных (URL сервера, логин, пароль).
* 2. Управление состоянием UI экрана (`SetupUiState`).
* 3. Инициацию процесса входа в систему через `LoginUseCase`.
* @property credentialsRepository Репозиторий для операций с учетными данными.
* @property loginUseCase Use case для выполнения логики входа.
* @summary ViewModel для экрана первоначальной настройки (Setup).
* @param credentialsRepository Репозиторий для операций с учетными данными.
* @param loginUseCase Use case для выполнения логики входа.
* @invariant Состояние `uiState` всегда является единственным источником истины для UI.
*/
@HiltViewModel
class SetupViewModel
@Inject
constructor(
private val credentialsRepository: CredentialsRepository,
private val loginUseCase: LoginUseCase,
) : ViewModel() {
// [STATE]
private val _uiState = MutableStateFlow(SetupUiState())
val uiState = _uiState.asStateFlow()
class SetupViewModel @Inject constructor(
private val credentialsRepository: CredentialsRepository,
private val loginUseCase: LoginUseCase
) : ViewModel() {
// [LIFECYCLE_HANDLER]
init {
// [ACTION] Загружаем учетные данные при создании ViewModel.
loadCredentials()
}
private val _uiState = MutableStateFlow(SetupUiState())
val uiState = _uiState.asStateFlow()
// [ENTITY: Function('loadCredentials')]
// [RELATION: Function('loadCredentials') -> [CALLS] -> Function('viewModelScope.launch')]
// [RELATION: Function('loadCredentials') -> [CALLS] -> Function('credentialsRepository.getCredentials')]
// [RELATION: Function('loadCredentials') -> [CALLS] -> Function('collect')]
// [RELATION: Function('loadCredentials') -> [WRITES_TO] -> Property('_uiState')]
/**
* [CONTRACT]
* @summary Загружает учетные данные из репозитория при инициализации.
* @sideeffect Асинхронно обновляет `_uiState` полученными учетными данными.
*/
private fun loadCredentials() {
viewModelScope.launch {
// [CORE-LOGIC] Подписываемся на поток учетных данных.
credentialsRepository.getCredentials().collect { credentials ->
// [ACTION] Обновляем состояние, если учетные данные существуют.
if (credentials != null) {
_uiState.update {
it.copy(
serverUrl = credentials.serverUrl,
username = credentials.username,
password = credentials.password,
)
}
init {
loadCredentials()
}
// [ENTITY: Function('loadCredentials')]
private fun loadCredentials() {
Timber.d("[DEBUG][ENTRYPOINT][loading_credentials] Loading credentials from repository.")
viewModelScope.launch {
credentialsRepository.getCredentials().collect { credentials ->
if (credentials != null) {
Timber.d("[DEBUG][ACTION][updating_state] Credentials found, updating UI state.")
_uiState.update {
it.copy(
serverUrl = credentials.serverUrl,
username = credentials.username,
password = credentials.password
)
}
}
}
}
// [END_ENTITY: Function('loadCredentials')]
// [ENTITY: Function('onServerUrlChange')]
// [RELATION: Function('onServerUrlChange') -> [WRITES_TO] -> Property('_uiState')]
/**
* [CONTRACT]
* [ACTION] Обновляет URL сервера в состоянии UI в ответ на ввод пользователя.
* @param newUrl Новое значение URL.
* @sideeffect Обновляет поле `serverUrl` в `_uiState`.
*/
fun onServerUrlChange(newUrl: String) {
_uiState.update { it.copy(serverUrl = newUrl) }
}
// [END_ENTITY: Function('onServerUrlChange')]
// [ENTITY: Function('onUsernameChange')]
// [RELATION: Function('onUsernameChange') -> [WRITES_TO] -> Property('_uiState')]
/**
* [CONTRACT]
* [ACTION] Обновляет имя пользователя в состоянии UI в ответ на ввод пользователя.
* @param newUsername Новое значение имени пользователя.
* @sideeffect Обновляет поле `username` в `_uiState`.
*/
fun onUsernameChange(newUsername: String) {
_uiState.update { it.copy(username = newUsername) }
}
// [END_ENTITY: Function('onUsernameChange')]
// [ENTITY: Function('onPasswordChange')]
// [RELATION: Function('onPasswordChange') -> [WRITES_TO] -> Property('_uiState')]
/**
* [CONTRACT]
* [ACTION] Обновляет пароль в состоянии UI в ответ на ввод пользователя.
* @param newPassword Новое значение пароля.
* @sideeffect Обновляет поле `password` в `_uiState`.
*/
fun onPasswordChange(newPassword: String) {
_uiState.update { it.copy(password = newPassword) }
}
// [END_ENTITY: Function('onPasswordChange')]
// [ENTITY: Function('connect')]
// [RELATION: Function('connect') -> [CALLS] -> Function('viewModelScope.launch')]
// [RELATION: Function('connect') -> [WRITES_TO] -> Property('_uiState')]
// [RELATION: Function('connect') -> [CREATES_INSTANCE_OF] -> Class('Credentials')]
// [RELATION: Function('connect') -> [CALLS] -> Function('credentialsRepository.saveCredentials')]
// [RELATION: Function('connect') -> [CALLS] -> Function('loginUseCase')]
// [RELATION: Function('connect') -> [CALLS] -> Function('fold')]
/**
* [CONTRACT]
* [ACTION] Запускает процесс подключения и входа в систему по действию пользователя.
* Выполняет две основные операции:
* 1. Сохраняет введенные учетные данные для последующих сессий.
* 2. Выполняет вход в систему с использованием этих данных.
* @sideeffect Обновляет `_uiState`, управляя флагами `isLoading`, `error` и `isSetupComplete`.
* @sideeffect Вызывает `credentialsRepository.saveCredentials`, изменяя сохраненные данные.
* @sideeffect Вызывает `loginUseCase`, который, в свою очередь, сохраняет токен.
*/
fun connect() {
viewModelScope.launch {
// [ACTION] Устанавливаем состояние загрузки и сбрасываем предыдущую ошибку.
_uiState.update { it.copy(isLoading = true, error = null) }
// [PREPARATION] Готовим данные для операций, очищая их от лишних пробелов.
val credentials =
Credentials(
serverUrl = _uiState.value.serverUrl.trim(),
username = _uiState.value.username.trim(),
password = _uiState.value.password,
)
// [ACTION] Сохраняем учетные данные для будущего использования.
credentialsRepository.saveCredentials(credentials)
// [CORE-LOGIC] Выполняем UseCase и обрабатываем результат.
loginUseCase(credentials).fold(
onSuccess = {
// [ACTION] Обработка успеха: обновляем UI, отмечая завершение настройки.
_uiState.update { it.copy(isLoading = false, isSetupComplete = true) }
},
onFailure = { exception ->
// [ERROR_HANDLER] Обработка ошибки: обновляем UI с сообщением об ошибке.
_uiState.update { it.copy(isLoading = false, error = exception.message ?: "Login failed") }
},
)
}
}
// [END_ENTITY: Function('connect')]
}
// [END_ENTITY: Function('loadCredentials')]
// [ENTITY: Function('onServerUrlChange')]
fun onServerUrlChange(newUrl: String) {
_uiState.update { it.copy(serverUrl = newUrl) }
}
// [END_ENTITY: Function('onServerUrlChange')]
// [ENTITY: Function('onUsernameChange')]
fun onUsernameChange(newUsername: String) {
_uiState.update { it.copy(username = newUsername) }
}
// [END_ENTITY: Function('onUsernameChange')]
// [ENTITY: Function('onPasswordChange')]
fun onPasswordChange(newPassword: String) {
_uiState.update { it.copy(password = newPassword) }
}
// [END_ENTITY: Function('onPasswordChange')]
// [ENTITY: Function('connect')]
fun connect() {
Timber.d("[DEBUG][ENTRYPOINT][connecting] Starting connection process.")
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true, error = null) }
val credentials = Credentials(
serverUrl = _uiState.value.serverUrl.trim(),
username = _uiState.value.username.trim(),
password = _uiState.value.password
)
Timber.d("[DEBUG][ACTION][saving_credentials] Saving credentials.")
credentialsRepository.saveCredentials(credentials)
Timber.d("[DEBUG][ACTION][executing_login] Executing login use case.")
loginUseCase(credentials).fold(
onSuccess = {
Timber.d("[DEBUG][SUCCESS][login_successful] Login successful.")
_uiState.update { it.copy(isLoading = false, isSetupComplete = true) }
},
onFailure = { exception ->
Timber.e(exception, "[ERROR][EXCEPTION][login_failed] Login failed.")
_uiState.update { it.copy(isLoading = false, error = exception.message ?: "Login failed") }
}
)
}
}
// [END_ENTITY: Function('connect')]
}
// [END_ENTITY: ViewModel('SetupViewModel')]
// [END_CONTRACT]
// [END_FILE_SetupViewModel.kt]

View File

@@ -1,36 +1,18 @@
// [PACKAGE] com.homebox.lens.ui.theme
// [FILE] Color.kt
// [SEMANTICS] ui, theme, color
package com.homebox.lens.ui.theme
// [IMPORTS]
import androidx.compose.ui.graphics.Color
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Constant('Purple80')]
val Purple80 = Color(0xFFD0BCFF)
// [END_ENTITY: Constant('Purple80')]
// [ENTITY: Constant('PurpleGrey80')]
val PurpleGrey80 = Color(0xFFCCC2DC)
// [END_ENTITY: Constant('PurpleGrey80')]
// [ENTITY: Constant('Pink80')]
val Pink80 = Color(0xFFEFB8C8)
// [END_ENTITY: Constant('Pink80')]
// [ENTITY: Constant('Purple40')]
val Purple40 = Color(0xFF6650a4)
// [END_ENTITY: Constant('Purple40')]
// [ENTITY: Constant('PurpleGrey40')]
val PurpleGrey40 = Color(0xFF625b71)
// [END_ENTITY: Constant('PurpleGrey40')]
// [ENTITY: Constant('Pink40')]
val Pink40 = Color(0xFF7D5260)
// [END_ENTITY: Constant('Pink40')]
// [END_CONTRACT]
// [END_FILE_Color.kt]
// [END_FILE_Color.kt]

View File

@@ -1,7 +1,6 @@
// [PACKAGE] com.homebox.lens.ui.theme
// [FILE] Theme.kt
// [SEMANTICS] ui, theme, color_scheme
// [SEMANTICS] ui, theme
package com.homebox.lens.ui.theme
// [IMPORTS]
@@ -21,63 +20,41 @@ import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Constant('DarkColorScheme')]
// [RELATION: Constant('DarkColorScheme') -> [CALLS] -> Function('darkColorScheme')]
// [RELATION: Constant('DarkColorScheme') -> [DEPENDS_ON] -> Constant('Purple80')]
// [RELATION: Constant('DarkColorScheme') -> [DEPENDS_ON] -> Constant('PurpleGrey80')]
// [RELATION: Constant('DarkColorScheme') -> [DEPENDS_ON] -> Constant('Pink80')]
private val DarkColorScheme =
darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80,
)
// [END_ENTITY: Constant('DarkColorScheme')]
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
// [ENTITY: Constant('LightColorScheme')]
// [RELATION: Constant('LightColorScheme') -> [CALLS] -> Function('lightColorScheme')]
// [RELATION: Constant('LightColorScheme') -> [DEPENDS_ON] -> Constant('Purple40')]
// [RELATION: Constant('LightColorScheme') -> [DEPENDS_ON] -> Constant('PurpleGrey40')]
// [RELATION: Constant('LightColorScheme') -> [DEPENDS_ON] -> Constant('Pink40')]
private val LightColorScheme =
lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40,
)
// [END_ENTITY: Constant('LightColorScheme')]
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
)
// [ENTITY: Function('HomeboxLensTheme')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('isSystemInDarkTheme')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('LocalContext.current')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('dynamicDarkColorScheme')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('dynamicLightColorScheme')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('LocalView.current')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('SideEffect')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('toArgb')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('WindowCompat.getInsetsController')]
// [RELATION: Function('HomeboxLensTheme') -> [CALLS] -> Function('MaterialTheme')]
// [RELATION: Function('HomeboxLensTheme') -> [DEPENDS_ON] -> Constant('DarkColorScheme')]
// [RELATION: Function('HomeboxLensTheme') -> [DEPENDS_ON] -> Constant('LightColorScheme')]
// [RELATION: Function('HomeboxLensTheme') -> [DEPENDS_ON] -> Constant('Typography')]
// [RELATION: Function('HomeboxLensTheme')] -> [DEPENDS_ON] -> [DataStructure('Typography')]
/**
* @summary The main theme for the Homebox Lens application.
* @param darkTheme Whether the theme should be dark or light.
* @param dynamicColor Whether to use dynamic color (on Android 12+).
* @param content The content to be displayed within the theme.
*/
@Composable
fun HomeboxLensTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
content: @Composable () -> Unit
) {
val colorScheme =
when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
@@ -90,9 +67,8 @@ fun HomeboxLensTheme(
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content,
content = content
)
}
// [END_ENTITY: Function('HomeboxLensTheme')]
// [END_CONTRACT]
// [END_FILE_Theme.kt]
// [END_FILE_Theme.kt]

View File

@@ -1,7 +1,6 @@
// [PACKAGE] com.homebox.lens.ui.theme
// [FILE] Typography.kt
// [SEMANTICS] ui, theme, typography
package com.homebox.lens.ui.theme
// [IMPORTS]
@@ -12,26 +11,19 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// [END_IMPORTS]
// [CONTRACT]
// [ENTITY: Constant('Typography')]
// [RELATION: Constant('Typography') -> [CALLS] -> Function('Typography')]
// [RELATION: Constant('Typography') -> [CALLS] -> Function('TextStyle')]
// [RELATION: Constant('Typography') -> [DEPENDS_ON] -> Class('FontFamily')]
// [RELATION: Constant('Typography') -> [DEPENDS_ON] -> Class('FontWeight')]
// [ENTITY: DataStructure('Typography')]
/**
* Set of Material typography styles to start with
* @summary Defines the typography for the application.
*/
val Typography =
Typography(
bodyLarge =
TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp,
),
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
// [END_ENTITY: Constant('Typography')]
// [END_CONTRACT]
// [END_FILE_Typography.kt]
)
// [END_ENTITY: DataStructure('Typography')]
// [END_FILE_Typography.kt]

View File

@@ -16,36 +16,7 @@
<string name="cd_scan_qr_code">Scan QR code</string>
<string name="cd_navigate_back">Navigate back</string>
<string name="cd_add_new_location">Add new location</string>
<string name="content_desc_add_label">Add new label</string>
<string name="content_desc_sync_inventory">Sync inventory</string>
<string name="content_desc_edit_item">Edit item</string>
<string name="content_desc_delete_item">Delete item</string>
<string name="content_desc_save_item">Save item</string>
<string name="content_desc_create_label">Create new label</string>
<string name="content_desc_label_icon">Label icon</string>
<string name="cd_more_options">More options</string>
<!-- Inventory List Screen -->
<string name="inventory_list_title">Inventory</string>
<!-- Item Details Screen -->
<string name="item_details_title">Details</string>
<string name="section_title_description">Description</string>
<string name="placeholder_no_description">No description</string>
<string name="section_title_details">Details</string>
<string name="label_quantity">Quantity</string>
<string name="label_location">Location</string>
<string name="section_title_labels">Labels</string>
<!-- Item Edit Screen -->
<string name="item_edit_title_create">Create item</string>
<string name="item_edit_title">Edit item</string>
<string name="label_name">Name</string>
<string name="label_description">Description</string>
<!-- Search Screen -->
<string name="placeholder_search_items">Search items...</string>
<string name="search_title">Search</string>
<string name="cd_add_new_label">Add new label</string>
<!-- Dashboard Screen -->
<string name="dashboard_title">Dashboard</string>
@@ -66,19 +37,30 @@
<string name="nav_labels">Labels</string>
<!-- Screen Titles -->
<string name="inventory_list_title">Inventory</string>
<!-- Screen Titles -->
<string name="item_details_title">Details</string>
<string name="item_edit_title">Edit Item</string>
<string name="labels_list_title">Labels</string>
<string name="locations_list_title">Locations</string>
<string name="search_title">Search</string>
<string name="save_item">Save</string>
<string name="item_name">Name</string>
<string name="item_description">Description</string>
<string name="item_quantity">Quantity</string>
<!-- Location Edit Screen -->
<string name="location_edit_title_create">Create location</string>
<string name="location_edit_title_edit">Edit location</string>
<string name="location_edit_title_create">Create Location</string>
<string name="location_edit_title_edit">Edit Location</string>
<!-- Locations List Screen -->
<string name="locations_not_found">Locations not found. Press + to add a new one.</string>
<string name="item_count">Items: %1$d</string>
<string name="cd_more_options">More options</string>
<!-- Setup Screen -->
<string name="screen_title_setup">Setup</string>
<string name="setup_title">Server Setup</string>
<string name="setup_server_url_label">Server URL</string>
<string name="setup_username_label">Username</string>
@@ -87,10 +69,15 @@
<!-- Labels List Screen -->
<string name="screen_title_labels">Labels</string>
<string name="no_labels_found">No labels found.</string>
<string name="dialog_title_create_label">Create label</string>
<string name="dialog_field_label_name">Label name</string>
<string name="content_desc_navigate_back">Navigate back</string>
<string name="content_desc_create_label">Create new label</string>
<string name="content_desc_label_icon">Label icon</string>
<string name="labels_list_empty">Labels not created yet.</string>
<string name="dialog_title_create_label">Create Label</string>
<string name="dialog_field_label_name">Label Name</string>
<string name="dialog_button_create">Create</string>
<string name="dialog_button_cancel">Cancel</string>
</resources>
</resources>

View File

@@ -66,6 +66,11 @@
<string name="locations_list_title">Места хранения</string>
<string name="search_title">Поиск</string>
<string name="save_item">Сохранить</string>
<string name="item_name">Название</string>
<string name="item_description">Описание</string>
<string name="item_quantity">Количество</string>
<!-- Location Edit Screen -->
<string name="location_edit_title_create">Создать локацию</string>
<string name="location_edit_title_edit">Редактировать локацию</string>

View File

@@ -0,0 +1,126 @@
package com.homebox.lens.ui.screen.itemedit
import app.cash.turbine.test
import com.homebox.lens.domain.model.Item
import com.homebox.lens.domain.model.ItemCreate
import com.homebox.lens.domain.model.ItemOut
import com.homebox.lens.domain.model.ItemSummary
import com.homebox.lens.domain.usecase.CreateItemUseCase
import com.homebox.lens.domain.usecase.GetItemDetailsUseCase
import com.homebox.lens.domain.usecase.UpdateItemUseCase
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.util.UUID
@ExperimentalCoroutinesApi
class ItemEditViewModelTest {
private val testDispatcher = StandardTestDispatcher()
private lateinit var createItemUseCase: CreateItemUseCase
private lateinit var updateItemUseCase: UpdateItemUseCase
private lateinit var getItemDetailsUseCase: GetItemDetailsUseCase
private lateinit var viewModel: ItemEditViewModel
@Before
fun setUp() {
Dispatchers.setMain(testDispatcher)
createItemUseCase = mockk()
updateItemUseCase = mockk()
getItemDetailsUseCase = mockk()
viewModel = ItemEditViewModel(createItemUseCase, updateItemUseCase, getItemDetailsUseCase)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `loadItem with valid id should update uiState with item`() = runTest {
val itemId = UUID.randomUUID().toString()
val itemOut = ItemOut(id = itemId, name = "Test Item", description = "Description", quantity = 1, images = emptyList(), location = null, labels = emptyList(), value = 10.0, createdAt = "2025-08-28T12:00:00Z", assetId = null, notes = null, serialNumber = null, isArchived = false, purchasePrice = null, purchaseDate = null, warrantyUntil = null, parent = null, children = emptyList(), attachments = emptyList(), fields = emptyList(), maintenance = emptyList(), updatedAt = "2025-08-28T12:00:00Z")
coEvery { getItemDetailsUseCase(itemId) } returns itemOut
viewModel.loadItem(itemId)
testDispatcher.scheduler.advanceUntilIdle()
val uiState = viewModel.uiState.value
assertFalse(uiState.isLoading)
assertNotNull(uiState.item)
assertEquals(itemId, uiState.item?.id)
assertEquals("Test Item", uiState.item?.name)
}
@Test
fun `loadItem with null id should prepare a new item`() = runTest {
viewModel.loadItem(null)
testDispatcher.scheduler.advanceUntilIdle()
val uiState = viewModel.uiState.value
assertFalse(uiState.isLoading)
assertNotNull(uiState.item)
assertEquals("", uiState.item?.id)
assertEquals("", uiState.item?.name)
}
@Test
fun `saveItem should call createItemUseCase for new item`() = runTest {
val createdItemSummary = ItemSummary(id = UUID.randomUUID().toString(), name = "New Item", assetId = null, image = null, isArchived = false, labels = emptyList(), location = null, value = 0.0, createdAt = "2025-08-28T12:00:00Z", updatedAt = "2025-08-28T12:00:00Z")
coEvery { createItemUseCase(any()) } returns createdItemSummary
viewModel.loadItem(null)
testDispatcher.scheduler.advanceUntilIdle()
viewModel.updateName("New Item")
viewModel.updateDescription("New Description")
viewModel.updateQuantity(2)
testDispatcher.scheduler.advanceUntilIdle()
viewModel.saveItem()
testDispatcher.scheduler.advanceUntilIdle()
val uiState = viewModel.uiState.value
assertFalse(uiState.isLoading)
assertNotNull(uiState.item)
assertEquals(createdItemSummary.id, uiState.item?.id)
}
@Test
fun `saveItem should call updateItemUseCase for existing item`() = runTest {
val itemId = UUID.randomUUID().toString()
val updatedItemOut = ItemOut(id = itemId, name = "Updated Item", description = "Updated Description", quantity = 4, images = emptyList(), location = null, labels = emptyList(), value = 12.0, createdAt = "2025-08-28T12:00:00Z", assetId = null, notes = null, serialNumber = null, isArchived = false, purchasePrice = null, purchaseDate = null, warrantyUntil = null, parent = null, children = emptyList(), attachments = emptyList(), fields = emptyList(), maintenance = emptyList(), updatedAt = "2025-08-28T12:00:00Z")
coEvery { getItemDetailsUseCase(itemId) } returns ItemOut(id = itemId, name = "Existing Item", description = "Existing Description", quantity = 3, images = emptyList(), location = null, labels = emptyList(), value = 10.0, createdAt = "2025-08-28T12:00:00Z", assetId = null, notes = null, serialNumber = null, isArchived = false, purchasePrice = null, purchaseDate = null, warrantyUntil = null, parent = null, children = emptyList(), attachments = emptyList(), fields = emptyList(), maintenance = emptyList(), updatedAt = "2025-08-28T12:00:00Z")
coEvery { updateItemUseCase(any()) } returns updatedItemOut
viewModel.loadItem(itemId)
testDispatcher.scheduler.advanceUntilIdle()
viewModel.updateName("Updated Item")
viewModel.updateDescription("Updated Description")
viewModel.updateQuantity(4)
testDispatcher.scheduler.advanceUntilIdle()
viewModel.saveItem()
testDispatcher.scheduler.advanceUntilIdle()
val uiState = viewModel.uiState.value
assertFalse(uiState.isLoading)
assertNotNull(uiState.item)
assertEquals(itemId, uiState.item?.id)
assertEquals("Updated Item", uiState.item?.name)
assertEquals(4, uiState.item?.quantity)
}
}