Work already pending in the tree before the bug-fix pass, committed on its own: - Remove Volume boost (it degraded audio) and its setting; keep passthrough. - Leave playback with the server's reason when Plex stops a session (timeline terminationCode/terminationText); never fall back or reconnect after. - Genre filtering lives in Categories; the Library grid lists the whole section. - Update UI verification scripts and AGENTS.md accordingly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
320 lines
27 KiB
Kotlin
320 lines
27 KiB
Kotlin
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||
package tv.kaleido.app
|
||
|
||
import androidx.compose.animation.Crossfade
|
||
import androidx.compose.animation.core.animateFloatAsState
|
||
import androidx.compose.animation.core.tween
|
||
import androidx.compose.foundation.*
|
||
import androidx.compose.foundation.layout.*
|
||
import androidx.compose.foundation.lazy.*
|
||
import androidx.compose.foundation.lazy.grid.*
|
||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||
import androidx.compose.material.icons.Icons
|
||
import androidx.compose.material.icons.outlined.*
|
||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||
import androidx.compose.material.icons.filled.PlayArrow
|
||
import androidx.compose.material3.*
|
||
import androidx.compose.runtime.*
|
||
import kotlinx.coroutines.Job
|
||
import kotlinx.coroutines.launch
|
||
import androidx.compose.runtime.saveable.rememberSaveable
|
||
import androidx.compose.ui.Alignment
|
||
import androidx.compose.ui.Modifier
|
||
import androidx.compose.ui.draw.clip
|
||
import androidx.compose.ui.draw.drawBehind
|
||
import androidx.compose.ui.geometry.Size
|
||
import androidx.compose.ui.focus.*
|
||
import androidx.compose.ui.graphics.Brush
|
||
import androidx.compose.ui.graphics.Color
|
||
import androidx.compose.ui.graphics.ColorFilter
|
||
import androidx.compose.ui.graphics.ColorMatrix
|
||
import androidx.compose.ui.graphics.graphicsLayer
|
||
import androidx.compose.ui.input.key.*
|
||
import androidx.compose.ui.text.font.FontWeight
|
||
import androidx.compose.ui.text.style.TextOverflow
|
||
import androidx.compose.ui.unit.dp
|
||
import androidx.compose.ui.unit.sp
|
||
import kotlinx.coroutines.delay
|
||
import kotlinx.coroutines.flow.first
|
||
import androidx.compose.foundation.shape.CircleShape
|
||
import androidx.compose.foundation.text.KeyboardActions
|
||
import androidx.compose.foundation.text.KeyboardOptions
|
||
import androidx.compose.ui.platform.LocalContext
|
||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||
import androidx.compose.ui.semantics.contentDescription
|
||
import androidx.compose.ui.semantics.semantics
|
||
import androidx.compose.ui.text.TextRange
|
||
import androidx.compose.ui.text.input.ImeAction
|
||
import androidx.compose.ui.text.input.TextFieldValue
|
||
|
||
@Composable fun Brand() {
|
||
Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) {
|
||
KaleidoMark(Modifier.size(29.dp))
|
||
Text("KALEIDO",color=Accent,fontSize=19.sp,lineHeight=24.sp,fontWeight=FontWeight.Bold,letterSpacing=1.4.sp)
|
||
}
|
||
}
|
||
|
||
@Composable fun TopBar(vm:KaleidoViewModel,navigation:DiscoveryNavigation?=null) {
|
||
val initialFocus by remember{derivedStateOf{vm.focusId.isBlank()}}
|
||
val scope=rememberCoroutineScope();val pendingTab=remember{arrayOfNulls<Job>(1)}
|
||
val focusedTab=remember{arrayOf(vm.page.kind)}
|
||
// Let the focus highlight draw before the new section composes in its long frame,
|
||
// so the press responds at once. A quick second move replaces the pending switch.
|
||
fun select(kind:String){vm.tab(kind);vm.focusId="tab:$kind"}
|
||
fun activate(kind:String){pendingTab[0]?.cancel();pendingTab[0]=scope.launch{withFrameNanos{};withFrameNanos{};if(vm.page.kind!=kind)select(kind)}}
|
||
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
|
||
// Extend the scrim beyond the controls so it dissolves into the scene without a hard edge.
|
||
Box(Modifier.fillMaxWidth().height(62.dp).onPreviewKeyEvent {
|
||
// There is no destination above the header. Letting repeated Up events run
|
||
// Compose's default search measures offscreen lazy rows looking for one.
|
||
it.type==KeyEventType.KeyDown&&it.key==Key.DirectionUp
|
||
}.drawBehind {
|
||
val depth=if(immersive)size.height*1.8f else size.height
|
||
val colors=if(!immersive)listOf(Ink,Ink)else if(navigation?.scrolled==true)listOf(Color.Black.copy(alpha=.93f),Color.Black.copy(alpha=.66f),Color.Black.copy(alpha=.18f),Color.Transparent)else listOf(Color.Black.copy(alpha=.64f),Color.Black.copy(alpha=.22f),Color.Transparent)
|
||
drawRect(Brush.verticalGradient(colors,endY=depth),size=Size(size.width,depth))
|
||
}.padding(horizontal=Cinema.gutter)) {
|
||
Box(Modifier.align(Alignment.CenterStart)){Brand()}
|
||
Row(Modifier.align(Alignment.Center).onPreviewKeyEvent{
|
||
if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
|
||
pendingTab[0]?.cancel()
|
||
val target=focusedTab[0]
|
||
if(vm.page.kind!=target){navigation.pendingEntry=target;vm.tab(target);vm.focusId=if(target=="home")"home-feature"else "discovery-entry"}else navigation.of(target).enter?.invoke()
|
||
true
|
||
}else false
|
||
}.focusProperties{if(navigation!=null)down=navigation.of(vm.page.kind).entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) {
|
||
listOf("home" to "Home","movies" to "Movies","tv" to "TV Shows").forEach{(kind,label)->
|
||
NavigationLabel(label,vm.page.kind==kind,modifier=if(navigation!=null&&vm.page.kind==kind)Modifier.focusRequester(navigation.top)else Modifier,initialFocus=vm.page.kind==kind&&initialFocus,onFocused={
|
||
focusedTab[0]=kind
|
||
// A tab already has focus. Don't schedule its delayed initial-focus
|
||
// request again when the section changes: it can steal the next press.
|
||
vm.focusId="tab:$kind"
|
||
if(vm.page.kind!=kind)activate(kind)
|
||
}){pendingTab[0]?.cancel();if(vm.page.kind!=kind)select(kind)}
|
||
}
|
||
}
|
||
Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(9.dp)) {
|
||
IconControl(Icons.Outlined.Search,"Search",selected=vm.page.kind=="search"){vm.tab("search")}
|
||
Box {
|
||
IconControl(Icons.Outlined.Settings,"Settings",selected=vm.page.kind=="settings"){vm.tab("settings")}
|
||
if(vm.update!=null)Box(Modifier.size(4.dp).align(Alignment.TopEnd).padding(top=2.dp).background(Accent,RoundedCornerShape(2.dp)))
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/** [episodeTitles] labels episodes by number and name, for rows already inside their show. [onClick] replaces opening details. */
|
||
/** [selectedItem] is marked and is where [entryFocus] enters, e.g. the episode a season page shows. */
|
||
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null,entryFocus:FocusRequester?=null,episodeTitles:Boolean=false,initialItem:String?=null,selectedItem:String?=initialItem,up:FocusRequester?=null,onFocused:((Title)->Unit)?=null,onClick:((Title)->Unit)?=null) {
|
||
val initial=remember(rowId){items.indexOfFirst{it.id==initialItem}.coerceAtLeast(0)}
|
||
val entry=items.indexOfFirst{it.id==selectedItem}.takeIf{it>=0} ?: initial
|
||
val row=rememberLazyListState(initialFirstVisibleItemIndex=(initial-1).coerceAtLeast(0))
|
||
// A reopened episode page resets its selection, but its saved scroll can still
|
||
// point elsewhere. Compose the entry card before the header sends focus Down.
|
||
LaunchedEffect(rowId){if(initialItem!=null)row.scrollToItem((initial-1).coerceAtLeast(0))}
|
||
Column {
|
||
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)}
|
||
LazyRow(state=row,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) {
|
||
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=(if(index==entry&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).then(if(up!=null)Modifier.focusProperties{this.up=up}else Modifier),onMove={anticipateTileMove(vm,items,index,it,0)},episodeTitle=episodeTitles,current=item.id==selectedItem,onFocused=onFocused,onClick=onClick)}
|
||
}
|
||
}
|
||
}
|
||
|
||
internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
|
||
val target=when(direction){
|
||
Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1
|
||
Key.DirectionRight->if(columns==0||index%columns<columns-1)index+1 else -1
|
||
Key.DirectionUp->if(columns>0)index-columns else -1
|
||
Key.DirectionDown->if(columns>0)index+columns else -1
|
||
else->-1
|
||
}
|
||
items.getOrNull(target)?.let{vm.anticipate(it,backdrop=false)}
|
||
}
|
||
|
||
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,initialFocus:Boolean=false,modifier:Modifier=Modifier,onMove:(Key)->Unit={},episodeTitle:Boolean=false,current:Boolean=false,onFocused:((Title)->Unit)?=null,onClick:((Title)->Unit)?=null) {
|
||
var focused by remember{mutableStateOf(false)}
|
||
val requester=remember{FocusRequester()}
|
||
val scale by animateFloatAsState(if(focused)1.035f else 1f,tween(180),label="artworkFocus")
|
||
LaunchedEffect(Unit){if(vm.focusId==focusKey||initialFocus){delay(220);runCatching{requester.requestFocus()}}}
|
||
Column(modifier.then(if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused;if(it.isFocused){vm.focusId=focusKey;onFocused?.invoke(item)}}.titleActions{vm.showActions(item)}.clickable{if(onClick!=null)onClick(item)else vm.open(item)}) {
|
||
Box(Modifier.fillMaxWidth().aspectRatio(if(landscape)16f/9f else 2f/3f).graphicsLayer{shadowElevation=if(focused)12.dp.toPx()else 0f;shape=RoundedCornerShape(Cinema.radius)}.clip(RoundedCornerShape(Cinema.radius))) {
|
||
val artwork=if(landscape&&item.type=="episode")item.thumb.ifBlank{item.art}else if(landscape)item.art.ifBlank{item.thumb}else item.thumb
|
||
Artwork(vm.api,artwork,Modifier.fillMaxSize(),if(landscape)720 else 450,if(landscape)405 else 675)
|
||
if(item.offset>0)Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(start=7.dp,end=7.dp,bottom=6.dp).height(2.dp).background(Color.Black.copy(alpha=.45f),RoundedCornerShape(1.dp))) {
|
||
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.015f)).fillMaxHeight().background(Accent,RoundedCornerShape(1.dp)))
|
||
}
|
||
WatchBadge(item,vm.watchedPercent)
|
||
if(current&&!focused)Box(Modifier.align(Alignment.TopStart).padding(6.dp).background(Color.Black.copy(alpha=.7f),RoundedCornerShape(3.dp)).padding(horizontal=6.dp,vertical=2.dp)){Text("Now viewing",color=Accent,fontSize=9.sp,lineHeight=12.sp)}
|
||
if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(Cinema.radius)).padding(2.dp).border(1.dp,Color.Black.copy(alpha=.55f),RoundedCornerShape(Cinema.radius)))
|
||
}
|
||
Text(if(episodeTitle&&item.type=="episode")"${item.index}. ${item.title}"else if(item.type=="clip")item.title else if(landscape)item.displayTitle else item.title,color=if(focused)Accent else Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp))
|
||
Text(if(episodeTitle&&item.type=="episode")listOf(if(item.duration>0)"${item.duration/60000} min"else "",item.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(" · ")
|
||
else if(landscape)item.subtitle else item.year.ifBlank{item.subtitle},color=Muted,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=1.dp))
|
||
}
|
||
}
|
||
|
||
@Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) {
|
||
// Discover is a retained DiscoveryScreen (see KaleidoApp); this is only the A–Z library.
|
||
if(!vm.allTitles)return
|
||
val name=if(vm.page.kind=="movies")"Movies"else "TV Shows"
|
||
LaunchedEffect(vm.categories,vm.section?.id,vm.genres){vm.loadCategoryArtworks()}
|
||
var sortMenu by remember{mutableStateOf(false)}
|
||
var sectionMenu by remember{mutableStateOf(false)}
|
||
val discoverFocus=remember{FocusRequester()};val libraryFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()}
|
||
val filterFocus=remember{FocusRequester()};val categoryEntryFocus=remember{FocusRequester()};val railFocus=remember{FocusRequester()};val sectionFocus=remember{FocusRequester()}
|
||
val filters=vm.section!=null||vm.busy
|
||
Column(Modifier.fillMaxSize()) {
|
||
Row(Modifier.fillMaxWidth().height(64.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) {
|
||
Text(name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)
|
||
Spacer(Modifier.width(21.dp))
|
||
NavigationLabel("Discover",!vm.allTitles,modifier=Modifier.focusRequester(discoverFocus).focusProperties{right=libraryFocus},onClick={vm.setAll(false)})
|
||
NavigationLabel("Library",!vm.categories,modifier=Modifier.focusRequester(libraryFocus).focusProperties{right=categoriesFocus;down=if(filters)filterFocus else FocusRequester.Cancel},initialFocus=vm.focusId=="library-entry"){vm.setAll(true)}
|
||
NavigationLabel("Categories",vm.categories,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{right=if(vm.sections.count{it.type==vm.section?.type}>1)sectionFocus else FocusRequester.Cancel;down=if(vm.categories&&vm.genre.isBlank())categoryEntryFocus else if(filters)filterFocus else FocusRequester.Cancel}){vm.openCategories()}
|
||
Spacer(Modifier.weight(1f))
|
||
if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library",Modifier.focusRequester(sectionFocus).focusProperties{left=categoriesFocus}){sectionMenu=true}
|
||
}
|
||
if(vm.categories&&vm.genre.isBlank()) {
|
||
if(vm.section==null)EmptyState("No $name library","This server has no matching library.")
|
||
else if(vm.genres.isEmpty()&&vm.busy)Text("Loading categories…",color=Muted,fontSize=13.sp,modifier=Modifier.padding(start=Cinema.gutter,top=24.dp))
|
||
else if(vm.genres.isEmpty())EmptyState("No categories available","This Plex library has no genre categories.")
|
||
else {
|
||
val categoryRequesters=remember(vm.section?.id,vm.genres,categoryEntryFocus){vm.genres.mapIndexed{i,entry->entry.first to if(i==0)categoryEntryFocus else FocusRequester()}.toMap()}
|
||
val categoryColor=remember{ColorFilter.colorMatrix(ColorMatrix().apply{setToSaturation(.65f)})}
|
||
LazyVerticalGrid(GridCells.Fixed(4),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=18.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(13.dp),modifier=Modifier.fillMaxSize()) {
|
||
itemsIndexed(vm.genres,key={_,it->it.first}){index,entry->
|
||
val requester=categoryRequesters.getValue(entry.first)
|
||
val sample=vm.categoryArtwork[entry.first]
|
||
val artworkPath=sample?.let{it.art.ifBlank{it.thumb}}.orEmpty()
|
||
var focused by remember(entry.first,vm.section?.id){mutableStateOf(false)}
|
||
val shape=RoundedCornerShape(Cinema.radius)
|
||
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).focusRequester(requester).focusProperties {
|
||
left=if(index%4==0)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index-1].first)
|
||
right=if(index%4==3||index==vm.genres.lastIndex)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+1].first)
|
||
up=if(index<4)categoriesFocus else categoryRequesters.getValue(vm.genres[index-4].first)
|
||
down=if(index+4>=vm.genres.size)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+4].first)
|
||
}.onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId="category:${entry.first}"}.navigationSound().clip(shape).background(Color(0xFF171717)).border(if(focused)2.dp else 1.dp,Color.White.copy(alpha=if(focused).9f else .1f),shape).clickable{vm.selectCategory(entry.first)}) {
|
||
if(artworkPath.isNotBlank())Artwork(vm.api,artworkPath,Modifier.fillMaxSize(),540,304,colorFilter=categoryColor)
|
||
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha=if(focused).48f else .62f)))
|
||
Text(entry.second,color=Color.White,fontSize=22.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,maxLines=2,overflow=TextOverflow.Ellipsis,textAlign=androidx.compose.ui.text.style.TextAlign.Center,
|
||
style=LocalTextStyle.current.copy(shadow=androidx.compose.ui.graphics.Shadow(Color.Black,androidx.compose.ui.geometry.Offset(0f,1f),5f)),modifier=Modifier.align(Alignment.Center).fillMaxWidth().padding(horizontal=16.dp))
|
||
}
|
||
LaunchedEffect(vm.focusId,index){if((vm.focusId=="categories-entry"&&index==0)||vm.focusId=="category:${entry.first}"){withFrameNanos{};runCatching{requester.requestFocus()}}}
|
||
}
|
||
}
|
||
}
|
||
} else if(!filters)EmptyState("No $name library","This server has no matching library.")
|
||
else {
|
||
Row(Modifier.fillMaxWidth().height(43.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(8.dp)) {
|
||
Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp)
|
||
Spacer(Modifier.weight(1f))
|
||
TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus},selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)}
|
||
TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true}
|
||
}
|
||
val grid=rememberLazyGridState()
|
||
val tileRequesters=remember{mutableMapOf<String,FocusRequester>()}
|
||
val scope=rememberCoroutineScope()
|
||
val enabledLetters=remember{LibraryJumpLetters.toSet()}
|
||
LaunchedEffect(grid,vm.library.size,vm.total){snapshotFlow{grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0}.collect{if(it>=vm.library.size-18&&vm.library.isNotEmpty())vm.more()}}
|
||
LaunchedEffect(vm.libraryJumpRequest){
|
||
val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size} ?: return@LaunchedEffect
|
||
grid.scrollToItem(index)
|
||
}
|
||
LaunchedEffect(vm.libraryFocusRequest){
|
||
val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")}
|
||
val index=itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0}
|
||
?: if(vm.focusId=="category-grid"&&!vm.busy&&vm.library.isNotEmpty())0 else -1
|
||
if(index>=0){
|
||
grid.scrollToItem(index)
|
||
snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it}
|
||
withFrameNanos{}
|
||
tileRequesters[vm.library[index].id]?.requestFocus()
|
||
}
|
||
}
|
||
suspend fun returnFocusToGrid(){
|
||
val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")}
|
||
val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size}
|
||
?: itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0} ?: 0
|
||
if(vm.library.isNotEmpty()){
|
||
grid.scrollToItem(index)
|
||
snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it}
|
||
withFrameNanos{}
|
||
tileRequesters[vm.library[index].id]?.requestFocus()
|
||
}
|
||
}
|
||
Row(Modifier.fillMaxWidth().weight(1f),horizontalArrangement=Arrangement.spacedBy(7.dp),verticalAlignment=Alignment.Top) {
|
||
LazyVerticalGrid(GridCells.Fixed(6),state=grid,contentPadding=PaddingValues(start=Cinema.gutter,end=5.dp,top=10.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.weight(1f)) {
|
||
itemsIndexed(vm.library,key={_,it->it.id}){index,item->
|
||
val requester=tileRequesters.getOrPut(item.id){FocusRequester()}
|
||
val lastColumn=index%6==5||index==vm.library.lastIndex
|
||
MediaTile(vm,item,"library:${item.id}",fillWidth=true,modifier=Modifier.focusRequester(requester).then(if(lastColumn)Modifier.focusProperties{right=railFocus}else Modifier),onMove={anticipateTileMove(vm,vm.library,index,it,6)},onFocused={vm.onLibraryGridFocused()})
|
||
}
|
||
if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another category or watch filter.")}
|
||
if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}}
|
||
}
|
||
LibraryJumpRail(enabledLetters,vm.libraryJumpLetter,railFocus,{scope.launch{runCatching{ returnFocusToGrid() }}},{vm.jumpToLibraryLetter(it)})
|
||
}
|
||
}
|
||
}
|
||
if(sortMenu)ChoiceDialog("Sort by",sortLabels.map{it.second},sortLabels.indexOfFirst{it.first==vm.sort},{sortMenu=false}){vm.filter(sortValue=sortLabels[it].first);sortMenu=false}
|
||
if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}}
|
||
}
|
||
|
||
@Composable fun SearchScreen(vm:KaleidoViewModel) {
|
||
val field=remember{FocusRequester()};val resultsFocus=remember{FocusRequester()};val clearFocus=remember{FocusRequester()}
|
||
val keyboard=LocalSoftwareKeyboardController.current
|
||
var value by remember{mutableStateOf(TextFieldValue(vm.query,TextRange(vm.query.length)))}
|
||
fun query(text:String){value=TextFieldValue(text,TextRange(text.length));vm.search(text)}
|
||
LaunchedEffect(vm.query){if(vm.query!=value.text)value=TextFieldValue(vm.query,TextRange(vm.query.length))}
|
||
val groups=remember(vm.searchResults,vm.query){searchGroups(vm.searchResults.titles,vm.query)}
|
||
val people=vm.searchResults.people
|
||
val hasResults=groups.isNotEmpty()||people.isNotEmpty()
|
||
fun enterResults(){keyboard?.hide();runCatching{resultsFocus.requestFocus()}}
|
||
Column(Modifier.fillMaxSize()) {
|
||
Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=12.dp,bottom=12.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) {
|
||
Text("Search",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp,modifier=Modifier.padding(end=7.dp))
|
||
// Returning from a result's details restores that result instead.
|
||
LaunchedEffect(Unit){if(!vm.focusId.startsWith("search-")){delay(150);runCatching{field.requestFocus()}}}
|
||
OutlinedTextField(value,{value=it;if(it.text!=vm.query)vm.search(it.text)},placeholder={Text("Movies, shows, episodes, people",fontSize=12.sp)},leadingIcon={Icon(Icons.Outlined.Search,null,Modifier.size(19.dp))},singleLine=true,
|
||
keyboardOptions=KeyboardOptions(imeAction=ImeAction.Search),keyboardActions=KeyboardActions(onSearch={if(hasResults)enterResults()else keyboard?.hide()}),
|
||
// Down enters results; Right at the end reaches Clear without deleting character by character.
|
||
modifier=Modifier.weight(1f).height(49.dp).focusRequester(field).onPreviewKeyEvent{
|
||
if(it.type!=KeyEventType.KeyDown)false
|
||
else if(it.key==Key.DirectionDown){if(hasResults)enterResults()else if(value.text.isNotEmpty()){keyboard?.hide();runCatching{clearFocus.requestFocus()}};true}
|
||
else if(it.key==Key.DirectionRight&&value.text.isNotEmpty()&&value.selection.collapsed&&value.selection.end==value.text.length){keyboard?.hide();runCatching{clearFocus.requestFocus()};true}
|
||
else false
|
||
},shape=RoundedCornerShape(6.dp),textStyle=androidx.compose.ui.text.TextStyle(fontSize=13.sp),colors=OutlinedTextFieldDefaults.colors(unfocusedBorderColor=Color.White.copy(alpha=.15f),focusedBorderColor=Accent))
|
||
if(value.text.isNotEmpty())ActionButton("Clear",Icons.Outlined.Close,modifier=Modifier.focusRequester(clearFocus).focusProperties{left=field;if(hasResults)down=resultsFocus}){
|
||
// Move focus before removing this button from the composition.
|
||
runCatching{field.requestFocus()};query("")
|
||
}
|
||
if(vm.query.isNotBlank())Text((vm.searchResults.titles.size+people.size).let{if(it==1)"1 result" else "$it results"},color=Muted,fontSize=11.sp)
|
||
}
|
||
if(vm.query.isNotBlank()&&!hasResults&&!vm.busy)Text("No matches for “${vm.query}”.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(start=Cinema.gutter,top=8.dp))
|
||
// Grouped rows, like Home: Movies, TV shows, collections, episodes, then people.
|
||
LazyColumn(Modifier.fillMaxSize(),contentPadding=PaddingValues(top=4.dp,bottom=30.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
|
||
groups.forEachIndexed{index,group->
|
||
item(key="search-${group.first}"){MediaRow(vm,group.first,group.second,"search-${group.first}",landscape=group.first=="Episodes",entryFocus=if(index==0)resultsFocus else null)}
|
||
}
|
||
if(people.isNotEmpty())item(key="search-people"){PeopleRow(vm,people,if(groups.isEmpty())resultsFocus else null)}
|
||
}
|
||
}
|
||
}
|
||
|
||
internal fun searchGroups(titles:List<Title>,query:String=""):List<Pair<String,List<Title>>> = rankSearchGroups(
|
||
titles,query,Title::type
|
||
){title->listOf(title.title,title.parentTitle,title.grandparentTitle)}
|
||
|
||
@Composable private fun PeopleRow(vm:KaleidoViewModel,people:List<CastMember>,entryFocus:FocusRequester?) {
|
||
Column {
|
||
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading("People")}
|
||
LazyRow(contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) {
|
||
itemsIndexed(people,key={_,it->it.id}){index,actor->
|
||
var focused by remember{mutableStateOf(false)}
|
||
Column(Modifier.width(108.dp).then(if(index==0&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).navigationSound().onFocusChanged{focused=it.isFocused}
|
||
.clickable{vm.openActor(actor)}.semantics{contentDescription=actor.name},horizontalAlignment=Alignment.CenterHorizontally) {
|
||
ActorPortrait(vm.api,actor,Modifier.size(86.dp).then(if(focused)Modifier.border(2.dp,Accent,CircleShape)else Modifier))
|
||
Text(actor.name,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=14.sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp))
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|