Modern Apps git

← Modern-Apps.git

ui: split root flow collection per section

Commit
58400823c41f7e48b19ab6681d9fb3568e90ccb3
Author
Vayun Mathur <[email protected]>
When
2026-11-20 19:52 UTC (15 days ago)
Parents
b2a6dd8
files DirectoryPage collected 15 flows at the root, so any
flow change recomposed the whole page. Each section now
collects only its own flows via per-section binders using
collectAsStateWithLifecycle (lifecycle-runtime-compose added
to files/photos, matching notes/auto); the root keeps just the
two slices DirectoryScreenCore needs. The frozen-while-not-
current behaviour the old snapshot gave is preserved per flow,
and the public stateless DirectoryScreen(state) used by
previews/tests is unchanged.

photos Navigation's three root collectors also switched to
collectAsStateWithLifecycle; they stay at Navigation because
RelockEffect plus two entries consume them there.

Verified: files 105 tests, photos 790 tests, 0 failures.

Diff

files/build.gradle.kts
diff --git a/files/build.gradle.kts b/files/build.gradle.ktsindex 152ad9f7d0..844ef73ca6 100644--- a/files/build.gradle.kts+++ b/files/build.gradle.kts@@ -20,5 +20,7 @@ dependencies {     implementation(libs.androidx.work.runtime.ktx)     // Image thumbnails for image files in the browser (AsyncImage).     implementation(project(":library:image"))+    // collectAsStateWithLifecycle in the directory binders (as in :auto).+    implementation(libs.androidx.lifecycle.runtime.compose)     testImplementation("androidx.work:work-testing:${libs.versions.workRuntimeKtx.get()}") }
files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.ktindex d286a72726..57ef843bf7 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt@@ -31,6 +31,7 @@ import com.vayunmathur.library.ui.IconChevronRight import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextField+import java.io.File  /** Title slot for [DirectoryScreen]: search field, category title, or breadcrumb trail. */ @Composable@@ -40,24 +41,53 @@ internal fun DirectoryTitle(     isCategory: Boolean,     isReadOnly: Boolean, ) {-    val root = state.rootDirectory+    DirectoryTitle(+        rootDirectory = state.rootDirectory,+        rootDisplayName = state.rootDisplayName,+        currentDirectory = state.currentDirectory,+        zipPath = state.zipPath,+        zipInternalPath = state.zipInternalPath,+        isSearchActive = state.isSearchActive,+        searchQuery = state.searchQuery,+        categoryTitle = state.categoryTitle,+        actions = actions,+        isCategory = isCategory,+        isReadOnly = isReadOnly,+    )+}++@Composable+internal fun DirectoryTitle(+    rootDirectory: File,+    rootDisplayName: String,+    currentDirectory: File,+    zipPath: File?,+    zipInternalPath: String,+    isSearchActive: Boolean,+    searchQuery: String,+    categoryTitle: String?,+    actions: FilesActions,+    isCategory: Boolean,+    isReadOnly: Boolean,+) {+    val root = rootDirectory     val breadcrumbs = remember(-        state.currentDirectory, state.zipPath, state.zipInternalPath, state.rootDisplayName+        currentDirectory, zipPath, zipInternalPath, rootDisplayName     ) {         val crumbs = mutableListOf<Crumb>()-        val zp = state.zipPath+        val zp = zipPath         if (zp == null) {-            fileAncestors(state.currentDirectory, root).forEach { f ->-                crumbs.add(Crumb(displayName = if (f.absolutePath == root.absolutePath) state.rootDisplayName else f.name, realFile = f, zipInternalPath = null))+            fileAncestors(currentDirectory, root).forEach { f ->+                crumbs.add(Crumb(displayName = if (f.absolutePath == root.absolutePath) rootDisplayName else f.name, realFile = f, zipInternalPath = null))             }         } else {             val parent = zp.parentFile ?: root             fileAncestors(parent, root).forEach { f ->-                crumbs.add(Crumb(displayName = if (f.absolutePath == root.absolutePath) state.rootDisplayName else f.name, realFile = f, zipInternalPath = null))+                crumbs.add(Crumb(displayName = if (f.absolutePath == root.absolutePath) rootDisplayName else f.name, realFile = f, zipInternalPath = null))             }             crumbs.add(Crumb(displayName = zp.name, realFile = null, zipInternalPath = ""))             var accum = ""-            for (seg in state.zipInternalPath.split("/").filter { it.isNotEmpty() }) {+            for (seg in zipInternalPath.split("/").filter { it.isNotEmpty() }) {                 accum = if (accum.isEmpty()) seg else "$accum/$seg"                 crumbs.add(Crumb(displayName = seg, realFile = null, zipInternalPath = accum))             }@@ -65,10 +95,10 @@ internal fun DirectoryTitle(         crumbs     } -    if (state.isSearchActive) {+    if (isSearchActive) {         val searchFocus = remember { FocusRequester() }         TextField(-            value = state.searchQuery,+            value = searchQuery,             onValueChange = { actions.setSearchQuery(it) },             placeholder = { Text(stringResource(R.string.search_files)) },             singleLine = true,@@ -78,7 +108,7 @@ internal fun DirectoryTitle(         )         LaunchedEffect(Unit) { searchFocus.requestFocus() }     } else if (isCategory) {-        Text(state.categoryTitle.orEmpty(), style = MaterialTheme.typography.titleLarge)+        Text(categoryTitle.orEmpty(), style = MaterialTheme.typography.titleLarge)     } else {         Row(             verticalAlignment = Alignment.CenterVertically,@@ -118,7 +148,7 @@ internal fun DirectoryTitle(                         .clickable {                             val rf = crumb.realFile                             if (rf != null) {-                                if (state.zipPath != null) actions.navigateToZipParentRealFolder(rf)+                                if (zipPath != null) actions.navigateToZipParentRealFolder(rf)                                 else actions.navigateTo(rf)                             } else {                                 actions.navigateToZipInternalPath(crumb.zipInternalPath ?: "")
files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.ktindex 55a2591f09..7200db5f2d 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt@@ -48,14 +48,46 @@ internal fun DirectoryListing(     /** Clears the rename dialog target; owned by [DirectoryScreen]. */     onClearRenameTarget: () -> Unit = {}, ) {-    val query = state.searchQuery.trim()+    DirectoryListing(+        directories = state.directories,+        files = state.files,+        searchQuery = state.searchQuery,+        clipboardCount = state.clipboardCount,+        selectedPaths = state.selectedPaths,+        isSearchActive = state.isSearchActive,+        viewMode = state.viewMode,+        actions = actions,+        canModifyHere = canModifyHere,+        isReadOnly = isReadOnly,+        modifier = modifier,+        onClearRenameTarget = onClearRenameTarget,+    )+}++@Composable+internal fun DirectoryListing(+    directories: List<FileBrowserItem>,+    files: List<FileBrowserItem>,+    searchQuery: String,+    clipboardCount: Int,+    selectedPaths: Set<FileBrowserItem>,+    isSearchActive: Boolean,+    viewMode: ViewMode,+    actions: FilesActions,+    canModifyHere: Boolean,+    isReadOnly: Boolean,+    modifier: Modifier = Modifier,+    /** Clears the rename dialog target; owned by [DirectoryScreen]. */+    onClearRenameTarget: () -> Unit = {},+) {+    val query = searchQuery.trim()     fun matches(item: FileBrowserItem) =         query.isEmpty() || item.name.contains(query, ignoreCase = true)-    val allItems = (state.directories + state.files).filter(::matches)+    val allItems = (directories + files).filter(::matches)      Column(modifier) {             // Paste bar: shown when the clipboard has files and we can write here.-            if (state.clipboardCount > 0 && canModifyHere && state.selectedPaths.isEmpty() && !state.isSearchActive) {+            if (clipboardCount > 0 && canModifyHere && selectedPaths.isEmpty() && !isSearchActive) {                 Surface(color = MaterialTheme.colorScheme.secondaryContainer) {                     Row(                         modifier = Modifier@@ -64,7 +96,7 @@ internal fun DirectoryListing(                         verticalAlignment = Alignment.CenterVertically,                     ) {                         Text(-                            pluralStringResource(R.plurals.ready_to_paste, state.clipboardCount, state.clipboardCount),+                            pluralStringResource(R.plurals.ready_to_paste, clipboardCount, clipboardCount),                             modifier = Modifier.weight(1f),                         )                         TextButton(onClick = { actions.pasteHere() }) { Text(stringResource(R.string.paste)) }@@ -74,7 +106,7 @@ internal fun DirectoryListing(             }              val onItemClick: (FileBrowserItem) -> Unit = { child ->-                if (state.selectedPaths.isNotEmpty()) {+                if (selectedPaths.isNotEmpty()) {                     actions.toggleSelection(child)                 } else if (child.isDirectory) {                     if (child.realFile != null) actions.navigateTo(child.realFile)@@ -104,7 +136,7 @@ internal fun DirectoryListing(                         color = MaterialTheme.colorScheme.outline,                     )                 }-            } else if (state.viewMode == ViewMode.GRID) {+            } else if (viewMode == ViewMode.GRID) {                 LazyVerticalGrid(                     columns = GridCells.Adaptive(minSize = 104.dp),                     modifier = Modifier.weight(1f).fillMaxWidth(),@@ -112,7 +144,7 @@ internal fun DirectoryListing(                     gridItems(allItems, key = { it.key }) { child ->                         GridItem(                             file = child,-                            isSelected = state.selectedPaths.any { it.key == child.key },+                            isSelected = selectedPaths.any { it.key == child.key },                             onClick = { onItemClick(child) },                             onLongClick = { onItemLongClick(child) },                         )@@ -121,7 +153,7 @@ internal fun DirectoryListing(             } else {                 LazyColumn(Modifier.weight(1f)) {                     items(allItems, key = { it.key }) { child ->-                        val isSelected = state.selectedPaths.any { it.key == child.key }+                        val isSelected = selectedPaths.any { it.key == child.key }                         DirectoryItem(                             file = child,                             isSelected = isSelected,@@ -135,7 +167,7 @@ internal fun DirectoryListing(                             },                             onStartDrag = {                                 if (isReadOnly) emptyList()-                                else if (state.selectedPaths.any { it.key == child.key }) state.selectedPaths.mapNotNull { it.realFile }.toList()+                                else if (selectedPaths.any { it.key == child.key }) selectedPaths.mapNotNull { it.realFile }.toList()                                 else listOfNotNull(child.realFile)                             })                         HorizontalDivider(
files/src/main/java/com/vayunmathur/files/ui/DirectoryMenus.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryMenus.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryMenus.ktindex f25fc10c3f..6bb880fa53 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryMenus.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryMenus.kt@@ -51,19 +51,58 @@ internal fun DirectoryTopActions(     onPickUnzipDestination: () -> Unit,     onShowNewFolder: () -> Unit,     onShowNewFile: () -> Unit,+) {+    DirectoryTopActions(+        selectedPaths = state.selectedPaths,+        isSearchActive = state.isSearchActive,+        hasIncomingUris = state.hasIncomingUris,+        sortBy = state.sortBy,+        sortAscending = state.sortAscending,+        viewMode = state.viewMode,+        showHidden = state.showHidden,+        actions = actions,+        canModifyHere = canModifyHere,+        isReadOnly = isReadOnly,+        onRename = onRename,+        onShowProperties = onShowProperties,+        onArchive = onArchive,+        onPickUnzipDestination = onPickUnzipDestination,+        onShowNewFolder = onShowNewFolder,+        onShowNewFile = onShowNewFile,+    )+}++@Composable+internal fun DirectoryTopActions(+    selectedPaths: Set<FileBrowserItem>,+    isSearchActive: Boolean,+    hasIncomingUris: Boolean,+    sortBy: SortBy,+    sortAscending: Boolean,+    viewMode: ViewMode,+    showHidden: Boolean,+    actions: FilesActions,+    canModifyHere: Boolean,+    isReadOnly: Boolean,+    onRename: (FileBrowserItem) -> Unit,+    onShowProperties: (FileBrowserItem) -> Unit,+    onArchive: () -> Unit,+    onPickUnzipDestination: () -> Unit,+    onShowNewFolder: () -> Unit,+    onShowNewFile: () -> Unit, ) {     var showOverflow by remember { mutableStateOf(false) }     var showSelectionOverflow by remember { mutableStateOf(false) } -    val zipToUnzip = remember(state.selectedPaths) {-        state.selectedPaths.singleOrNull()?.takeIf {+    val zipToUnzip = remember(selectedPaths) {+        selectedPaths.singleOrNull()?.takeIf {             !it.isDirectory && it.realFile != null && it.name.endsWith(".zip", ignoreCase = true)         }     } -    if (state.isSearchActive) {+    if (isSearchActive) {         IconButton(onClick = { actions.setSearchActive(false) }) { IconClose() }-    } else if (state.selectedPaths.isNotEmpty()) {+    } else if (selectedPaths.isNotEmpty()) {         IconButton(onClick = { actions.clearSelection() }) { IconClose() }         IconButton(onClick = { actions.deleteSelection() }) { IconDelete() }         IconButton(onClick = { showSelectionOverflow = true }) { IconMoreVert() }@@ -86,7 +125,7 @@ internal fun DirectoryTopActions(                 leadingIcon = { IconShare() },                 onClick = { showSelectionOverflow = false; actions.shareSelection() },             )-            val single = state.selectedPaths.singleOrNull()+            val single = selectedPaths.singleOrNull()             if (single != null && !single.isDirectory) {                 DropdownMenuItem(                     text = { Text(stringResource(R.string.open_with)) },@@ -133,7 +172,7 @@ internal fun DirectoryTopActions(                     onClick = { showSelectionOverflow = false; onPickUnzipDestination() },                 )             }-            if (state.hasIncomingUris) {+            if (hasIncomingUris) {                 DropdownMenuItem(                     text = { Text(stringResource(R.string.files_saved)) },                     leadingIcon = { IconSave() },@@ -142,7 +181,7 @@ internal fun DirectoryTopActions(             }         }     } else {-        if (state.hasIncomingUris && !isReadOnly) {+        if (hasIncomingUris && !isReadOnly) {             IconButton(onClick = { actions.saveIncomingUris() }) { IconSave() }         }         IconButton(onClick = { actions.setSearchActive(true) }) { IconSearch() }@@ -154,32 +193,32 @@ internal fun DirectoryTopActions(             SortBy.entries.forEach { option ->                 DropdownMenuItem(                     text = { Text(sortLabel(option)) },-                    leadingIcon = { if (state.sortBy == option) IconCheck() },+                    leadingIcon = { if (sortBy == option) IconCheck() },                     onClick = { showOverflow = false; actions.setSortBy(option) },                 )             }             HorizontalDivider()             DropdownMenuItem(                 text = { Text(stringResource(R.string.sort_ascending)) },-                leadingIcon = { if (state.sortAscending) IconCheck() },+                leadingIcon = { if (sortAscending) IconCheck() },                 onClick = { showOverflow = false; actions.setSortAscending(true) },             )             DropdownMenuItem(                 text = { Text(stringResource(R.string.sort_descending)) },-                leadingIcon = { if (!state.sortAscending) IconCheck() },+                leadingIcon = { if (!sortAscending) IconCheck() },                 onClick = { showOverflow = false; actions.setSortAscending(false) },             )             DropdownMenuItem(                 text = {                     Text(                         stringResource(-                            if (state.viewMode == ViewMode.LIST) R.string.grid_view+                            if (viewMode == ViewMode.LIST) R.string.grid_view                             else R.string.list_view                         )                     )                 },                 leadingIcon = {-                    if (state.viewMode == ViewMode.LIST) IconGrid() else IconList()+                    if (viewMode == ViewMode.LIST) IconGrid() else IconList()                 },                 onClick = { showOverflow = false; actions.toggleViewMode() },             )@@ -187,11 +226,11 @@ internal fun DirectoryTopActions(                 text = {                     Text(                         stringResource(-                            if (state.showHidden) R.string.hide_hidden else R.string.show_hidden+                            if (showHidden) R.string.hide_hidden else R.string.show_hidden                         )                     )                 },-                leadingIcon = { if (state.showHidden) IconVisibilityOff() else IconVisible() },+                leadingIcon = { if (showHidden) IconVisibilityOff() else IconVisible() },                 onClick = { showOverflow = false; actions.toggleHidden() },             )             if (!isReadOnly) {
files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.ktindex 3529b80050..4eaac99406 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt@@ -1,23 +1,24 @@ package com.vayunmathur.files.ui -import android.content.Intent import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect-import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources+import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.files.R import com.vayunmathur.files.data.saf.StorageUris+import com.vayunmathur.files.platform.FileBrowserItem import com.vayunmathur.files.platform.FilesActions-import com.vayunmathur.files.platform.FilesUiState import com.vayunmathur.files.platform.FilesViewModel import com.vayunmathur.library.ui.SnackbarHostState @@ -27,6 +28,15 @@ import com.vayunmathur.library.ui.SnackbarHostState  * [isCurrent] is false while this entry is animating away under a newer one. Every folder on the  * back stack is a separate entry sharing one view model, so without it the outgoing screen would  * repaint with the contents of the folder being opened just as it slides out of view.+ *+ * No flow is collected at this root. Each section below collects only the flows it draws+ * (with [collectAsStateWithLifecycle]), so a change in one flow recomposes only its section.+ * A flow feeding several sections is collected once at their lowest common consumer:+ * `selectedPaths`/`isSearchActive` in [DirectoryScreenCore] (Back, nav icon and the+ * sections all need them), and the sort/view/search/hidden flows in the sections that+ * share them. `clipboardIsCut` has no UI consumer, so it is not collected at all.+ * Every collected value passes through [frozen], preserving the [isCurrent] freeze that+ * the old single `lastShown` snapshot provided.  */ @Composable fun DirectoryPage(@@ -39,22 +49,6 @@ fun DirectoryPage(     val resources = LocalResources.current     val snackbarHostState = remember { SnackbarHostState() } -    val currentDirectory by viewModel.currentDirectory.collectAsState()-    val zipPath by viewModel.zipPath.collectAsState()-    val zipInternalPath by viewModel.zipInternalPath.collectAsState()-    val selectedPaths by viewModel.selectedPaths.collectAsState()-    val entries by viewModel.entries.collectAsState()-    val incomingUris by viewModel.incomingUris.collectAsState()-    val sortBy by viewModel.sortBy.collectAsState()-    val sortAscending by viewModel.sortAscending.collectAsState()-    val viewMode by viewModel.viewMode.collectAsState()-    val searchQuery by viewModel.searchQuery.collectAsState()-    val isSearchActive by viewModel.isSearchActive.collectAsState()-    val clipboard by viewModel.clipboard.collectAsState()-    val clipboardIsCut by viewModel.clipboardIsCut.collectAsState()-    val showHidden by viewModel.showHidden.collectAsState()-    val categoryTitle by viewModel.categoryTitle.collectAsState()-     LaunchedEffect(snackbarHostState) {         viewModel.snackbarMessages.collect { message ->             snackbarHostState.showSnackbar(message)@@ -81,57 +75,227 @@ fun DirectoryPage(         }     } -    val zipToUnzip = remember(selectedPaths) {-        selectedPaths.singleOrNull()?.takeIf {-            !it.isDirectory && it.realFile != null && it.name.endsWith(".zip", ignoreCase = true)-        }-    }-     // The "unzip here" folder picker needs an Activity, so it is launched from here rather-    // than from the screen.+    // than from the screen. The zip and the fallback folder are read from the view model+    // when the pick returns, so neither flow needs collecting at this root.     val treeLauncher =         rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->+            val zipToUnzip = viewModel.selectedPaths.value.singleOrNull()?.takeIf {+                !it.isDirectory && it.realFile != null && it.name.endsWith(".zip", ignoreCase = true)+            }             if (uri != null && zipToUnzip != null) {                 // Resolve the picked tree against its own volume: splitting the                 // URI on ':' and re-rooting at the primary volume extracts an                 // SD-card pick into the same-named internal folder instead.-                val path = StorageUris.fileForTreeUri(context, uri) ?: currentDirectory+                val path = StorageUris.fileForTreeUri(context, uri)+                    ?: viewModel.currentDirectory.value                 viewModel.unzip(zipToUnzip, path)             }         } -    val (directories, files) = entries+    // Lowest common consumer for selectedPaths/isSearchActive: DirectoryScreenCore.+    val selectedPaths by viewModel.selectedPaths.collectAsStateWithLifecycle()+    val isSearchActive by viewModel.isSearchActive.collectAsStateWithLifecycle()+    DirectoryScreenCore(+        selectedPaths = frozen(isCurrent, selectedPaths),+        isSearchActive = frozen(isCurrent, isSearchActive),+        actions = actions,+        snackbarHostState = snackbarHostState,+        onOpenDrawer = onOpenDrawer,+        title = { DirectoryTitleLive(viewModel, actions, isCurrent) },+        topActions = { onRename, onShowProperties, onArchive, onShowNewFolder, onShowNewFile ->+            DirectoryTopActionsLive(+                viewModel = viewModel,+                actions = actions,+                isCurrent = isCurrent,+                onRename = onRename,+                onShowProperties = onShowProperties,+                onArchive = onArchive,+                onPickUnzipDestination = { treeLauncher.launch(null) },+                onShowNewFolder = onShowNewFolder,+                onShowNewFile = onShowNewFile,+            )+        },+        body = { padding, onClearRenameTarget ->+            DirectoryBodyLive(viewModel, actions, isCurrent, padding, onClearRenameTarget)+        },+    )+}++/**+ * The last value seen while [isCurrent], or [live] itself while current. Keeps a+ * non-current back-stack entry frozen on the folder it showed, per collected flow.+ */+@Composable+private fun <T> frozen(isCurrent: Boolean, live: T): T {+    var last by remember { mutableStateOf(live) }+    SideEffect { if (isCurrent) last = live }+    return if (isCurrent) live else last+} -    val liveState = FilesUiState(+@Composable+private fun DirectoryTitleLive(+    viewModel: FilesViewModel,+    actions: FilesActions,+    isCurrent: Boolean,+) {+    val currentDirectory by viewModel.currentDirectory.collectAsStateWithLifecycle()+    val zipPath by viewModel.zipPath.collectAsStateWithLifecycle()+    val zipInternalPath by viewModel.zipInternalPath.collectAsStateWithLifecycle()+    val isSearchActive by viewModel.isSearchActive.collectAsStateWithLifecycle()+    val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()+    val categoryTitle by viewModel.categoryTitle.collectAsStateWithLifecycle()+    val shownZipPath = frozen(isCurrent, zipPath)+    val shownCategoryTitle = frozen(isCurrent, categoryTitle)+    DirectoryTitle(         rootDirectory = viewModel.rootDirectory,         rootDisplayName = Build.MODEL,-        currentDirectory = currentDirectory,-        zipPath = zipPath,-        zipInternalPath = zipInternalPath,-        directories = directories,-        files = files,-        selectedPaths = selectedPaths,-        hasIncomingUris = incomingUris != null,-        sortBy = sortBy,-        sortAscending = sortAscending,-        viewMode = viewMode,-        searchQuery = searchQuery,-        isSearchActive = isSearchActive,-        clipboardCount = clipboard.size,-        clipboardIsCut = clipboardIsCut,-        showHidden = showHidden,-        categoryTitle = categoryTitle,+        currentDirectory = frozen(isCurrent, currentDirectory),+        zipPath = shownZipPath,+        zipInternalPath = frozen(isCurrent, zipInternalPath),+        isSearchActive = frozen(isCurrent, isSearchActive),+        searchQuery = frozen(isCurrent, searchQuery),+        categoryTitle = shownCategoryTitle,+        actions = actions,+        isCategory = shownCategoryTitle != null,+        isReadOnly = shownZipPath != null,     )-    var lastShown by remember { mutableStateOf(liveState) }-    if (isCurrent) SideEffect { lastShown = liveState }+} -    DirectoryScreen(-        state = if (isCurrent) liveState else lastShown,+@Composable+private fun DirectoryTopActionsLive(+    viewModel: FilesViewModel,+    actions: FilesActions,+    isCurrent: Boolean,+    onRename: (FileBrowserItem) -> Unit,+    onShowProperties: (FileBrowserItem) -> Unit,+    onArchive: () -> Unit,+    onPickUnzipDestination: () -> Unit,+    onShowNewFolder: () -> Unit,+    onShowNewFile: () -> Unit,+) {+    val selectedPaths by viewModel.selectedPaths.collectAsStateWithLifecycle()+    val isSearchActive by viewModel.isSearchActive.collectAsStateWithLifecycle()+    val incomingUris by viewModel.incomingUris.collectAsStateWithLifecycle()+    val sortBy by viewModel.sortBy.collectAsStateWithLifecycle()+    val sortAscending by viewModel.sortAscending.collectAsStateWithLifecycle()+    val viewMode by viewModel.viewMode.collectAsStateWithLifecycle()+    val showHidden by viewModel.showHidden.collectAsStateWithLifecycle()+    val zipPath by viewModel.zipPath.collectAsStateWithLifecycle()+    val categoryTitle by viewModel.categoryTitle.collectAsStateWithLifecycle()+    val isReadOnly = frozen(isCurrent, zipPath) != null+    val isCategory = frozen(isCurrent, categoryTitle) != null+    DirectoryTopActions(+        selectedPaths = frozen(isCurrent, selectedPaths),+        isSearchActive = frozen(isCurrent, isSearchActive),+        hasIncomingUris = frozen(isCurrent, incomingUris) != null,+        sortBy = frozen(isCurrent, sortBy),+        sortAscending = frozen(isCurrent, sortAscending),+        viewMode = frozen(isCurrent, viewMode),+        showHidden = frozen(isCurrent, showHidden),         actions = actions,-        snackbarHostState = snackbarHostState,-        onPickUnzipDestination = { treeLauncher.launch(null) },-        onOpenDrawer = onOpenDrawer,+        canModifyHere = !isReadOnly && !isCategory,+        isReadOnly = isReadOnly,+        onRename = onRename,+        onShowProperties = onShowProperties,+        onArchive = onArchive,+        onPickUnzipDestination = onPickUnzipDestination,+        onShowNewFolder = onShowNewFolder,+        onShowNewFile = onShowNewFile,     ) } +@Composable+private fun DirectoryBodyLive(+    viewModel: FilesViewModel,+    actions: FilesActions,+    isCurrent: Boolean,+    padding: PaddingValues,+    onClearRenameTarget: () -> Unit,+) {+    val currentDirectory by viewModel.currentDirectory.collectAsStateWithLifecycle()+    val zipPath by viewModel.zipPath.collectAsStateWithLifecycle()+    val categoryTitle by viewModel.categoryTitle.collectAsStateWithLifecycle()+    val isReadOnly = frozen(isCurrent, zipPath) != null+    val isCategory = frozen(isCurrent, categoryTitle) != null+    val canModifyHere = !isReadOnly && !isCategory+    DirectoryBody(+        currentDirectory = frozen(isCurrent, currentDirectory),+        rootDirectory = viewModel.rootDirectory,+        isCategory = isCategory,+        isReadOnly = isReadOnly,+        padding = padding,+        parentPane = { modifier -> DirectoryParentPaneLive(viewModel, actions, isCurrent, modifier) },+        listing = { modifier ->+            DirectoryListingLive(+                viewModel = viewModel,+                actions = actions,+                isCurrent = isCurrent,+                canModifyHere = canModifyHere,+                isReadOnly = isReadOnly,+                modifier = modifier,+                onClearRenameTarget = onClearRenameTarget,+            )+        },+    )+}++@Composable+private fun DirectoryParentPaneLive(+    viewModel: FilesViewModel,+    actions: FilesActions,+    isCurrent: Boolean,+    modifier: Modifier,+) {+    val currentDirectory by viewModel.currentDirectory.collectAsStateWithLifecycle()+    val showHidden by viewModel.showHidden.collectAsStateWithLifecycle()+    val sortBy by viewModel.sortBy.collectAsStateWithLifecycle()+    val sortAscending by viewModel.sortAscending.collectAsStateWithLifecycle()+    val viewMode by viewModel.viewMode.collectAsStateWithLifecycle()+    val selectedPaths by viewModel.selectedPaths.collectAsStateWithLifecycle()+    DirectoryParentPane(+        currentDirectory = frozen(isCurrent, currentDirectory),+        rootDirectory = viewModel.rootDirectory,+        rootDisplayName = Build.MODEL,+        showHidden = frozen(isCurrent, showHidden),+        sortBy = frozen(isCurrent, sortBy),+        sortAscending = frozen(isCurrent, sortAscending),+        viewMode = frozen(isCurrent, viewMode),+        selectedPaths = frozen(isCurrent, selectedPaths),+        actions = actions,+        modifier = modifier,+    )+} +@Composable+private fun DirectoryListingLive(+    viewModel: FilesViewModel,+    actions: FilesActions,+    isCurrent: Boolean,+    canModifyHere: Boolean,+    isReadOnly: Boolean,+    modifier: Modifier,+    onClearRenameTarget: () -> Unit,+) {+    val entries by viewModel.entries.collectAsStateWithLifecycle()+    val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()+    val clipboard by viewModel.clipboard.collectAsStateWithLifecycle()+    val selectedPaths by viewModel.selectedPaths.collectAsStateWithLifecycle()+    val isSearchActive by viewModel.isSearchActive.collectAsStateWithLifecycle()+    val viewMode by viewModel.viewMode.collectAsStateWithLifecycle()+    val (directories, files) = frozen(isCurrent, entries)+    DirectoryListing(+        directories = directories,+        files = files,+        searchQuery = frozen(isCurrent, searchQuery),+        clipboardCount = frozen(isCurrent, clipboard).size,+        selectedPaths = frozen(isCurrent, selectedPaths),+        isSearchActive = frozen(isCurrent, isSearchActive),+        viewMode = frozen(isCurrent, viewMode),+        actions = actions,+        canModifyHere = canModifyHere,+        isReadOnly = isReadOnly,+        modifier = modifier,+        onClearRenameTarget = onClearRenameTarget,+    )+}
files/src/main/java/com/vayunmathur/files/ui/DirectoryParentPane.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryParentPane.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryParentPane.ktindex 9527b00de0..fe506bd692 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryParentPane.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryParentPane.kt@@ -52,8 +52,35 @@ fun DirectoryParentPane(     actions: FilesActions,     modifier: Modifier = Modifier, ) {-    val current = state.currentDirectory-    val root = state.rootDirectory+    DirectoryParentPane(+        currentDirectory = state.currentDirectory,+        rootDirectory = state.rootDirectory,+        rootDisplayName = state.rootDisplayName,+        showHidden = state.showHidden,+        sortBy = state.sortBy,+        sortAscending = state.sortAscending,+        viewMode = state.viewMode,+        selectedPaths = state.selectedPaths,+        actions = actions,+        modifier = modifier,+    )+}++@Composable+fun DirectoryParentPane(+    currentDirectory: File,+    rootDirectory: File,+    rootDisplayName: String,+    showHidden: Boolean,+    sortBy: SortBy,+    sortAscending: Boolean,+    viewMode: ViewMode,+    selectedPaths: Set<FileBrowserItem>,+    actions: FilesActions,+    modifier: Modifier = Modifier,+) {+    val current = currentDirectory+    val root = rootDirectory     val parent = remember(current) { current.parentFile }     if (parent == null || current.absolutePath == root.absolutePath) {         Box(modifier.fillMaxSize()) {}@@ -61,17 +88,17 @@ fun DirectoryParentPane(     }      val siblings = remember(-        parent.absolutePath, state.showHidden, state.sortBy, state.sortAscending+        parent.absolutePath, showHidden, sortBy, sortAscending     ) {         val all = parent.listFiles()?.toList().orEmpty()-        val visible = if (state.showHidden) all else all.filterNot { it.name.startsWith(".") }+        val visible = if (showHidden) all else all.filterNot { it.name.startsWith(".") }         val (dirs, files) = visible.map { it.toSiblingItem() }.partition { it.isDirectory }-        sortSiblings(dirs, state.sortBy, state.sortAscending) +-            sortSiblings(files, state.sortBy, state.sortAscending)+        sortSiblings(dirs, sortBy, sortAscending) ++            sortSiblings(files, sortBy, sortAscending)     }      val onSiblingClick: (FileBrowserItem) -> Unit = { child ->-        if (state.selectedPaths.isNotEmpty()) actions.clearSelection()+        if (selectedPaths.isNotEmpty()) actions.clearSelection()         val target = child.realFile         if (child.isDirectory) {             if (target != null) actions.navigateTo(target)@@ -84,7 +111,7 @@ fun DirectoryParentPane(         }     } -    val header = if (parent.absolutePath == root.absolutePath) state.rootDisplayName else parent.name+    val header = if (parent.absolutePath == root.absolutePath) rootDisplayName else parent.name     Column(modifier) {         Box(             Modifier@@ -100,7 +127,7 @@ fun DirectoryParentPane(                     color = MaterialTheme.colorScheme.outline,                 )             }-        } else if (state.viewMode == ViewMode.GRID) {+        } else if (viewMode == ViewMode.GRID) {             LazyVerticalGrid(                 columns = GridCells.Adaptive(minSize = 104.dp),                 modifier = Modifier.weight(1f).fillMaxWidth(),
files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.ktindex 07dfe03e7d..4b82782fd8 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt@@ -3,6 +3,7 @@ package com.vayunmathur.files.ui import androidx.activity.compose.BackHandler import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize@@ -60,6 +61,137 @@ fun DirectoryScreen(     // (new/paste/move/rename/archive) that target "here" don't apply.     val canModifyHere = !isReadOnly && !isCategory +    DirectoryScreenCore(+        selectedPaths = state.selectedPaths,+        isSearchActive = state.isSearchActive,+        actions = actions,+        snackbarHostState = snackbarHostState,+        onOpenDrawer = onOpenDrawer,+        title = {+            DirectoryTitle(+                state = state,+                actions = actions,+                isCategory = isCategory,+                isReadOnly = isReadOnly,+            )+        },+        topActions = { onRename, onShowProperties, onArchive, onShowNewFolder, onShowNewFile ->+            DirectoryTopActions(+                state = state,+                actions = actions,+                canModifyHere = canModifyHere,+                isReadOnly = isReadOnly,+                onRename = onRename,+                onShowProperties = onShowProperties,+                onArchive = onArchive,+                onPickUnzipDestination = onPickUnzipDestination,+                onShowNewFolder = onShowNewFolder,+                onShowNewFile = onShowNewFile,+            )+        },+        body = { padding, onClearRenameTarget ->+            DirectoryBody(+                state = state,+                actions = actions,+                canModifyHere = canModifyHere,+                isReadOnly = isReadOnly,+                isCategory = isCategory,+                padding = padding,+                onClearRenameTarget = onClearRenameTarget,+            )+        },+    )+}++/** Expanded-width parent pane beside the listing, or the listing alone. Shared by both bodies. */+@Composable+internal fun DirectoryBody(+    state: FilesUiState,+    actions: FilesActions,+    canModifyHere: Boolean,+    isReadOnly: Boolean,+    isCategory: Boolean,+    padding: PaddingValues,+    onClearRenameTarget: () -> Unit,+) {+    // Expanded windows (desktop, large tablets) list the parent folder beside the current+    // one. This stays inside the same destination on purpose: files deliberately has no+    // list/detail metadata, so one back-stack entry per folder level is what keeps Back+    // walking up exactly one folder with a predictive-back preview of where it lands. A+    // second destination would split that walk. Categories and zip contents have no parent+    // folder, the root has nothing above it, and compact widths keep the push behavior -+    // all of those stay single-pane exactly as before.+    DirectoryBody(+        currentDirectory = state.currentDirectory,+        rootDirectory = state.rootDirectory,+        isCategory = isCategory,+        isReadOnly = isReadOnly,+        padding = padding,+        parentPane = { modifier ->+            DirectoryParentPane(state = state, actions = actions, modifier = modifier)+        },+        listing = { modifier ->+            DirectoryListing(+                state = state,+                actions = actions,+                canModifyHere = canModifyHere,+                isReadOnly = isReadOnly,+                modifier = modifier,+                onClearRenameTarget = onClearRenameTarget,+            )+        },+    )+}++@Composable+internal fun DirectoryBody(+    currentDirectory: java.io.File,+    rootDirectory: java.io.File,+    isCategory: Boolean,+    isReadOnly: Boolean,+    padding: PaddingValues,+    parentPane: @Composable (Modifier) -> Unit,+    listing: @Composable (Modifier) -> Unit,+) {+    val atRoot = currentDirectory.absolutePath == rootDirectory.absolutePath+    if (isExpandedWidth() && !isCategory && !isReadOnly && !atRoot) {+        Row(Modifier.fillMaxSize().padding(padding)) {+            parentPane(Modifier.weight(0.35f).fillMaxHeight())+            VerticalDivider(modifier = Modifier.fillMaxHeight())+            listing(Modifier.weight(0.65f).fillMaxHeight())+        }+    } else {+        listing(Modifier.fillMaxSize().padding(padding))+    }+}++/**+ * Scaffold, dialogs and Back handling for the directory browser.+ *+ * Only [selectedPaths] and [isSearchActive] are read here: they are the lowest common+ * consumer for those flows (Back, the nav icon, clearing the rename target and the+ * archive name all need them alongside the sections). Every other flow is collected+ * by the section composable that consumes it — see the live binders in `DirectoryPage`.+ * The stateless [DirectoryScreen] above supplies the same slots from a [FilesUiState].+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+internal fun DirectoryScreenCore(+    selectedPaths: Set<FileBrowserItem>,+    isSearchActive: Boolean,+    actions: FilesActions,+    snackbarHostState: SnackbarHostState,+    onOpenDrawer: () -> Unit,+    title: @Composable () -> Unit,+    topActions: @Composable (+        onRename: (FileBrowserItem) -> Unit,+        onShowProperties: (FileBrowserItem) -> Unit,+        onArchive: () -> Unit,+        onShowNewFolder: () -> Unit,+        onShowNewFile: () -> Unit,+    ) -> Unit,+    body: @Composable (padding: PaddingValues, onClearRenameTarget: () -> Unit) -> Unit,+) {     var itemBeingRenamed by remember { mutableStateOf<FileBrowserItem?>(null) }     var itemForProperties by remember { mutableStateOf<FileBrowserItem?>(null) }     var showArchiveDialog by remember { mutableStateOf(false) }@@ -67,8 +199,8 @@ fun DirectoryScreen(     var showNewFolderDialog by remember { mutableStateOf(false) }     var showNewFileDialog by remember { mutableStateOf(false) } -    LaunchedEffect(state.selectedPaths) {-        if (state.selectedPaths.isEmpty()) itemBeingRenamed = null+    LaunchedEffect(selectedPaths) {+        if (selectedPaths.isEmpty()) itemBeingRenamed = null     }      if (showArchiveDialog) {@@ -157,9 +289,9 @@ fun DirectoryScreen(     // Only the parts of Back that are not navigation. Folder, archive and category depth are back     // stack entries now, so everything else has to fall through to the navigation host - swallowing     // it here would also swallow the predictive-back gesture and its preview.-    BackHandler(state.isSearchActive || state.selectedPaths.isNotEmpty()) {+    BackHandler(isSearchActive || selectedPaths.isNotEmpty()) {         itemBeingRenamed = null-        if (state.isSearchActive) actions.setSearchActive(false) else actions.handleBack()+        if (isSearchActive) actions.setSearchActive(false) else actions.handleBack()     }      AppScaffold(@@ -173,72 +305,26 @@ fun DirectoryScreen(             },         snackbarHost = { SnackbarHost(snackbarHostState) },         navigationIcon = {-                if (!state.isSearchActive && state.selectedPaths.isEmpty()) {+                if (!isSearchActive && selectedPaths.isEmpty()) {                     IconButton(onClick = onOpenDrawer) { IconMenu() }                 }             },-        title = {-            DirectoryTitle(-                state = state,-                actions = actions,-                isCategory = isCategory,-                isReadOnly = isReadOnly,-            )-        },+        title = title,         actions = {-            DirectoryTopActions(-                state = state,-                actions = actions,-                canModifyHere = canModifyHere,-                isReadOnly = isReadOnly,-                onRename = { itemBeingRenamed = it },-                onShowProperties = { itemForProperties = it },-                onArchive = {+            topActions(+                { itemBeingRenamed = it },+                { itemForProperties = it },+                {                     archiveName =-                        if (state.selectedPaths.size == 1) "${state.selectedPaths.first().name}.zip"+                        if (selectedPaths.size == 1) "${selectedPaths.first().name}.zip"                         else "archive.zip"                     showArchiveDialog = true                 },-                onPickUnzipDestination = onPickUnzipDestination,-                onShowNewFolder = { showNewFolderDialog = true },-                onShowNewFile = { showNewFileDialog = true },+                { showNewFolderDialog = true },+                { showNewFileDialog = true },             )         },     ) { padding ->-        // Expanded windows (desktop, large tablets) list the parent folder beside the current-        // one. This stays inside the same destination on purpose: files deliberately has no-        // list/detail metadata, so one back-stack entry per folder level is what keeps Back-        // walking up exactly one folder with a predictive-back preview of where it lands. A-        // second destination would split that walk. Categories and zip contents have no parent-        // folder, the root has nothing above it, and compact widths keep the push behavior --        // all of those stay single-pane exactly as before.-        val atRoot = state.currentDirectory.absolutePath == state.rootDirectory.absolutePath-        if (isExpandedWidth() && !isCategory && !isReadOnly && !atRoot) {-            Row(Modifier.fillMaxSize().padding(padding)) {-                DirectoryParentPane(-                    state = state,-                    actions = actions,-                    modifier = Modifier.weight(0.35f).fillMaxHeight(),-                )-                VerticalDivider(modifier = Modifier.fillMaxHeight())-                DirectoryListing(-                    state = state,-                    actions = actions,-                    canModifyHere = canModifyHere,-                    isReadOnly = isReadOnly,-                    modifier = Modifier.weight(0.65f).fillMaxHeight(),-                    onClearRenameTarget = { itemBeingRenamed = null },-                )-            }-        } else {-            DirectoryListing(-                state = state,-                actions = actions,-                canModifyHere = canModifyHere,-                isReadOnly = isReadOnly,-                modifier = Modifier.fillMaxSize().padding(padding),-                onClearRenameTarget = { itemBeingRenamed = null },-            )-        }+        body(padding) { itemBeingRenamed = null }     } }
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex a93accd6aa..cb7566f1eb 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -36,6 +36,8 @@ rustNativeLib("photos_fx", "photos")  dependencies {     implementation(libs.androidx.compose.foundation)+    // collectAsStateWithLifecycle in Navigation (as in :auto).+    implementation(libs.androidx.lifecycle.runtime.compose)     implementation(libs.androidx.fragment.ktx)     implementation(project(":library:map"))     implementation(project(":library:image"))
photos/src/main/java/com/vayunmathur/photos/Navigation.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/Navigation.kt b/photos/src/main/java/com/vayunmathur/photos/Navigation.ktindex 4cb4049b3a..d6111f5356 100644--- a/photos/src/main/java/com/vayunmathur/photos/Navigation.kt+++ b/photos/src/main/java/com/vayunmathur/photos/Navigation.kt@@ -7,9 +7,9 @@ import android.net.Uri import androidx.activity.compose.LocalActivity 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.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.util.ListDetailPage import com.vayunmathur.library.util.ListPage import com.vayunmathur.library.util.MainNavigation@@ -51,9 +51,9 @@ fun Navigation(     val viewerRoute = remember(viewUri) { viewerRouteFor(viewUri) }      val backStack = rememberNavBackStack<Route>(viewerRoute ?: Route.Gallery)-    val vaultPhotoDao by secureFolderViewModel.vaultPhotoDao.collectAsState()-    val vaultPassword by secureFolderViewModel.vaultPassword.collectAsState()-    val relockOnExit by secureFolderViewModel.relockOnExit.collectAsState()+    val vaultPhotoDao by secureFolderViewModel.vaultPhotoDao.collectAsStateWithLifecycle()+    val vaultPassword by secureFolderViewModel.vaultPassword.collectAsStateWithLifecycle()+    val relockOnExit by secureFolderViewModel.relockOnExit.collectAsStateWithLifecycle()      RelockEffect(backStack, relockOnExit, vaultPhotoDao, secureFolderViewModel)     IndexViewUriEffect(viewUri, galleryViewModel)