Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

21.9 KB
Raw Blame
// Vendored from the Backdrop catalog app, Apache-2.0.
//
//   https://github.com/Kyant0/AndroidLiquidGlass
//   commit b18eb0ff12c616546a68c72e7d0097f1ab286c87
//
// These are the library author's own example components rather than part of the
// published artifact, so there is nothing to depend on — they have to be copied.
// Kept as close to upstream as possible (package line and a few Material
// swaps aside) so a later upstream fix can be diffed in; see LICENSE-backdrop.txt.

package dev.lelonio.square.ui.glass

import dev.lelonio.square.ui.glass.morph.liquidGlassIndicator
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.Constraints
import kotlin.math.roundToInt
import dev.lelonio.square.ui.glass.backdrop.BackdropEffectScope
import androidx.compose.ui.graphics.GraphicsLayerScope
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastCoerceIn
import androidx.compose.ui.util.fastRoundToInt
import androidx.compose.ui.util.lerp
import dev.lelonio.square.ui.glass.backdrop.Backdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.layerBackdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberLayerBackdrop
import dev.lelonio.square.ui.glass.backdrop.drawBackdrop
import dev.lelonio.square.ui.glass.backdrop.effects.blur
import dev.lelonio.square.ui.glass.backdrop.effects.lens
import dev.lelonio.square.ui.glass.backdrop.effects.vibrancy
import dev.lelonio.square.ui.glass.backdrop.highlight.Highlight
import dev.lelonio.square.ui.glass.backdrop.shadow.InnerShadow
import dev.lelonio.square.ui.glass.backdrop.shadow.Shadow
import dev.lelonio.square.ui.glass.shapes.ContinuousCapsule
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.sign

// The tinted copy is a drawing source, not another shared-transition endpoint.
internal val LocalLiquidBottomTabsReplica = staticCompositionLocalOf { false }
// The geometric shell is a sibling, captured before the selector is drawn.
internal val LocalLiquidBottomTabsSurfaceBackdrop = staticCompositionLocalOf<Backdrop?> { null }

@Composable
fun LiquidBottomTabs(
    selectedTabIndex: () -> Int,
    onTabSelected: (index: Int) -> Unit,
    backdrop: Backdrop,
    tabsCount: Int,
    modifier: Modifier = Modifier,
    // LOCAL CHANGE: upstream picks these from the system light/dark setting and
    // fills the capsule at 40% opacity, which made this bar read as a solid
    // white slab next to the other glass on screen. They are parameters now, and
    // this app passes a much lighter film so the bar is the same material as
    // everything else. Upstream values kept as the defaults.
    accentColor: Color = Color(0xFF0091FF),
    containerColor: Color = Color(0xFF121212).copy(0.4f),
    // LOCAL CHANGE: upstream pins the bar at 64dp. The player wants a slimmer
    // version of the same control, and copying the file to change one number
    // would leave two of them to keep in step.
    height: Dp = 64f.dp,
    // LOCAL CHANGE: how deep the capsule refracts what is behind it. Upstream's
    // 24dp is tuned for the 64dp bar; on a shorter one the bend coming down from
    // the top edge and the bend coming up from the bottom meet in the middle and
    // leave a hard horizontal seam across the glass. Keep it below half the
    // height.
    lensDepth: Dp = 24f.dp,
    // LOCAL CHANGE: hides the moving capsule without moving it.
    //
    // The bar always has a selected index — it is what the indicator is drawn
    // at — but the app has screens that are none of the tabs, and on those the
    // indicator claimed the app was somewhere it was not. Faded rather than
    // removed, so it comes back where it left and the drag target stays alive.
    indicatorVisible: Boolean = true,
    /**
     * LOCAL CHANGE: what the moving indicator is filled with.
     *
     * Upstream lightens the slot it marks — white at a tenth on a dark bar. The
     * reference this app is matched against does the opposite: it sinks the lit
     * slot into the bar, so the mark is darker than the glass around it. Null
     * keeps upstream's.
     */
    indicatorColor: Color? = null,
    drawContainer: Boolean = true,
    content: @Composable RowScope.() -> Unit
) {
    val isLightTheme = !isSystemInDarkTheme()

    val tabsBackdrop = rememberLayerBackdrop()
    val surfaceBackdrop = LocalLiquidBottomTabsSurfaceBackdrop.current

    // LOCAL CHANGE: the width is read where it is used, not in composition.
    //
    // Upstream measures itself with BoxWithConstraints, which composes its
    // content again for every width it is given. That is free for a bar that
    // stands still and ruinous for one that changes shape: as the bottom bar
    // folds, this group loses a little width on every frame, and every frame
    // recomposed all five tabs twice over (the row and its tinted copy), with
    // the page scrolling underneath. Nothing here needs the width before
    // layout: the drag, the lit slot and the highlight all ask for it when
    // they run.
    val widthPx = remember { mutableFloatStateOf(0f) }

    Box(
        modifier.onSizeChanged { widthPx.floatValue = it.width.toFloat() },
        contentAlignment = Alignment.CenterStart
    ) {
        val density = LocalDensity.current
        val tabWidth: () -> Float = remember(density, tabsCount) {
            { with(density) { (widthPx.floatValue - 8f.dp.toPx()) / tabsCount } }
        }

        val offsetAnimation = remember { Animatable(0f) }
        val panelOffset by remember(density) {
            derivedStateOf {
                val width = widthPx.floatValue
                val fraction = if (width > 0f) {
                    (offsetAnimation.value / width).fastCoerceIn(-1f, 1f)
                } else {
                    0f
                }
                with(density) {
                    4f.dp.toPx() * fraction.sign * EaseOut.transform(abs(fraction))
                }
            }
        }

        val isLtr = LocalLayoutDirection.current == LayoutDirection.Ltr
        val animationScope = rememberCoroutineScope()
        var currentIndex by remember(selectedTabIndex) {
            mutableIntStateOf(selectedTabIndex())
        }
        val dampedDragAnimation = remember(animationScope) {
            DampedDragAnimation(
                animationScope = animationScope,
                initialValue = selectedTabIndex().toFloat(),
                valueRange = 0f..(tabsCount - 1).toFloat(),
                visibilityThreshold = 0.001f,
                initialScale = 1f,
                pressedScale = 78f / 56f,
                onDragStarted = {},
                onDragStopped = {
                    val targetIndex = targetValue.fastRoundToInt().fastCoerceIn(0, tabsCount - 1)
                    // LOCAL CHANGE: report a press that lands on the tab that is
                    // already selected.
                    //
                    // Selection is reported by watching `currentIndex` change,
                    // so releasing on the current tab reported nothing at all.
                    // On a screen that is not a tab — a playlist, the settings,
                    // search — the bar still shows one of them as selected, and
                    // that is exactly the tab you press to get back to it. The
                    // press animated and then did nothing.
                    if (targetIndex == currentIndex) onTabSelected(targetIndex)
                    currentIndex = targetIndex
                    animateToValue(targetIndex.toFloat())
                    animationScope.launch {
                        offsetAnimation.animateTo(
                            0f,
                            spring(1f, 300f, 0.5f)
                        )
                    }
                },
                onDrag = { _, dragAmount ->
                    updateValue(
                        (targetValue + dragAmount.x / tabWidth() * if (isLtr) 1f else -1f)
                            .fastCoerceIn(0f, (tabsCount - 1).toFloat())
                    )
                    animationScope.launch {
                        offsetAnimation.snapTo(offsetAnimation.value + dragAmount.x)
                    }
                }
            )
        }
        LaunchedEffect(selectedTabIndex) {
            snapshotFlow { selectedTabIndex() }
                .collectLatest { index ->
                    currentIndex = index
                }
        }
        LaunchedEffect(dampedDragAnimation) {
            snapshotFlow { currentIndex }
                .drop(1)
                .collectLatest { index ->
                    dampedDragAnimation.animateToValue(index.toFloat())
                    onTabSelected(index)
                }
        }

        val interactiveHighlight = remember(animationScope) {
            InteractiveHighlight(
                animationScope = animationScope,
                position = { size, offset ->
                    Offset(
                        if (isLtr) (dampedDragAnimation.value + 0.5f) * tabWidth() + panelOffset
                        else size.width - (dampedDragAnimation.value + 0.5f) * tabWidth() + panelOffset,
                        size.height / 2f
                    )
                }
            )
        }

        Row(
            Modifier
                .graphicsLayer {
                    translationX = panelOffset
                }
                // LOCAL CHANGE: the shell is made of the app's glass, like every
                // other pane. The puck below keeps its own recipe on purpose —
                // what it does is press-driven, a bend and a rim that only exist
                // while a finger is on it, which is not a material.
                .then(if (drawContainer) Modifier.liquidGlass(
                    config = LocalGlassEffectConfig.current,
                    shape = ContinuousCapsule(),
                    // Follows the setting like everything else; the shell of a
                    // panel switcher is not a different material from the bar.
                    blurRadiusDp = LocalGlassEffectConfig.current.blurRadius,
                    ownBackdrop = backdrop,
                    layerBlock = {
                        val progress = dampedDragAnimation.pressProgress
                        val scale = lerp(1f, 1f + 16f.dp.toPx() / size.width, progress)
                        scaleX = scale
                        scaleY = scale
                    },
                ) else Modifier)
                // Clip the row's rectangular touch glow, not its selector siblings.
                .clip(ContinuousCapsule())
                .then(interactiveHighlight.modifier)
                .height(height)
                .fillMaxWidth()
                .padding(4f.dp),
            verticalAlignment = Alignment.CenterVertically,
            content = content
        )

        CompositionLocalProvider(
            LocalLiquidBottomTabsReplica provides true,
            LocalLiquidBottomTabScale provides {
                lerp(1f, 1.2f, dampedDragAnimation.pressProgress)
            }
        ) {
            // LOCAL CHANGE: only the tabs, tinted, on nothing.
            //
            // This copy used to carry the page and the bar's film under the
            // tabs, and the lit slot drew all of it through itself and then laid
            // its own wash on top. The wash is what makes the slot, and on top
            // it darkened the one tab that has to stand out: at the dark side's
            // strength a white tab came out a flat mid grey. The page now comes
            // through the slot on its own, and this is drawn over the wash; see
            // the two layers below.
            Row(
                Modifier
                    .clearAndSetSemantics {}
                    .alpha(0f)
                    .layerBackdrop(tabsBackdrop)
                    .graphicsLayer {
                        translationX = panelOffset
                    }
                    .height(height - 8f.dp)
                    .fillMaxWidth()
                    .padding(horizontal = 4f.dp)
                    .graphicsLayer(colorFilter = ColorFilter.tint(accentColor)),
                verticalAlignment = Alignment.CenterVertically,
                content = content
            )
        }

        val indicatorAlpha by animateFloatAsState(
            targetValue = if (indicatorVisible) 1f else 0f,
            animationSpec = tween(220),
            label = "indicatorAlpha",
        )

        // Where the slot is and how it is bent, shared by its two layers so
        // they move and stretch as one.
        val slotPlacement = Modifier
            .padding(horizontal = 4f.dp)
            .graphicsLayer {
                alpha = indicatorAlpha
                translationX =
                    if (isLtr) dampedDragAnimation.value * tabWidth() + panelOffset
                    else size.width - (dampedDragAnimation.value + 1f) * tabWidth() + panelOffset
            }
        // Grow the sampling surface itself, rather than scaling a capture of
        // the resting slot. Both selector layers keep the same centre and read
        // the page at their actual expanded bounds.
        val slotGrowth = Modifier.layout { measurable, constraints ->
            val velocity = dampedDragAnimation.velocity / 10f
            val scaleX = dampedDragAnimation.scaleX /
                (1f - (velocity * 0.75f).fastCoerceIn(-0.2f, 0.2f))
            val scaleY = dampedDragAnimation.scaleY *
                (1f - (velocity * 0.25f).fastCoerceIn(-0.2f, 0.2f))
            val width = constraints.maxWidth
            val height = constraints.maxHeight
            val expandedWidth = (width * scaleX).roundToInt().coerceAtLeast(1)
            val expandedHeight = (height * scaleY).roundToInt().coerceAtLeast(1)
            val child = measurable.measure(Constraints.fixed(expandedWidth, expandedHeight))
            layout(width, height) {
                child.placeRelative((width - expandedWidth) / 2, (height - expandedHeight) / 2)
            }
        }
        val dispersion = LocalGlassEffectConfig.current.chromaticAberration
        val slotLens: BackdropEffectScope.() -> Unit = {
            val progress = dampedDragAnimation.pressProgress
            lens(
                10f.dp.toPx() * progress,
                14f.dp.toPx() * progress,
                // LOCAL CHANGE: follows the colour-splitting switch (#133).
                chromaticAberration = dispersion
            )
        }

        val pressedBackdrop = remember(backdrop, surfaceBackdrop, dampedDragAnimation) {
            object : Backdrop {
                private val surfacePaint = androidx.compose.ui.graphics.Paint()
                override val isCoordinatesDependent = true
                override fun androidx.compose.ui.graphics.drawscope.DrawScope.drawBackdrop(
                    density: androidx.compose.ui.unit.Density,
                    coordinates: androidx.compose.ui.layout.LayoutCoordinates?,
                    layerBlock: (GraphicsLayerScope.() -> Unit)?,
                ) {
                    // Fade the actual shell in and out continuously. Selecting
                    // it until progress reaches exactly zero stacked two films
                    // on release, then removed one abruptly: a white flash.
                    with(backdrop) { drawBackdrop(density, coordinates, layerBlock) }
                    val progress = dampedDragAnimation.pressProgress.coerceIn(0f, 1f)
                    if (surfaceBackdrop != null && progress > 0f) {
                        surfacePaint.alpha = progress
                        val canvas = drawContext.canvas
                        canvas.saveLayer(androidx.compose.ui.geometry.Rect(0f, 0f, size.width, size.height), surfacePaint)
                        try {
                            with(surfaceBackdrop) { drawBackdrop(density, coordinates, layerBlock) }
                        } finally {
                            canvas.restore()
                        }
                    }
                }
            }
        }

        // The slot: the page through it, frosted and filmed the way the tabs'
        // copy used to bring it, then the wash, the rim and the shadow.
        Box(
            slotPlacement
                .then(interactiveHighlight.gestureModifier)
                .then(dampedDragAnimation.modifier)
                .height(height - 8f.dp)
                .fillMaxWidth(1f / tabsCount)
                .then(slotGrowth)
                .drawBackdrop(
                    backdrop = pressedBackdrop,
                    shape = { ContinuousCapsule() },
                    effects = {
                        // At rest the slot is frosted like the bar under it:
                        // upstream's resting pill sits on the bar's glass and
                        // lets it show through, where this slot draws the
                        // page itself, and drawn clear it let the page
                        // straight through the bar. The frost lifts as it is
                        // pressed, down to upstream's clear lens.
                        vibrancy()
                        blur(8f.dp.toPx() * (1f - dampedDragAnimation.pressProgress.coerceIn(0f, 1f)))
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                            // LOCAL CHANGE: liquid_glass_widgets' indicator
                            // glass, coming in with the press.
                            liquidGlassIndicator(dampedDragAnimation.pressProgress)
                        } else {
                            slotLens()
                        }
                    },
                    highlight = {
                        val progress = dampedDragAnimation.pressProgress
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop null
                        Highlight.Default.copy(alpha = progress)
                    },
                    shadow = {
                        val progress = dampedDragAnimation.pressProgress
                        Shadow(alpha = progress)
                    },
                    innerShadow = {
                        val progress = dampedDragAnimation.pressProgress
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop null
                        InnerShadow(
                            radius = 8f.dp * progress,
                            alpha = progress
                        )
                    },
                    onDrawSurface = {
                        val progress = dampedDragAnimation.pressProgress
                        // Upstream's resting pill fades over the first 0.15
                        // of the press, as its glass comes in.
                        val resting = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                            dev.lelonio.square.ui.glass.morph.indicatorRestingAlpha(progress)
                        } else {
                            1f - progress
                        }
                        drawRect(containerColor, alpha = resting)
                        drawRect(
                            indicatorColor ?: if (isLightTheme) Color.Black.copy(0.1f)
                            else Color.White.copy(0.1f),
                            alpha = resting
                        )
                        drawRect(Color.Black.copy(alpha = 0.03f * progress))
                    }
                )
        )

        // LOCAL CHANGE: the lit tab, over its slot rather than under the wash.
        //
        // Bent by the same lens and stretched by the same drag, so while a
        // finger is on the bar it still reads as one piece of glass; no rim or
        // shadow of its own, those belong to the slot. Nothing takes touches
        // here, so the slot underneath still gets them.
        Box(
            slotPlacement
                .height(height - 8f.dp)
                .fillMaxWidth(1f / tabsCount)
                .then(slotGrowth)
                .drawBackdrop(
                    backdrop = tabsBackdrop,
                    shape = { ContinuousCapsule() },
                    effects = slotLens,
                    highlight = null,
                    shadow = null,
                )
        )
    }
}