Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
// 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.foundation.background
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
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.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChanged
import androidx.compose.ui.layout.layout
import androidx.compose.ui.zIndex
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.DpSize
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.rememberBackdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberCombinedBackdrop
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.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
@Composable
fun LiquidSlider(
value: () -> Float,
onValueChange: (Float) -> Unit,
valueRange: ClosedFloatingPointRange<Float>,
visibilityThreshold: Float,
backdrop: Backdrop,
modifier: Modifier = Modifier,
// LOCAL CHANGE: upstream hardcodes an iOS blue. This app tints from the
// current cover, so the colours are parameters with the upstream values as
// defaults.
accentColor: Color = Color(0xFF0091FF),
trackColor: Color = Color(0xFF787880).copy(0.36f),
// LOCAL CHANGE: told once, when the finger lifts. For a slider whose every
// value is expensive to apply — a seek — and that wants only the last one.
onValueChangeFinished: () -> Unit = {},
// LOCAL CHANGE: upstream's thumb is a 40 by 24 capsule. Equal sides make it
// a circle, which is what the playback position wants.
thumbSize: DpSize = DpSize(40f.dp, 24f.dp),
// LOCAL CHANGE: the thumb's scale at rest and while held, upstream's as
// defaults. A thumb meant to sit small is drawn at its held size and scaled
// down, rather than drawn small: the lens is sized in dp, and a lens near
// half the pane it sits in is what hangs the refraction shader.
thumbRestScale: Float = 1f,
thumbPressedScale: Float = 1.5f,
) {
val trackBackdrop = rememberLayerBackdrop()
val dispersion = LocalGlassEffectConfig.current.chromaticAberration
BoxWithConstraints(
modifier.fillMaxWidth(),
contentAlignment = Alignment.CenterStart
) {
val trackWidth = constraints.maxWidth
val isLtr = LocalLayoutDirection.current == LayoutDirection.Ltr
// LOCAL CHANGE: read through this, never the parameter. The animation
// and the gesture handler below are made once and outlive the
// composition that made them, so the callback they closed over was the
// first one — and that one had closed over whatever the caller knew
// then. The effects panel builds speed and pitch as a pair, so moving
// one sent the other as it was when the panel opened, and a pitch set
// a moment ago sprang back to a value nobody had chosen.
val latestOnValueChange by rememberUpdatedState(onValueChange)
val latestOnFinished by rememberUpdatedState(onValueChangeFinished)
// LOCAL CHANGE: the value too, for the same reason. The effect below
// is started once, and it went on reading the first lambda it was
// given: a progress bar whose song turned into its video kept drawing
// the thumb against the song's length, well past where the video was.
val latestValue by rememberUpdatedState(value)
val animationScope = rememberCoroutineScope()
var didDrag by remember { mutableStateOf(false) }
val dampedDragAnimation = remember(animationScope) {
DampedDragAnimation(
animationScope = animationScope,
initialValue = value(),
valueRange = valueRange,
visibilityThreshold = visibilityThreshold,
initialScale = thumbRestScale,
pressedScale = thumbPressedScale,
onDragStarted = {},
onDragStopped = {
if (didDrag) {
didDrag = false
latestOnValueChange(targetValue)
}
},
onDrag = { _, dragAmount ->
if (!didDrag) {
didDrag = dragAmount.x != 0f
}
val delta = (valueRange.endInclusive - valueRange.start) * (dragAmount.x / trackWidth)
latestOnValueChange(
if (isLtr) (targetValue + delta).coerceIn(valueRange)
else (targetValue - delta).coerceIn(valueRange)
)
}
)
}
LaunchedEffect(dampedDragAnimation) {
snapshotFlow { latestValue() }
.collectLatest { value ->
if (dampedDragAnimation.targetValue != value) {
dampedDragAnimation.updateValue(value)
}
}
}
// LOCAL CHANGE, not upstream: one gesture handler over the whole slider.
//
// Upstream drags only from the thumb, and its detector never consumes
// the pointer, so in this app a press that landed on the thumb was
// picked up by nothing and the thumb sat still — while a press on the
// bare track worked. One handler on the root, mapping the finger's
// absolute position and consuming, removes the distinction: grabbing
// anywhere jumps there and then tracks, thumb included.
//
// It has to drive the press state as well, and that is the part that
// was missing. Every glass effect on the thumb, the lens, the
// aberration, the inner shadow and the swell, is a function of
// `pressProgress`, which upstream raises from its own detector on the
// thumb. Taking the pointer away from that detector took the animation
// with it: the thumb tracked the finger as a flat capsule and the
// material never reacted at all.
//
// From the first down rather than from the drag: a slider that only
// comes alive once the finger has travelled the touch slop feels like
// it noticed late.
Box(
Modifier
.matchParentSize()
.pointerInput(animationScope, trackWidth) {
fun seekTo(x: Float) {
// Nothing to divide by before the track has been
// measured, and the answer if you try is an enormous
// number that clamps to the end of the range — a value
// the user never asked for, written to wherever this
// slider stores itself.
if (trackWidth <= 0) return
val delta =
(valueRange.endInclusive - valueRange.start) * (x / trackWidth)
val target =
(if (isLtr) valueRange.start + delta
else valueRange.endInclusive - delta)
.coerceIn(valueRange)
dampedDragAnimation.updateValue(target)
latestOnValueChange(target)
}
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
dampedDragAnimation.press()
down.consume()
seekTo(down.position.x)
try {
while (true) {
val change = awaitPointerEvent().changes
.firstOrNull { it.id == down.id }
?: break
if (!change.pressed) break
if (change.positionChanged()) {
change.consume()
seekTo(change.position.x)
}
}
} finally {
// Also on a cancelled gesture: a thumb left swollen
// and lensed after the finger is gone reads as the
// control being stuck mid-drag.
dampedDragAnimation.release()
latestOnFinished()
}
}
}
// Drawn above the thumb so it sees the press first, but with no
// content of its own.
.zIndex(1f),
)
Box(Modifier.layerBackdrop(trackBackdrop)) {
Box(
Modifier
.clip(ContinuousCapsule())
.background(trackColor)
.pointerInput(animationScope) {
detectTapGestures { position ->
val delta = (valueRange.endInclusive - valueRange.start) * (position.x / trackWidth)
val targetValue =
(if (isLtr) valueRange.start + delta
else valueRange.endInclusive - delta)
.coerceIn(valueRange)
dampedDragAnimation.animateToValue(targetValue)
latestOnValueChange(targetValue)
latestOnFinished()
}
}
.height(6f.dp)
.fillMaxWidth()
)
Box(
Modifier
.clip(ContinuousCapsule())
.background(accentColor)
.height(6f.dp)
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
val width = (constraints.maxWidth * dampedDragAnimation.progress).fastRoundToInt()
layout(width, placeable.height) {
placeable.place(0, 0)
}
}
)
}
Box(
Modifier
.graphicsLayer {
translationX =
(-size.width / 2f + trackWidth * dampedDragAnimation.progress)
.fastCoerceIn(-size.width / 4f, trackWidth - size.width * 3f / 4f) * if (isLtr) 1f else -1f
}
.then(dampedDragAnimation.modifier)
.drawBackdrop(
backdrop = rememberCombinedBackdrop(
backdrop,
rememberBackdrop(trackBackdrop) { drawBackdrop ->
val progress = dampedDragAnimation.pressProgress
val scaleX = lerp(2f / 3f, 1f, progress)
val scaleY = lerp(0f, 1f, progress)
scale(scaleX, scaleY) {
drawBackdrop()
}
}
),
shape = { ContinuousCapsule() },
effects = {
val progress = dampedDragAnimation.pressProgress
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; see
// liquidGlassIndicator.
liquidGlassIndicator(progress)
} else {
blur(8f.dp.toPx() * (1f - progress))
lens(
10f.dp.toPx() * progress,
14f.dp.toPx() * progress,
// LOCAL CHANGE: follows the colour-splitting
// switch, as every other pane does (#147).
chromaticAberration = dispersion
)
}
},
highlight = {
val progress = dampedDragAnimation.pressProgress
// Upstream's glass lights its own edge.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop null
Highlight.Ambient.copy(
width = Highlight.Ambient.width / 1.5f,
blurRadius = Highlight.Ambient.blurRadius / 1.5f,
alpha = progress
)
},
shadow = {
Shadow(
radius = 4f.dp,
color = Color.Black.copy(alpha = 0.05f)
)
},
innerShadow = {
val progress = dampedDragAnimation.pressProgress
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop null
InnerShadow(
radius = 4f.dp * progress,
alpha = progress
)
},
layerBlock = {
scaleX = dampedDragAnimation.scaleX
scaleY = dampedDragAnimation.scaleY
val velocity = dampedDragAnimation.velocity / 10f
scaleX /= 1f - (velocity * 0.75f).fastCoerceIn(-0.2f, 0.2f)
scaleY *= 1f - (velocity * 0.25f).fastCoerceIn(-0.2f, 0.2f)
},
onDrawSurface = {
val progress = dampedDragAnimation.pressProgress
// Upstream's resting thumb 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(Color.White.copy(alpha = resting))
}
)
// Required rather than asked for: a thumb taller than the
// slider it sits on keeps its size and overhangs the track.
.requiredSize(thumbSize)
)
}
}