SettingsScreen.kt

20.6 KB · raw

1package com.peachpasswords.ui.settings23import androidx.activity.compose.BackHandler4import androidx.compose.animation.core.Animatable5import androidx.compose.animation.core.animateDpAsState6import androidx.compose.animation.core.animateFloat7import androidx.compose.animation.core.animateFloatAsState8import androidx.compose.animation.core.infiniteRepeatable9import androidx.compose.animation.core.keyframes10import androidx.compose.animation.core.rememberInfiniteTransition11import androidx.compose.animation.core.tween12import androidx.compose.foundation.background13import androidx.compose.foundation.clickable14import androidx.compose.foundation.gestures.detectDragGestures15import androidx.compose.foundation.interaction.MutableInteractionSource16import androidx.compose.foundation.layout.Arrangement17import androidx.compose.foundation.layout.Box18import androidx.compose.foundation.layout.BoxWithConstraints19import androidx.compose.foundation.layout.Column20import androidx.compose.foundation.layout.Row21import androidx.compose.foundation.layout.Spacer22import androidx.compose.foundation.layout.fillMaxSize23import androidx.compose.foundation.layout.fillMaxWidth24import androidx.compose.foundation.layout.height25import androidx.compose.foundation.layout.padding26import androidx.compose.foundation.layout.size27import androidx.compose.foundation.layout.statusBarsPadding28import androidx.compose.foundation.rememberScrollState29import androidx.compose.foundation.shape.RoundedCornerShape30import androidx.compose.foundation.verticalScroll31import androidx.compose.runtime.Composable32import androidx.compose.runtime.LaunchedEffect33import androidx.compose.runtime.getValue34import androidx.compose.runtime.mutableStateOf35import androidx.compose.runtime.remember36import androidx.compose.runtime.rememberCoroutineScope37import androidx.compose.runtime.setValue38import androidx.compose.runtime.collectAsState39import androidx.compose.ui.Alignment40import androidx.compose.ui.Modifier41import androidx.compose.ui.draw.clip42import androidx.compose.ui.draw.drawWithCache43import androidx.compose.ui.draw.shadow44import androidx.compose.ui.draw.drawBehind45import androidx.compose.ui.geometry.Offset46import androidx.compose.ui.graphics.BlendMode47import androidx.compose.ui.graphics.Brush48import androidx.compose.ui.graphics.Color49import androidx.compose.ui.graphics.drawscope.DrawScope50import androidx.compose.ui.graphics.graphicsLayer51import androidx.compose.ui.input.pointer.pointerInput52import androidx.compose.ui.platform.LocalDensity53import androidx.compose.ui.unit.Dp54import androidx.compose.ui.text.font.FontStyle55import androidx.compose.ui.text.font.FontWeight56import androidx.compose.ui.text.style.TextOverflow57import androidx.compose.ui.unit.dp58import androidx.compose.ui.unit.em59import androidx.compose.ui.unit.sp60import androidx.compose.ui.zIndex61import androidx.hilt.navigation.compose.hiltViewModel62import androidx.compose.material3.Text63import com.peachpasswords.ui.theme.LocalPeachAccent64import com.peachpasswords.ui.theme.LocalReduceMotion65import com.peachpasswords.ui.theme.peachColors66import com.peachpasswords.ui.theme.PeachMotion67import com.peachpasswords.ui.theme.PeachTheme68import com.peachpasswords.ui.theme.PeachStackColors69import com.peachpasswords.ui.theme.PeachType70import com.peachpasswords.ui.theme.ShellBackground71import kotlinx.coroutines.delay72import kotlinx.coroutines.launch7374// Deck geometry — ported verbatim from StackDeck.tsx constants. The active card75// sits at top:0; every other card is a thin tab fanned below it, ordered76// cyclically starting just after the active card so the stack reads as a loop.77private val EXPANDED_H = 258.dp78private val TAB_H = 46.dp79private val TAB_OVERLAP = 14.dp80private val TAB_CARD_H = TAB_H + 4.dp8182/** Drag distance past which a stack card flips between focused and deck states. */83private val DRAG_THRESHOLD = 60.dp8485/** Outcome of releasing a vertical drag on a stack card. */86internal enum class DragOutcome { EXPAND, COLLAPSE, NONE }8788/**89 * Resolve a released drag on a stack card (brief Fix 7). Dragging a collapsed90 * (deck) card up past the threshold focuses it; dragging the focused card down91 * past the threshold returns to the deck. Anything short of the threshold is a no-op.92 */93internal fun resolveStackDrag(dragOffsetPx: Float, thresholdPx: Float, isExpanded: Boolean): DragOutcome = when {94    dragOffsetPx < -thresholdPx && !isExpanded -> DragOutcome.EXPAND95    dragOffsetPx > thresholdPx && isExpanded -> DragOutcome.COLLAPSE96    else -> DragOutcome.NONE97}9899/**100 * Fixed vertical stride between consecutive collapsed tabs — browser parity101 * (StackDeck.tsx: `EXPANDED_H - TAB_OVERLAP + distance * (TAB_H - TAB_OVERLAP)`).102 * The deck reads as a tight physical stack fanned just below the active card, not103 * spread to fill the whole screen. Each tab overlaps its neighbour by [TAB_OVERLAP].104 */105private val COLLAPSED_TAB_STRIDE = TAB_H - TAB_OVERLAP106107/**108 * Top offset (from the deck top) of a collapsed tab at the given cyclic [distance]109 * from the active card. Mirrors the browser's deck-open layout so positions match110 * one-to-one. The active card sits at 0; the first fanned tab sits just under the111 * expanded card and each subsequent tab steps down by one [COLLAPSED_TAB_STRIDE].112 */113internal fun collapsedTabTop(distance: Int): Dp =114    EXPANDED_H - TAB_OVERLAP + COLLAPSED_TAB_STRIDE * distance115116@Composable117fun SettingsScreen(118    onBack: () -> Unit,119    onNavigate: (com.peachpasswords.ui.PeachNav) -> Unit = {},120    vm: SettingsViewModel = hiltViewModel(),121) {122    val entries by vm.entries.collectAsState()123    val settings by vm.settings.collectAsState()124    val isPro by vm.isPro.collectAsState()125    val showCelebration by vm.showCelebration.collectAsState()126    val reduceMotion = LocalReduceMotion.current127    val accent = LocalPeachAccent.current128    val scope = rememberCoroutineScope()129130    var active by remember { mutableStateOf(CardId.Pro) }131    var deckOpen by remember { mutableStateOf(true) }132    var fanning by remember { mutableStateOf(false) }133    var celebrating by remember { mutableStateOf<CardId?>(null) }134135    val activeIndex = STACK_CARDS.indexOfFirst { it.id == active }.coerceAtLeast(0)136137    fun handleBack() {138        if (!deckOpen) deckOpen = true else onBack()139    }140    BackHandler { handleBack() }141142    // Pro celebration: replay every card in a quick fan, land back on Pro, shake.143    fun celebrate() {144        if (fanning) return145        scope.launch {146            fanning = true147            active = CardId.Pro148            CELEBRATION_FAN.forEachIndexed { i, id ->149                delay(150L)150                active = id151            }152            delay(150L)153            active = CardId.Pro154            fanning = false155            celebrating = CardId.Pro156            delay(900L)157            celebrating = null158        }159    }160161    // The Settings stack always renders dark, regardless of the app theme162    // (spec §5.5/§8): force a dark PeachTheme around it — this also darkens the163    // ShellBackground base (which keys off MaterialTheme) — while keeping the164    // user's chosen accent and reduce-motion preference.165    PeachTheme(darkTheme = true, accent = accent, reduceMotion = reduceMotion) {166    ShellBackground {167        Column(Modifier.fillMaxSize().statusBarsPadding().padding(horizontal = 12.dp)) {168            // Masthead: back chevron · "Settings" · card counter.169            Row(170                Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 8.dp),171                verticalAlignment = Alignment.CenterVertically,172            ) {173                Box(174                    Modifier.size(28.dp).clip(RoundedCornerShape(999.dp))175                        .background(Color(0x04F0E8D8))176                        .clickable { handleBack() },177                    contentAlignment = Alignment.Center,178                ) {179                    Text("‹", color = peachColors.T1, fontFamily = PeachType.Mono, fontSize = 16.sp)180                }181                Text(182                    "Settings",183                    modifier = Modifier.weight(1f).padding(start = 10.dp),184                    color = peachColors.T0,185                    fontFamily = PeachType.Display,186                    fontStyle = FontStyle.Italic,187                    fontSize = 22.sp,188                )189                Text(190                    "${activeIndex + 1} / ${STACK_CARDS.size}",191                    color = peachColors.T2,192                    fontFamily = PeachType.Mono,193                    fontSize = 9.sp,194                    letterSpacing = 0.22.em,195                )196            }197198            BoxWithConstraints(Modifier.fillMaxSize()) {199                val focusHeight = maxHeight - 8.dp200                STACK_CARDS.forEachIndexed { index, card ->201                    val isActive = card.id == active202                    val distance = when {203                        index == activeIndex -> -1204                        index > activeIndex -> index - activeIndex - 1205                        else -> STACK_CARDS.size - activeIndex + index - 1206                    }207                    val targetTop = when {208                        isActive -> 0.dp209                        !deckOpen -> focusHeight + 44.dp + (distance * 8).dp210                        else -> collapsedTabTop(distance)211                    }212                    val targetHeight = when {213                        isActive && deckOpen -> EXPANDED_H214                        isActive -> focusHeight215                        else -> TAB_CARD_H216                    }217                    val concealed = !deckOpen && !isActive218219                    val animSpec = if (fanning) {220                        tween<Float>(140, easing = PeachMotion.Celebrate)221                    } else {222                        tween<Float>(PeachMotion.Stack, easing = PeachMotion.StackSpring)223                    }224                    val top by animateDpAsState(225                        targetTop,226                        animationSpec = if (fanning) tween(140, easing = PeachMotion.Celebrate)227                        else tween(PeachMotion.Stack, easing = PeachMotion.StackSpring),228                        label = "top",229                    )230                    val cardH by animateDpAsState(231                        targetHeight,232                        animationSpec = if (fanning) tween(140, easing = PeachMotion.Celebrate)233                        else tween(PeachMotion.Stack, easing = PeachMotion.StackSpring),234                        label = "h",235                    )236                    val alpha by animateFloatAsState(if (concealed) 0f else 1f, animSpec, label = "a")237                    val zIndex = if (isActive) 99f else (50 - distance).toFloat()238239                    // Celebration shake — keyframed bob + tilt as the Pro card lands.240                    val shakeDy = remember { Animatable(0f) }241                    val shakeRot = remember { Animatable(0f) }242                    LaunchedEffect(celebrating == card.id) {243                        if (celebrating == card.id && !reduceMotion) {244                            launch {245                                shakeRot.animateTo(0f, keyframes {246                                    durationMillis = 880247                                    0f at 0; -1.3f at 211; 0.9f at 422; -0.45f at 616; 0f at 757248                                })249                            }250                            shakeDy.animateTo(0f, keyframes {251                                durationMillis = 880252                                0f at 0; -10f at 211; 5f at 422; -4f at 616; 2f at 757253                            })254                        }255                    }256257                    val density = LocalDensity.current258                    StackCard(259                        spec = card,260                        active = isActive,261                        focused = isActive && !deckOpen,262                        lede = vm.lede(card.id, entries.count { it.deletedAt == null }, settings),263                        showSparkle = card.id == CardId.Pro && isPro,264                        onIconClick = if (card.id == CardId.Pro && isPro) ({ celebrate() }) else null,265                        body = {266                            CardBody(267                                id = card.id,268                                fg = card.fg,269                                vm = vm,270                                settings = settings,271                                entriesCount = entries.count { it.deletedAt == null },272                                onNavigate = onNavigate,273                            )274                        },275                        modifier = Modifier276                            .fillMaxWidth()277                            .align(Alignment.TopStart)278                            .zIndex(zIndex)279                            // Drag the deck like a physical stack: flick a tab up to focus280                            // it, drag the focused card down to drop back into the deck.281                            .pointerInput(card.id, deckOpen, isActive) {282                                var dragY = 0f283                                val thresholdPx = with(density) { DRAG_THRESHOLD.toPx() }284                                detectDragGestures(285                                    onDragStart = { dragY = 0f },286                                    onDrag = { change, amount -> change.consume(); dragY += amount.y },287                                    onDragEnd = {288                                        when (resolveStackDrag(dragY, thresholdPx, isActive && !deckOpen)) {289                                            DragOutcome.EXPAND -> { active = card.id; deckOpen = false }290                                            DragOutcome.COLLAPSE -> { deckOpen = true }291                                            DragOutcome.NONE -> {}292                                        }293                                    },294                                )295                            }296                            .graphicsLayer {297                                translationY = top.toPx() + with(density) { shakeDy.value.dp.toPx() }298                                rotationZ = shakeRot.value299                                this.alpha = alpha300                            }301                            .height(cardH),302                        onClick = {303                            // Tapping the active card is a no-op (browser StackDeck304                            // parity); flick it up to focus, a tab up to focus that one.305                            if (!isActive) {306                                active = card.id307                                deckOpen = false308                            }309                        },310                        enabled = !concealed,311                    )312                }313            }314        }315        if (showCelebration) {316            ProCelebration(onDone = { vm.dismissCelebration(); celebrate() })317        }318    }319    }320}321322@Composable323private fun StackCard(324    spec: StackCardSpec,325    active: Boolean,326    focused: Boolean,327    lede: String,328    showSparkle: Boolean,329    onIconClick: (() -> Unit)?,330    body: @Composable () -> Unit,331    modifier: Modifier,332    onClick: () -> Unit,333    enabled: Boolean,334) {335    val interaction = remember { MutableInteractionSource() }336    Box(337        modifier338            .shadow(if (active) 18.dp else 8.dp, RoundedCornerShape(PeachStackColors.CardRadius), clip = false)339            .clip(RoundedCornerShape(PeachStackColors.CardRadius))340            .drawBehind { drawRect(brush = cardGradient155(spec.bgStart, spec.bgEnd)) }341            .clickable(342                interactionSource = interaction,343                indication = null,344                enabled = enabled && !active || (active && !focused),345            ) { onClick() }346            .padding(347                horizontal = if (active) 18.dp else 16.dp,348                vertical = if (active) 16.dp else 12.dp,349            ),350    ) {351        if (showSparkle) SparkleDust(Modifier.fillMaxSize())352        if (active) {353            Column(Modifier.fillMaxSize()) {354                Row(355                    Modifier.fillMaxWidth(),356                    horizontalArrangement = Arrangement.SpaceBetween,357                    verticalAlignment = Alignment.CenterVertically,358                ) {359                    Text(360                        spec.num,361                        color = spec.fg.copy(alpha = 0.7f),362                        fontFamily = PeachType.Mono,363                        fontSize = 8.5.sp,364                        letterSpacing = 0.26.em,365                    )366                    Box(367                        Modifier.clip(RoundedCornerShape(999.dp))368                            .then(if (onIconClick != null) Modifier.clickable { onIconClick() } else Modifier)369                            .padding(2.dp),370                    ) {371                        CardIcon(spec.icon, spec.fg.copy(alpha = 0.85f))372                    }373                }374                Text(375                    spec.title,376                    modifier = Modifier.padding(top = 6.dp),377                    color = spec.fg,378                    fontFamily = PeachType.Display,379                    fontStyle = FontStyle.Italic,380                    fontSize = 26.sp,381                )382                Text(383                    lede,384                    modifier = Modifier.padding(top = 4.dp),385                    color = spec.fg.copy(alpha = 0.72f),386                    fontFamily = PeachType.Display,387                    fontStyle = FontStyle.Italic,388                    fontSize = 12.5.sp,389                )390                // Body scrolls independently; only revealed at full height in391                // focus mode, but kept mounted so deck-mode shows a preview.392                Column(393                    Modifier.fillMaxWidth().weight(1f)394                        .padding(top = 14.dp)395                        .verticalScroll(rememberScrollState()),396                ) {397                    body()398                    Spacer(Modifier.height(24.dp))399                }400            }401        } else {402            // Tab: just the title, single line, vertically centred.403            Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterStart) {404                Text(405                    spec.title,406                    color = spec.fg,407                    fontFamily = PeachType.Display,408                    fontStyle = FontStyle.Italic,409                    fontWeight = FontWeight.Normal,410                    fontSize = 19.sp,411                    maxLines = 1,412                    overflow = TextOverflow.Ellipsis,413                )414            }415        }416    }417}418419/**420 * Settings card gradient at CSS 155° across the drawn card (spec §5.5). Computed421 * from the live draw size so the angle holds on any card height, unlike Compose's422 * default corner-to-corner linear gradient.423 */424private fun DrawScope.cardGradient155(start: Color, end: Color): Brush {425    val a = Math.toRadians(155.0)426    val dx = kotlin.math.sin(a).toFloat()427    val dy = -kotlin.math.cos(a).toFloat()428    val cx = size.width / 2f429    val cy = size.height / 2f430    val half = (kotlin.math.abs(dx) * size.width + kotlin.math.abs(dy) * size.height) / 2f431    return Brush.linearGradient(432        colors = listOf(start, end),433        start = Offset(cx - dx * half, cy - dy * half),434        end = Offset(cx + dx * half, cy + dy * half),435    )436}437438/**439 * Ambient drifting sparkle dust for the Pro card. Three offset dot grids slowly440 * translate diagonally and loop, screen-blended at low opacity — the Compose441 * analogue of the browser's `stk-pro-dust` keyframes.442 */443@Composable444private fun SparkleDust(modifier: Modifier = Modifier) {445    val reduceMotion = LocalReduceMotion.current446    val t = rememberInfiniteTransition(label = "dust")447    val drift by if (reduceMotion) {448        remember { mutableStateOf(0f) }449    } else {450        t.animateFloat(451            initialValue = 0f,452            targetValue = 1f,453            animationSpec = infiniteRepeatable(tween(14000, easing = androidx.compose.animation.core.LinearEasing)),454            label = "drift",455        )456    }457    Box(458        modifier.drawWithCache {459            val tile = 48.dp.toPx()460            val dx = drift * tile461            onDrawBehind {462                val cols = (size.width / tile).toInt() + 2463                val rows = (size.height / tile).toInt() + 2464                for (r in 0..rows) {465                    for (c in 0..cols) {466                        val baseX = c * tile + dx467                        val baseY = r * tile + dx468                        drawCircle(Color(0xFFFFF8DC), 0.6f, Offset(baseX % (size.width + tile), baseY % (size.height + tile)), alpha = 0.11f, blendMode = BlendMode.Screen)469                        drawCircle(Color(0xFFFFEEAA), 1f, Offset((baseX + 19f) % (size.width + tile), (baseY + 15f) % (size.height + tile)), alpha = 0.08f, blendMode = BlendMode.Screen)470                    }471                }472            }473        },474    )475}