package link.roadio.riff.ui import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertSame import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test class BrowseViewLifetimeTest { private fun root(): BrowserItem = BrowserItem( "root", "Library", BrowserKind.ROOT, children = listOf( BrowserItem( "category:albums", "Albums", BrowserKind.CATEGORY, children = (0..300).map { index -> BrowserItem( "album:$index", "Album $index", BrowserKind.ALBUM, children = listOf( BrowserItem("track:$index:0", "Alpha", BrowserKind.TRACK), BrowserItem("track:$index:1", "Bravo", BrowserKind.TRACK), ), ) }, ), ), ).withBrowseNamePolicy(false) private fun state( root: BrowserItem, index: Int, ) = PlayerUiState( screen = PlayerScreen.HIERARCHY, root = root, browserPath = listOf("category:albums", "album:$index"), hierarchyRoot = HierarchyRoot.ALBUMS, nowPlaying = NowPlayingUiState(), selectorIndex = 1, selectorOffset = 19, focusedItemId = "track:$index:1", pageSize = 6, ) @Test fun evictionDoesNotBlankPreparedCurrentPageOrInvalidateSearchIdentity() { val root = root() val old = state(root, 0) val rows = old.currentNode().children val ready = old.copy(azSnapshot = AzPreparedSection(rows).snapshot(old.azQuery())) for (index in 1..300) state(root, index).currentNode() assertSame(rows, ready.currentNode().children) assertTrue(ready.azAppliedReady()) assertNotNull(ready.currentAzSnapshot()) assertEquals(listOf("track:0:0", "track:0:1"), ready.visibleChildren().map { it.id }) } @Test fun reloadRepairsMoreRememberedContextsThanDisplayCacheCapacity() { val oldRoot = root() val newRoot = root() val navigation = PlayerNavigationState() repeat(301) { navigation.rememberHierarchy(state(oldRoot, it)) } val old = state(oldRoot, 0) val orders = AzReloadOrders(navigationOrderRequests(old, newRoot, navigation.roots, navigation.containers)) val repaired = navigation.repairedCopy(oldRoot, newRoot, orders) assertEquals(301, repaired.containers.size) repaired.containers.forEach { (path, saved) -> assertEquals(1, saved.selectorIndex) assertEquals(19, saved.selectorOffset) assertEquals("track:${path.last().substringAfter(':')}:1", saved.focusedItemId) } } @Test fun failedNavigationRepairLeavesAllOriginalMemoryUntouched() { val oldRoot = root() val newRoot = root() val navigation = PlayerNavigationState() navigation.rememberHierarchy(state(oldRoot, 0)) navigation.rememberHierarchy(state(oldRoot, 1)) val roots = navigation.roots.toMap() val containers = navigation.containers.toMap() assertThrows(IllegalArgumentException::class.java) { navigation.repairNavigationMemory(oldRoot, newRoot, AzReloadOrders(emptyList())) } assertEquals(roots, navigation.roots) assertEquals(containers, navigation.containers) } }