1
0

chore: initial commit

Signed-off-by: Alan Brault <alan.brault@visus.io>
This commit is contained in:
2025-11-17 08:02:58 -05:00
commit 3346eecb52
77 changed files with 4246 additions and 0 deletions

1
lib/solanim-ui/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

View File

@@ -0,0 +1,56 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.lumo.ui)
}
android {
namespace = "io.visus.solanim.ui"
compileSdk {
version = release(36)
}
defaultConfig {
minSdk = 35
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
api(platform(libs.androidx.compose.bom))
api(libs.androidx.compose.foundation)
api(libs.androidx.compose.foundation.layout)
api(libs.androidx.compose.material.ripple)
api(libs.androidx.compose.ui)
api(libs.androidx.compose.ui.graphics)
api(libs.androidx.compose.ui.util)
api(libs.androidx.ui.tooling)
api(libs.androidx.ui.tooling.preview)
api(libs.composables)
api(libs.colorpicker.compose)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
}

View File

21
lib/solanim-ui/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,24 @@
package io.visus.solanim.ui
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("io.visus.solanim.ui.test", appContext.packageName)
}
}

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
</manifest>

View File

@@ -0,0 +1,141 @@
package io.visus.solanim.ui
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
val Black: Color = Color(0xFF000000)
val Gray900: Color = Color(0xFF282828)
val Gray800: Color = Color(0xFF4b4b4b)
val Gray700: Color = Color(0xFF5e5e5e)
val Gray600: Color = Color(0xFF727272)
val Gray500: Color = Color(0xFF868686)
val Gray400: Color = Color(0xFFC7C7C7)
val Gray300: Color = Color(0xFFDFDFDF)
val Gray200: Color = Color(0xFFE2E2E2)
val Gray100: Color = Color(0xFFF7F7F7)
val Gray50: Color = Color(0xFFFFFFFF)
val White: Color = Color(0xFFFFFFFF)
val Red900: Color = Color(0xFF520810)
val Red800: Color = Color(0xFF950f22)
val Red700: Color = Color(0xFFbb032a)
val Red600: Color = Color(0xFFde1135)
val Red500: Color = Color(0xFFf83446)
val Red400: Color = Color(0xFFfc7f79)
val Red300: Color = Color(0xFFffb2ab)
val Red200: Color = Color(0xFFffd2cd)
val Red100: Color = Color(0xFFffe1de)
val Red50: Color = Color(0xFFfff0ee)
val Blue900: Color = Color(0xFF276EF1)
val Blue800: Color = Color(0xFF3F7EF2)
val Blue700: Color = Color(0xFF578EF4)
val Blue600: Color = Color(0xFF6F9EF5)
val Blue500: Color = Color(0xFF87AEF7)
val Blue400: Color = Color(0xFF9FBFF8)
val Blue300: Color = Color(0xFFB7CEFA)
val Blue200: Color = Color(0xFFCFDEFB)
val Blue100: Color = Color(0xFFE7EEFD)
val Blue50: Color = Color(0xFFFFFFFF)
val Green950: Color = Color(0xFF0B4627)
val Green900: Color = Color(0xFF16643B)
val Green800: Color = Color(0xFF1A7544)
val Green700: Color = Color(0xFF178C4E)
val Green600: Color = Color(0xFF1DAF61)
val Green500: Color = Color(0xFF1FC16B)
val Green400: Color = Color(0xFF3EE089)
val Green300: Color = Color(0xFF84EBB4)
val Green200: Color = Color(0xFFC2F5DA)
val Green100: Color = Color(0xFFD0FBE9)
val Green50: Color = Color(0xFFE0FAEC)
val NavyBlue900: Color = Color(0xFF00002E)
val NavyBlue800: Color = Color(0xFF1A1A47)
@Immutable
data class Colors(
val primary: Color,
val onPrimary: Color,
val secondary: Color,
val onSecondary: Color,
val tertiary: Color,
val onTertiary: Color,
val error: Color,
val onError: Color,
val success: Color,
val onSuccess: Color,
val disabled: Color,
val onDisabled: Color,
val surface: Color,
val onSurface: Color,
val background: Color,
val onBackground: Color,
val outline: Color,
val transparent: Color = Color.Transparent,
val white: Color = White,
val black: Color = Black,
val text: Color,
val textSecondary: Color,
val textDisabled: Color,
val scrim: Color,
val elevation: Color,
val defaultBackgroundGradient: Brush,
)
internal val DarkColors =
Colors(
primary = White,
onPrimary = Black,
secondary = Gray400,
onSecondary = White,
tertiary = Blue300,
onTertiary = Black,
surface = Gray900,
onSurface = White,
error = Red400,
onError = Black,
success = Green700,
onSuccess = Black,
disabled = Gray700,
onDisabled = Gray500,
background = Black,
onBackground = White,
outline = Gray800,
transparent = Color.Transparent,
white = White,
black = Black,
text = White,
textSecondary = Gray300,
textDisabled = Gray600,
scrim = Color.Black.copy(alpha = 0.72f),
elevation = Gray200,
defaultBackgroundGradient = Brush.verticalGradient(
colors = listOf(
NavyBlue800,
NavyBlue900,
Black,
)
)
)
val LocalColors = staticCompositionLocalOf { DarkColors }
val LocalContentColor = compositionLocalOf { Color.Black }
val LocalContentAlpha = compositionLocalOf { 1f }
fun Colors.contentColorFor(backgroundColor: Color): Color {
return when (backgroundColor) {
primary -> onPrimary
secondary -> onSecondary
tertiary -> onTertiary
surface -> onSurface
error -> onError
success -> onSuccess
disabled -> onDisabled
background -> onBackground
else -> Color.Unspecified
}
}

View File

@@ -0,0 +1,59 @@
package io.visus.solanim.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.text.selection.LocalTextSelectionColors
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import io.visus.solanim.ui.foundation.ripple
object AppTheme {
val colors: Colors
@ReadOnlyComposable @Composable
get() = LocalColors.current
val typography: Typography
@ReadOnlyComposable @Composable
get() = LocalTypography.current
}
@Composable
fun AppTheme(
content: @Composable () -> Unit,
) {
val rippleIndication = ripple()
val selectionColors = rememberTextSelectionColors(DarkColors)
val typography = provideTypography()
CompositionLocalProvider(
LocalColors provides DarkColors,
LocalTypography provides typography,
LocalIndication provides rippleIndication,
LocalTextSelectionColors provides selectionColors,
LocalContentColor provides DarkColors.contentColorFor(DarkColors.background),
LocalTextStyle provides typography.body1,
content = content,
)
}
@Composable
fun contentColorFor(color: Color): Color {
return AppTheme.colors.contentColorFor(color)
}
@Composable
internal fun rememberTextSelectionColors(colorScheme: Colors): TextSelectionColors {
val primaryColor = colorScheme.primary
return remember(primaryColor) {
TextSelectionColors(
handleColor = primaryColor,
backgroundColor = primaryColor.copy(alpha = TextSelectionBackgroundOpacity),
)
}
}
internal const val TextSelectionBackgroundOpacity = 0.4f

View File

@@ -0,0 +1,139 @@
package io.visus.solanim.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.structuralEqualityPolicy
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
@Composable
fun fontFamily() = FontFamily.Default
data class Typography(
val h1: TextStyle,
val h2: TextStyle,
val h3: TextStyle,
val h4: TextStyle,
val body1: TextStyle,
val body2: TextStyle,
val body3: TextStyle,
val label1: TextStyle,
val label2: TextStyle,
val label3: TextStyle,
val button: TextStyle,
val input: TextStyle,
)
private val defaultTypography =
Typography(
h1 =
TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
lineHeight = 32.sp,
letterSpacing = 0.sp,
),
h2 =
TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp,
),
h3 =
TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.sp,
),
h4 =
TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.sp,
),
body1 =
TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.sp,
),
body2 =
TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.15.sp,
),
body3 =
TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.15.sp,
),
label1 =
TextStyle(
fontWeight = FontWeight.W500,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.1.sp,
),
label2 =
TextStyle(
fontWeight = FontWeight.W500,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp,
),
label3 =
TextStyle(
fontWeight = FontWeight.W500,
fontSize = 10.sp,
lineHeight = 12.sp,
letterSpacing = 0.5.sp,
),
button =
TextStyle(
fontWeight = FontWeight.W500,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 1.sp,
),
input =
TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.sp,
),
)
@Composable
fun provideTypography(): Typography {
val fontFamily = fontFamily()
return defaultTypography.copy(
h1 = defaultTypography.h1.copy(fontFamily = fontFamily),
h2 = defaultTypography.h2.copy(fontFamily = fontFamily),
h3 = defaultTypography.h3.copy(fontFamily = fontFamily),
h4 = defaultTypography.h4.copy(fontFamily = fontFamily),
body1 = defaultTypography.body1.copy(fontFamily = fontFamily),
body2 = defaultTypography.body2.copy(fontFamily = fontFamily),
body3 = defaultTypography.body3.copy(fontFamily = fontFamily),
label1 = defaultTypography.label1.copy(fontFamily = fontFamily),
label2 = defaultTypography.label2.copy(fontFamily = fontFamily),
label3 = defaultTypography.label3.copy(fontFamily = fontFamily),
button = defaultTypography.button.copy(fontFamily = fontFamily),
input = defaultTypography.input.copy(fontFamily = fontFamily),
)
}
val LocalTypography = staticCompositionLocalOf { defaultTypography }
val LocalTextStyle = compositionLocalOf(structuralEqualityPolicy()) { TextStyle.Default }

View File

@@ -0,0 +1,98 @@
package io.visus.solanim.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.toolingGraphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import io.visus.solanim.ui.LocalContentColor
@Composable
fun Icon(
imageVector: ImageVector,
modifier: Modifier = Modifier,
contentDescription: String? = null,
tint: Color = LocalContentColor.current,
) {
Icon(
painter = rememberVectorPainter(imageVector),
contentDescription = contentDescription,
modifier = modifier,
tint = tint,
)
}
@Composable
fun Icon(
bitmap: ImageBitmap,
modifier: Modifier = Modifier,
contentDescription: String? = null,
tint: Color = LocalContentColor.current,
) {
val painter = remember(bitmap) { BitmapPainter(bitmap) }
Icon(
painter = painter,
contentDescription = contentDescription,
modifier = modifier,
tint = tint,
)
}
@Composable
fun Icon(
painter: Painter,
modifier: Modifier = Modifier,
contentDescription: String? = null,
tint: Color = LocalContentColor.current,
) {
val colorFilter = if (tint == Color.Unspecified) null else ColorFilter.tint(tint)
val semantics =
if (contentDescription != null) {
Modifier.semantics {
this.contentDescription = contentDescription
this.role = Role.Image
}
} else {
Modifier
}
Box(
modifier
.toolingGraphicsLayer()
.defaultSizeFor(painter)
.paint(painter, colorFilter = colorFilter, contentScale = ContentScale.Fit)
.then(semantics),
)
}
private fun Modifier.defaultSizeFor(painter: Painter) =
this.then(
if (painter.intrinsicSize == Size.Unspecified || painter.intrinsicSize.isInfinite()) {
DefaultIconSizeModifier
} else {
Modifier
},
)
private fun Size.isInfinite() = width.isInfinite() && height.isInfinite()
private val DefaultIconSizeModifier = Modifier.size(IconDefaults.iconSize)
internal object IconDefaults {
val iconSize = 24.dp
}

View File

@@ -0,0 +1,265 @@
package io.visus.solanim.ui.components
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.SubcomposeLayout
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.offset
import io.visus.solanim.ui.AppTheme
import io.visus.solanim.ui.contentColorFor
import io.visus.solanim.ui.foundation.systemBarsForVisualComponents
import kotlin.jvm.JvmInline
@Composable
fun Scaffold(
modifier: Modifier = Modifier,
topBar: @Composable () -> Unit = {},
bottomBar: @Composable () -> Unit = {},
snackbarHost: @Composable () -> Unit = {},
floatingActionButton: @Composable () -> Unit = {},
floatingActionButtonPosition: FabPosition = FabPosition.End,
containerColor: Color = AppTheme.colors.background,
contentColor: Color = contentColorFor(containerColor),
contentWindowInsets: WindowInsets = ScaffoldDefaults.contentWindowInsets,
content: @Composable (PaddingValues) -> Unit,
) {
Surface(modifier = modifier, color = containerColor, contentColor = contentColor) {
ScaffoldLayout(
fabPosition = floatingActionButtonPosition,
topBar = topBar,
bottomBar = bottomBar,
content = content,
snackbar = snackbarHost,
contentWindowInsets = contentWindowInsets,
fab = floatingActionButton,
)
}
}
@Composable
private fun ScaffoldLayout(
fabPosition: FabPosition,
topBar: @Composable () -> Unit,
content: @Composable (PaddingValues) -> Unit,
snackbar: @Composable () -> Unit,
fab: @Composable () -> Unit,
contentWindowInsets: WindowInsets,
bottomBar: @Composable () -> Unit,
) {
SubcomposeLayout { constraints ->
val layoutWidth = constraints.maxWidth
val layoutHeight = constraints.maxHeight
val looseConstraints = constraints.copy(minWidth = 0, minHeight = 0)
layout(layoutWidth, layoutHeight) {
val topBarPlaceables =
subcompose(ScaffoldLayoutContent.TopBar, topBar).map {
it.measure(looseConstraints)
}
val topBarHeight = topBarPlaceables.maxByOrNull { it.height }?.height ?: 0
val snackbarPlaceables =
subcompose(ScaffoldLayoutContent.Snackbar, snackbar).map {
// respect only bottom and horizontal for snackbar and fab
val leftInset =
contentWindowInsets
.getLeft(this@SubcomposeLayout, layoutDirection)
val rightInset =
contentWindowInsets
.getRight(this@SubcomposeLayout, layoutDirection)
val bottomInset = contentWindowInsets.getBottom(this@SubcomposeLayout)
// offset the snackbar constraints by the insets values
it.measure(
looseConstraints.offset(
-leftInset - rightInset,
-bottomInset,
),
)
}
val snackbarHeight = snackbarPlaceables.maxByOrNull { it.height }?.height ?: 0
val snackbarWidth = snackbarPlaceables.maxByOrNull { it.width }?.width ?: 0
val fabPlaceables =
subcompose(ScaffoldLayoutContent.Fab, fab).mapNotNull { measurable ->
// respect only bottom and horizontal for snackbar and fab
val leftInset =
contentWindowInsets.getLeft(
this@SubcomposeLayout,
layoutDirection,
)
val rightInset =
contentWindowInsets.getRight(
this@SubcomposeLayout,
layoutDirection,
)
val bottomInset = contentWindowInsets.getBottom(this@SubcomposeLayout)
measurable.measure(
looseConstraints.offset(
-leftInset - rightInset,
-bottomInset,
),
)
.takeIf { it.height != 0 && it.width != 0 }
}
val fabPlacement =
if (fabPlaceables.isNotEmpty()) {
val fabWidth = fabPlaceables.maxByOrNull { it.width }!!.width
val fabHeight = fabPlaceables.maxByOrNull { it.height }!!.height
// FAB distance from the left of the layout, taking into account LTR / RTL
val fabLeftOffset =
if (fabPosition == FabPosition.End) {
if (layoutDirection == LayoutDirection.Ltr) {
layoutWidth - FabSpacing.roundToPx() - fabWidth
} else {
FabSpacing.roundToPx()
}
} else {
(layoutWidth - fabWidth) / 2
}
FabPlacement(
left = fabLeftOffset,
width = fabWidth,
height = fabHeight,
)
} else {
null
}
val bottomBarPlaceables =
subcompose(ScaffoldLayoutContent.BottomBar) {
CompositionLocalProvider(
LocalFabPlacement provides fabPlacement,
content = bottomBar,
)
}.map { it.measure(looseConstraints) }
val bottomBarHeight = bottomBarPlaceables.maxByOrNull { it.height }?.height
val fabOffsetFromBottom =
fabPlacement?.let {
if (bottomBarHeight == null) {
it.height + FabSpacing.roundToPx() +
contentWindowInsets.getBottom(this@SubcomposeLayout)
} else {
// Total height is the bottom bar height + the FAB height + the padding
// between the FAB and bottom bar
bottomBarHeight + it.height + FabSpacing.roundToPx()
}
}
val snackbarOffsetFromBottom =
if (snackbarHeight != 0) {
snackbarHeight +
(
fabOffsetFromBottom ?: bottomBarHeight
?: contentWindowInsets.getBottom(this@SubcomposeLayout)
)
} else {
0
}
val bodyContentPlaceables =
subcompose(ScaffoldLayoutContent.MainContent) {
val insets = contentWindowInsets.asPaddingValues(this@SubcomposeLayout)
val innerPadding =
PaddingValues(
top =
if (topBarPlaceables.isEmpty()) {
insets.calculateTopPadding()
} else {
topBarHeight.toDp()
},
bottom =
if (bottomBarPlaceables.isEmpty() || bottomBarHeight == null) {
insets.calculateBottomPadding()
} else {
bottomBarHeight.toDp()
},
start = insets.calculateStartPadding((this@SubcomposeLayout).layoutDirection),
end = insets.calculateEndPadding((this@SubcomposeLayout).layoutDirection),
)
content(innerPadding)
}.map { it.measure(looseConstraints) }
// Placing to control drawing order to match default elevation of each placeable
bodyContentPlaceables.forEach {
it.place(0, 0)
}
topBarPlaceables.forEach {
it.place(0, 0)
}
snackbarPlaceables.forEach {
it.place(
(layoutWidth - snackbarWidth) / 2 +
contentWindowInsets.getLeft(
this@SubcomposeLayout,
layoutDirection,
),
layoutHeight - snackbarOffsetFromBottom,
)
}
// The bottom bar is always at the bottom of the layout
bottomBarPlaceables.forEach {
it.place(0, layoutHeight - (bottomBarHeight ?: 0))
}
// Explicitly not using placeRelative here as `leftOffset` already accounts for RTL
fabPlacement?.let { placement ->
fabPlaceables.forEach {
it.place(placement.left, layoutHeight - fabOffsetFromBottom!!)
}
}
}
}
}
object ScaffoldDefaults {
val contentWindowInsets: WindowInsets
@Composable
get() = WindowInsets.systemBarsForVisualComponents
}
@JvmInline
value class FabPosition internal constructor(
@Suppress("unused") private val value: Int,
) {
companion object {
val Center = FabPosition(0)
val End = FabPosition(1)
}
override fun toString(): String {
return when (this) {
Center -> "FabPosition.Center"
else -> "FabPosition.End"
}
}
}
@Immutable
internal class FabPlacement(
val left: Int,
val width: Int,
val height: Int,
)
internal val LocalFabPlacement = staticCompositionLocalOf<FabPlacement?> { null }
private val FabSpacing = 16.dp
private enum class ScaffoldLayoutContent { TopBar, MainContent, Snackbar, Fab, BottomBar }

View File

@@ -0,0 +1,438 @@
package io.visus.solanim.ui.components
import androidx.annotation.IntRange
import androidx.compose.foundation.background
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.nomanr.composables.slider.BasicRangeSlider
import com.nomanr.composables.slider.BasicSlider
import com.nomanr.composables.slider.RangeSliderState
import com.nomanr.composables.slider.SliderColors
import com.nomanr.composables.slider.SliderState
import io.visus.solanim.ui.AppTheme
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun Slider(
value: Float,
onValueChange: (Float) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
onValueChangeFinished: (() -> Unit)? = null,
colors: SliderColors = SliderDefaults.colors(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
@IntRange(from = 0) steps: Int = 0,
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
) {
val state =
remember(steps, valueRange) {
SliderState(
value,
steps,
onValueChangeFinished,
valueRange,
)
}
state.onValueChangeFinished = onValueChangeFinished
state.onValueChange = onValueChange
state.value = value
Slider(
state = state,
modifier = modifier,
enabled = enabled,
interactionSource = interactionSource,
colors = colors,
)
}
@Composable
fun Slider(
state: SliderState,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: SliderColors = SliderDefaults.colors(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
require(state.steps >= 0) { "steps should be >= 0" }
BasicSlider(modifier = modifier, state = state, colors = colors, enabled = enabled, interactionSource = interactionSource)
}
@Composable
fun RangeSlider(
value: ClosedFloatingPointRange<Float>,
onValueChange: (ClosedFloatingPointRange<Float>) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
@IntRange(from = 0) steps: Int = 0,
onValueChangeFinished: (() -> Unit)? = null,
colors: SliderColors = SliderDefaults.colors(),
startInteractionSource: MutableInteractionSource = remember { MutableInteractionSource() },
endInteractionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
val state =
remember(steps, valueRange) {
RangeSliderState(
value.start,
value.endInclusive,
steps,
onValueChangeFinished,
valueRange,
)
}
state.onValueChangeFinished = onValueChangeFinished
state.onValueChange = { onValueChange(it.start..it.endInclusive) }
state.activeRangeStart = value.start
state.activeRangeEnd = value.endInclusive
RangeSlider(
state = state,
modifier = modifier,
enabled = enabled,
colors = colors,
startInteractionSource = startInteractionSource,
endInteractionSource = endInteractionSource,
)
}
@Composable
fun RangeSlider(
state: RangeSliderState,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: SliderColors = SliderDefaults.colors(),
startInteractionSource: MutableInteractionSource = remember { MutableInteractionSource() },
endInteractionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
require(state.steps >= 0) { "steps should be >= 0" }
BasicRangeSlider(
modifier = modifier,
state = state,
enabled = enabled,
startInteractionSource = startInteractionSource,
endInteractionSource = endInteractionSource,
colors = colors,
)
}
@Stable
object SliderDefaults {
@Composable
fun colors(
thumbColor: Color = AppTheme.colors.primary,
activeTrackColor: Color = AppTheme.colors.primary,
activeTickColor: Color = AppTheme.colors.onPrimary,
inactiveTrackColor: Color = AppTheme.colors.secondary,
inactiveTickColor: Color = AppTheme.colors.primary,
disabledThumbColor: Color = AppTheme.colors.disabled,
disabledActiveTrackColor: Color = AppTheme.colors.disabled,
disabledActiveTickColor: Color = AppTheme.colors.disabled,
disabledInactiveTrackColor: Color = AppTheme.colors.disabled,
disabledInactiveTickColor: Color = Color.Unspecified,
) = SliderColors(
thumbColor = thumbColor,
activeTrackColor = activeTrackColor,
activeTickColor = activeTickColor,
inactiveTrackColor = inactiveTrackColor,
inactiveTickColor = inactiveTickColor,
disabledThumbColor = disabledThumbColor,
disabledActiveTrackColor = disabledActiveTrackColor,
disabledActiveTickColor = disabledActiveTickColor,
disabledInactiveTrackColor = disabledInactiveTrackColor,
disabledInactiveTickColor = disabledInactiveTickColor,
)
}
@Preview
@Composable
private fun SliderPreview() {
AppTheme {
Column(
modifier =
Modifier
.background(Color.White)
.verticalScroll(rememberScrollState())
.padding(16.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(32.dp),
) {
BasicText(
text = "Slider Components",
style = AppTheme.typography.h3,
)
Column {
BasicText(
text = "Basic Slider",
style = AppTheme.typography.h4,
)
var value by remember { mutableFloatStateOf(0.5f) }
Slider(
value = value,
onValueChange = { value = it },
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Stepped Slider (5 steps)",
style = AppTheme.typography.h4,
)
var value by remember { mutableFloatStateOf(0.4f) }
Slider(
value = value,
onValueChange = { value = it },
steps = 4,
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Custom Range (0-100)",
style = AppTheme.typography.h4,
)
var value by remember { mutableFloatStateOf(30f) }
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Slider(
value = value,
onValueChange = { value = it },
valueRange = 0f..100f,
modifier = Modifier.weight(1f),
)
BasicText(
text = "${value.toInt()}",
style = AppTheme.typography.body1,
modifier = Modifier.width(40.dp),
)
}
}
Column {
BasicText(
text = "Disabled States",
style = AppTheme.typography.h4,
)
Slider(
value = 0.3f,
onValueChange = {},
enabled = false,
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(8.dp))
Slider(
value = 0.7f,
onValueChange = {},
enabled = false,
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Custom Colors",
style = AppTheme.typography.h4,
)
var value by remember { mutableFloatStateOf(0.5f) }
Slider(
value = value,
onValueChange = { value = it },
colors =
SliderDefaults.colors(
thumbColor = AppTheme.colors.error,
activeTrackColor = AppTheme.colors.error,
inactiveTrackColor = AppTheme.colors.error.copy(alpha = 0.3f),
),
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Interactive Slider",
style = AppTheme.typography.h4,
)
var value by remember { mutableFloatStateOf(50f) }
var isEditing by remember { mutableStateOf(false) }
BasicText(
text = if (isEditing) "Editing..." else "Value: ${value.toInt()}",
style = AppTheme.typography.body1,
)
Slider(
value = value,
onValueChange = {
value = it
isEditing = true
},
valueRange = 0f..100f,
onValueChangeFinished = { isEditing = false },
modifier = Modifier.fillMaxWidth(),
)
}
}
}
}
@Preview
@Composable
private fun RangeSliderPreview() {
AppTheme {
Column(
modifier =
Modifier
.background(Color.White)
.verticalScroll(rememberScrollState())
.padding(16.dp)
.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(32.dp),
) {
BasicText(
text = "Range Slider Components",
style = AppTheme.typography.h3,
)
Column {
BasicText(
text = "Basic Range Slider",
style = AppTheme.typography.h4,
)
var range by remember { mutableStateOf(0.2f..0.8f) }
RangeSlider(
value = range,
onValueChange = { range = it },
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Stepped Range Slider (5 steps)",
style = AppTheme.typography.h4,
)
var range by remember { mutableStateOf(0.2f..0.6f) }
RangeSlider(
value = range,
onValueChange = { range = it },
steps = 4,
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Custom Range (0-100)",
style = AppTheme.typography.h4,
)
var range by remember { mutableStateOf(20f..80f) }
Column {
RangeSlider(
value = range,
onValueChange = { range = it },
valueRange = 0f..100f,
modifier = Modifier.fillMaxWidth(),
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
BasicText(
text = "Start: ${range.start.toInt()}",
style = AppTheme.typography.body1,
)
BasicText(
text = "End: ${range.endInclusive.toInt()}",
style = AppTheme.typography.body1,
)
}
}
}
Column {
BasicText(
text = "Disabled State",
style = AppTheme.typography.h4,
)
RangeSlider(
value = 0.3f..0.7f,
onValueChange = {},
enabled = false,
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Custom Colors",
style = AppTheme.typography.h4,
)
var range by remember { mutableStateOf(0.3f..0.7f) }
RangeSlider(
value = range,
onValueChange = { range = it },
colors =
SliderDefaults.colors(
thumbColor = AppTheme.colors.error,
activeTrackColor = AppTheme.colors.error,
inactiveTrackColor = AppTheme.colors.error.copy(alpha = 0.3f),
),
modifier = Modifier.fillMaxWidth(),
)
}
Column {
BasicText(
text = "Interactive Range Slider",
style = AppTheme.typography.h4,
)
var range by remember { mutableStateOf(30f..70f) }
var isEditing by remember { mutableStateOf(false) }
BasicText(
text = if (isEditing) "Editing..." else "Range: ${range.start.toInt()} - ${range.endInclusive.toInt()}",
style = AppTheme.typography.body1,
)
RangeSlider(
value = range,
onValueChange = {
range = it
isEditing = true
},
valueRange = 0f..100f,
onValueChangeFinished = { isEditing = false },
modifier = Modifier.fillMaxWidth(),
)
}
}
}
}

View File

@@ -0,0 +1,202 @@
package io.visus.solanim.ui.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.toggleable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.semantics.isTraversalGroup
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import io.visus.solanim.ui.AppTheme
import io.visus.solanim.ui.LocalContentColor
import io.visus.solanim.ui.contentColorFor
import io.visus.solanim.ui.foundation.ripple
@Composable
@NonRestartableComposable
fun Surface(
modifier: Modifier = Modifier,
shape: Shape = RectangleShape,
color: Color = AppTheme.colors.surface,
contentColor: Color = contentColorFor(color),
shadowElevation: Dp = 0.dp,
border: BorderStroke? = null,
content: @Composable () -> Unit,
) {
CompositionLocalProvider(
LocalContentColor provides contentColor,
) {
Box(
modifier =
modifier
.surface(
shape = shape,
backgroundColor = color,
border = border,
shadowElevation = shadowElevation,
)
.semantics(mergeDescendants = false) {
isTraversalGroup = true
}
.pointerInput(Unit) {},
propagateMinConstraints = true,
) {
content()
}
}
}
@Composable
@NonRestartableComposable
fun Surface(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
shape: Shape = RectangleShape,
color: Color = AppTheme.colors.background,
contentColor: Color = contentColorFor(color),
shadowElevation: Dp = 0.dp,
border: BorderStroke? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit,
) {
CompositionLocalProvider(
LocalContentColor provides contentColor,
) {
Box(
modifier =
modifier
.surface(
shape = shape,
backgroundColor = color,
border = border,
shadowElevation = shadowElevation,
)
.clickable(
interactionSource = interactionSource,
indication = ripple(color = contentColor),
enabled = enabled,
onClick = onClick,
),
propagateMinConstraints = true,
) {
content()
}
}
}
@Composable
@NonRestartableComposable
fun Surface(
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
shape: Shape = RectangleShape,
color: Color = AppTheme.colors.background,
contentColor: Color = contentColorFor(color),
shadowElevation: Dp = 0.dp,
border: BorderStroke? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit,
) {
CompositionLocalProvider(
LocalContentColor provides contentColor,
) {
Box(
modifier =
modifier
.surface(
shape = shape,
backgroundColor = color,
border = border,
shadowElevation = shadowElevation,
)
.selectable(
selected = selected,
interactionSource = interactionSource,
indication = ripple(),
enabled = enabled,
onClick = onClick,
),
propagateMinConstraints = true,
) {
content()
}
}
}
@Composable
@NonRestartableComposable
fun Surface(
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
shape: Shape = RectangleShape,
color: Color = AppTheme.colors.background,
contentColor: Color = contentColorFor(color),
shadowElevation: Dp = 0.dp,
border: BorderStroke? = null,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable () -> Unit,
) {
CompositionLocalProvider(
LocalContentColor provides contentColor,
) {
Box(
modifier =
modifier
.surface(
shape = shape,
backgroundColor = color,
border = border,
shadowElevation = shadowElevation,
)
.toggleable(
value = checked,
interactionSource = interactionSource,
indication = ripple(),
enabled = enabled,
onValueChange = onCheckedChange,
),
propagateMinConstraints = true,
) {
content()
}
}
}
@Composable
private fun Modifier.surface(
shape: Shape,
backgroundColor: Color,
border: BorderStroke?,
shadowElevation: Dp,
) = this
.shadow(
ambientColor = AppTheme.colors.elevation,
spotColor = AppTheme.colors.elevation,
elevation = shadowElevation,
shape = shape,
clip = false,
)
.then(if (border != null) Modifier.border(border, shape) else Modifier)
.background(color = backgroundColor, shape = shape)
.clip(shape)

View File

@@ -0,0 +1,180 @@
package io.visus.solanim.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import io.visus.solanim.ui.LocalContentColor
import io.visus.solanim.ui.LocalTextStyle
import io.visus.solanim.ui.LocalTypography
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun Text(
text: String,
modifier: Modifier = Modifier,
color: Color = LocalContentColor.current,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign = TextAlign.Start,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
minLines: Int = 1,
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current,
) {
Text(
text = AnnotatedString(text = text),
modifier = modifier,
color = color,
fontSize = fontSize,
fontStyle = fontStyle,
fontWeight = fontWeight,
fontFamily = fontFamily,
letterSpacing = letterSpacing,
textDecoration = textDecoration,
textAlign = textAlign,
lineHeight = lineHeight,
overflow = overflow,
softWrap = softWrap,
maxLines = maxLines,
minLines = minLines,
onTextLayout = onTextLayout,
style = style,
)
}
@Composable
internal fun Text(
text: AnnotatedString,
modifier: Modifier = Modifier,
color: Color = LocalContentColor.current,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign = TextAlign.Start,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
minLines: Int = 1,
inlineContent: Map<String, InlineTextContent> = mapOf(),
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current,
) {
val mergedStyle =
style.merge(
TextStyle(
color = color,
fontSize = fontSize,
fontWeight = fontWeight,
textAlign = textAlign,
lineHeight = lineHeight,
fontFamily = fontFamily,
textDecoration = textDecoration,
fontStyle = fontStyle,
letterSpacing = letterSpacing,
),
)
BasicText(
text,
modifier,
mergedStyle,
onTextLayout,
overflow,
softWrap,
maxLines,
minLines,
inlineContent,
)
}
@Preview
@Composable
fun TypographySample() {
val typography = LocalTypography.current
Column(
modifier =
Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
text = "H1 Heading",
style = typography.h1,
)
Text(
text = "H2 Heading",
style = typography.h2,
)
Text(
text = "H3 Heading",
style = typography.h3,
)
Text(
text = "H4 Heading",
style = typography.h4,
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "This is body1 text.",
style = typography.body1,
)
Text(
text = "This is body2 text.",
style = typography.body2,
)
Text(
text = "Body3 text for fine print.",
style = typography.body3,
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Label1: Form Label",
style = typography.label1,
)
Text(
text = "Label2: Secondary Info",
style = typography.label2,
)
Text(
text = "Label3: Tiny Details",
style = typography.label3,
)
Spacer(modifier = Modifier.height(16.dp))
}
}

View File

@@ -0,0 +1,320 @@
package io.visus.solanim.ui.components.topbar
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import io.visus.solanim.ui.AppTheme
import io.visus.solanim.ui.LocalContentColor
import io.visus.solanim.ui.components.Surface
import io.visus.solanim.ui.components.topbar.TopBarDefaults.TopBarHeight
import io.visus.solanim.ui.contentColorFor
import io.visus.solanim.ui.foundation.systemBarsForVisualComponents
@Composable
fun TopBar(
modifier: Modifier = Modifier,
scrollBehavior: TopBarScrollBehavior? = null,
colors: TopBarColors = TopBarDefaults.topBarColors(),
windowInsets: WindowInsets? = TopBarDefaults.windowInsets,
content: @Composable () -> Unit,
) {
TopBarLayout(
modifier = modifier,
scrollBehavior = scrollBehavior,
colors = colors,
windowInsets = windowInsets,
) {
Row(
modifier =
Modifier
.fillMaxWidth()
.height(TopBarHeight),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
content()
}
}
}
@Composable
internal fun TopBarLayout(
modifier: Modifier = Modifier,
colors: TopBarColors = TopBarDefaults.topBarColors(),
windowInsets: WindowInsets? = TopBarDefaults.windowInsets,
scrollBehavior: TopBarScrollBehavior? = null,
content: @Composable () -> Unit,
) {
val height = remember { mutableIntStateOf(0) }
val density = LocalDensity.current
val windowInsetsPaddingValues = windowInsets?.asPaddingValues(density) ?: PaddingValues()
val heightOffsetLimit = -height.intValue.toFloat()
SideEffect {
if (scrollBehavior?.state?.heightOffsetLimit != heightOffsetLimit) {
scrollBehavior?.state?.heightOffsetLimit = heightOffsetLimit
}
}
val colorTransitionFraction = scrollBehavior?.state?.overlappedFraction ?: 0f
val fraction = if (colorTransitionFraction > 0) colorTransitionFraction else 0f
val topBarContainerColor by animateColorAsState(
targetValue = colors.containerColor(fraction),
animationSpec = spring(stiffness = Spring.StiffnessMediumLow),
label = "animate container color",
)
val topBarContentColor by animateColorAsState(
targetValue = colors.contentColor(fraction),
animationSpec = spring(stiffness = Spring.StiffnessMediumLow),
label = "animate content color",
)
val topBarDragModifier =
if (scrollBehavior != null && !scrollBehavior.isPinned) {
Modifier.draggable(
orientation = Orientation.Vertical,
state =
rememberDraggableState {
scrollBehavior.state.heightOffset += it
},
onDragStopped = { velocity ->
settleBar(
scrollBehavior.state,
velocity,
scrollBehavior.flingAnimationSpec,
scrollBehavior.snapAnimationSpec,
)
},
)
} else {
Modifier
}
// calculating based on scrolling behaviour
val dynamicHeight = height.intValue + (scrollBehavior?.state?.heightOffset ?: 0).toInt()
Surface(modifier = modifier.then(topBarDragModifier), color = topBarContainerColor) {
CompositionLocalProvider(LocalContentColor provides topBarContentColor) {
Layout(
content = content,
modifier =
Modifier
.padding(windowInsetsPaddingValues)
.clipToBounds(),
) { measurables, constraints ->
val placeables =
measurables.map { measurable ->
measurable.measure(constraints)
}
if (placeables.isEmpty() || placeables.size > 1) {
throw IllegalStateException("TopBar expects one child!")
}
if (height.intValue == 0) height.intValue = placeables.first().height
layout(constraints.maxWidth, dynamicHeight) {
// Expects only one child, a layout with topbar content
placeables.first().place(0, dynamicHeight - height.intValue)
}
}
}
}
}
object TopBarDefaults {
val TopBarHeight = 56.dp
@Composable
fun topBarColors(
containerColor: Color = AppTheme.colors.background,
scrolledContainerColor: Color = AppTheme.colors.background,
): TopBarColors =
TopBarColors(
containerColor,
scrolledContainerColor,
)
val windowInsets: WindowInsets
@Composable get() =
WindowInsets.systemBarsForVisualComponents.only(
WindowInsetsSides.Horizontal + WindowInsetsSides.Top,
)
@Composable
fun pinnedScrollBehavior(
state: TopBarState = rememberTopBarState(),
canScroll: () -> Boolean = { true },
): TopBarScrollBehavior = PinnedScrollBehavior(state = state, canScroll = canScroll)
@Composable
fun enterAlwaysScrollBehavior(
state: TopBarState = rememberTopBarState(),
canScroll: () -> Boolean = { true },
snapAnimationSpec: AnimationSpec<Float>? = spring(stiffness = Spring.StiffnessMediumLow),
flingAnimationSpec: DecayAnimationSpec<Float>? = rememberSplineBasedDecay(),
): TopBarScrollBehavior =
EnterAlwaysScrollBehavior(
state = state,
snapAnimationSpec = snapAnimationSpec,
flingAnimationSpec = flingAnimationSpec,
canScroll = canScroll,
)
@Composable
fun exitUntilCollapsedScrollBehavior(
state: TopBarState = rememberTopBarState(),
canScroll: () -> Boolean = { true },
snapAnimationSpec: AnimationSpec<Float>? = spring(stiffness = Spring.StiffnessMediumLow),
flingAnimationSpec: DecayAnimationSpec<Float>? = rememberSplineBasedDecay(),
): TopBarScrollBehavior =
ExitUntilCollapsedScrollBehavior(
state = state,
snapAnimationSpec = snapAnimationSpec,
flingAnimationSpec = flingAnimationSpec,
canScroll = canScroll,
)
}
@Composable
fun rememberTopBarState(
initialHeightOffsetLimit: Float = -Float.MAX_VALUE,
initialHeightOffset: Float = 0f,
initialContentOffset: Float = 0f,
): TopBarState {
return rememberSaveable(saver = TopBarState.Saver) {
TopBarState(
initialHeightOffsetLimit,
initialHeightOffset,
initialContentOffset,
)
}
}
@Stable
class TopBarState(
initialHeightOffsetLimit: Float,
initialHeightOffset: Float,
initialContentOffset: Float,
) {
var heightOffsetLimit by mutableFloatStateOf(initialHeightOffsetLimit)
var heightOffset: Float
get() = _heightOffset.floatValue
set(newOffset) {
_heightOffset.floatValue =
newOffset.coerceIn(
minimumValue = heightOffsetLimit,
maximumValue = 0f,
)
}
var contentOffset by mutableStateOf(initialContentOffset)
val collapsedFraction: Float
get() =
if (heightOffsetLimit != 0f) {
heightOffset / heightOffsetLimit
} else {
0f
}
val overlappedFraction: Float
get() =
if (heightOffsetLimit != 0f) {
1 - (
(heightOffsetLimit - contentOffset).coerceIn(
minimumValue = heightOffsetLimit,
maximumValue = 0f,
) / heightOffsetLimit
)
} else {
0f
}
companion object {
/**
* The default [Saver] implementation for [TopBarState].
*/
val Saver: Saver<TopBarState, *> =
listSaver(save = {
listOf(
it.heightOffsetLimit,
it.heightOffset,
it.contentOffset,
)
}, restore = {
TopBarState(
initialHeightOffsetLimit = it[0],
initialHeightOffset = it[1],
initialContentOffset = it[2],
)
})
}
private var _heightOffset = mutableFloatStateOf(initialHeightOffset)
}
@Stable
data class TopBarColors(
val containerColor: Color,
val scrolledContainerColor: Color,
) {
@Composable
internal fun containerColor(colorTransitionFraction: Float): Color {
return lerp(
containerColor,
scrolledContainerColor,
FastOutLinearInEasing.transform(colorTransitionFraction),
)
}
@Composable
internal fun contentColor(colorTransitionFraction: Float): Color {
return lerp(
contentColorFor(color = containerColor),
contentColorFor(color = scrolledContainerColor),
FastOutLinearInEasing.transform(colorTransitionFraction),
)
}
}

View File

@@ -0,0 +1,234 @@
package io.visus.solanim.ui.components.topbar
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.AnimationState
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.animateDecay
import androidx.compose.animation.core.animateTo
import androidx.compose.runtime.Stable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.unit.Velocity
import kotlin.math.abs
class PinnedScrollBehavior(
override val state: TopBarState,
val canScroll: () -> Boolean = { true },
) : TopBarScrollBehavior {
override val isPinned: Boolean = true
override val snapAnimationSpec: AnimationSpec<Float>? = null
override val flingAnimationSpec: DecayAnimationSpec<Float>? = null
override var nestedScrollConnection =
object : NestedScrollConnection {
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource,
): Offset {
if (!canScroll()) return Offset.Zero
if (consumed.y == 0f && available.y > 0f) {
// Reset the total content offset to zero when scrolling all the way down.
// This will eliminate some float precision inaccuracies.
state.contentOffset = 0f
} else {
state.contentOffset += consumed.y
}
return Offset.Zero
}
}
}
class EnterAlwaysScrollBehavior(
override val state: TopBarState,
override val snapAnimationSpec: AnimationSpec<Float>?,
override val flingAnimationSpec: DecayAnimationSpec<Float>?,
val canScroll: () -> Boolean = { true },
) : TopBarScrollBehavior {
override val isPinned: Boolean = false
override var nestedScrollConnection =
object : NestedScrollConnection {
override fun onPreScroll(
available: Offset,
source: NestedScrollSource,
): Offset {
if (!canScroll()) return Offset.Zero
val prevHeightOffset = state.heightOffset
state.heightOffset += available.y
return if (prevHeightOffset != state.heightOffset) {
// We're in the middle of top app bar collapse or expand.
// Consume only the scroll on the Y axis.
available.copy(x = 0f)
} else {
Offset.Zero
}
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource,
): Offset {
if (!canScroll()) return Offset.Zero
state.contentOffset += consumed.y
if (state.heightOffset == 0f || state.heightOffset == state.heightOffsetLimit) {
if (consumed.y == 0f && available.y > 0f) {
// Reset the total content offset to zero when scrolling all the way down.
// This will eliminate some float precision inaccuracies.
state.contentOffset = 0f
}
}
state.heightOffset += consumed.y
return Offset.Zero
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity,
): Velocity {
val superConsumed = super.onPostFling(consumed, available)
return superConsumed +
settleBar(
state,
available.y,
flingAnimationSpec,
snapAnimationSpec,
)
}
}
}
class ExitUntilCollapsedScrollBehavior(
override val state: TopBarState,
override val snapAnimationSpec: AnimationSpec<Float>?,
override val flingAnimationSpec: DecayAnimationSpec<Float>?,
val canScroll: () -> Boolean = { true },
) : TopBarScrollBehavior {
override val isPinned: Boolean = false
override var nestedScrollConnection =
object : NestedScrollConnection {
override fun onPreScroll(
available: Offset,
source: NestedScrollSource,
): Offset {
// Don't intercept if scrolling down.
if (!canScroll() || available.y > 0f) return Offset.Zero
val prevHeightOffset = state.heightOffset
state.heightOffset += available.y
return if (prevHeightOffset != state.heightOffset) {
// We're in the middle of top app bar collapse or expand.
// Consume only the scroll on the Y axis.
available.copy(x = 0f)
} else {
Offset.Zero
}
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource,
): Offset {
if (!canScroll()) return Offset.Zero
state.contentOffset += consumed.y
if (available.y < 0f || consumed.y < 0f) {
// When scrolling up, just update the state's height offset.
val oldHeightOffset = state.heightOffset
state.heightOffset += consumed.y
return Offset(0f, state.heightOffset - oldHeightOffset)
}
if (consumed.y == 0f && available.y > 0) {
// Reset the total content offset to zero when scrolling all the way down. This
// will eliminate some float precision inaccuracies.
state.contentOffset = 0f
}
if (available.y > 0f) {
// Adjust the height offset in case the consumed delta Y is less than what was
// recorded as available delta Y in the pre-scroll.
val oldHeightOffset = state.heightOffset
state.heightOffset += available.y
return Offset(0f, state.heightOffset - oldHeightOffset)
}
return Offset.Zero
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity,
): Velocity {
val superConsumed = super.onPostFling(consumed, available)
return superConsumed +
settleBar(
state,
available.y,
flingAnimationSpec,
snapAnimationSpec,
)
}
}
}
suspend fun settleBar(
state: TopBarState,
velocity: Float,
flingAnimationSpec: DecayAnimationSpec<Float>?,
snapAnimationSpec: AnimationSpec<Float>?,
): Velocity {
// Check if the app bar is completely collapsed/expanded. If so, no need to settle the app bar,
// and just return Zero Velocity.
// Note that we don't check for 0f due to float precision with the collapsedFraction
// calculation.
if (state.collapsedFraction < 0.01f || state.collapsedFraction == 1f) {
return Velocity.Zero
}
var remainingVelocity = velocity
// In case there is an initial velocity that was left after a previous user fling, animate to
// continue the motion to expand or collapse the app bar.
if (flingAnimationSpec != null && abs(velocity) > 1f) {
var lastValue = 0f
AnimationState(
initialValue = 0f,
initialVelocity = velocity,
)
.animateDecay(flingAnimationSpec) {
val delta = value - lastValue
val initialHeightOffset = state.heightOffset
state.heightOffset = initialHeightOffset + delta
val consumed = abs(initialHeightOffset - state.heightOffset)
lastValue = value
remainingVelocity = this.velocity
// avoid rounding errors and stop if anything is unconsumed
if (abs(delta - consumed) > 0.5f) this.cancelAnimation()
}
}
// Snap if animation specs were provided.
if (snapAnimationSpec != null) {
if (state.heightOffset < 0 &&
state.heightOffset > state.heightOffsetLimit
) {
AnimationState(initialValue = state.heightOffset).animateTo(
if (state.collapsedFraction < 0.5f) {
0f
} else {
state.heightOffsetLimit
},
animationSpec = snapAnimationSpec,
) { state.heightOffset = value }
}
}
return Velocity(0f, remainingVelocity)
}
@Stable
interface TopBarScrollBehavior {
val state: TopBarState
val isPinned: Boolean
val snapAnimationSpec: AnimationSpec<Float>?
val flingAnimationSpec: DecayAnimationSpec<Float>?
val nestedScrollConnection: NestedScrollConnection
}

View File

@@ -0,0 +1,74 @@
package io.visus.solanim.ui.foundation
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.Easing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.interaction.DragInteraction
import androidx.compose.foundation.interaction.FocusInteraction
import androidx.compose.foundation.interaction.HoverInteraction
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.ui.unit.Dp
internal suspend fun Animatable<Dp, *>.animateElevation(
target: Dp,
from: Interaction? = null,
to: Interaction? = null,
) {
val spec =
when {
// Moving to a new state
to != null -> ElevationDefaults.incomingAnimationSpecForInteraction(to)
// Moving to default, from a previous state
from != null -> ElevationDefaults.outgoingAnimationSpecForInteraction(from)
// Loading the initial state, or moving back to the baseline state from a disabled /
// unknown state, so just snap to the final value.
else -> null
}
if (spec != null) animateTo(target, spec) else snapTo(target)
}
private object ElevationDefaults {
fun incomingAnimationSpecForInteraction(interaction: Interaction): AnimationSpec<Dp>? {
return when (interaction) {
is PressInteraction.Press -> DefaultIncomingSpec
is DragInteraction.Start -> DefaultIncomingSpec
is HoverInteraction.Enter -> DefaultIncomingSpec
is FocusInteraction.Focus -> DefaultIncomingSpec
else -> null
}
}
fun outgoingAnimationSpecForInteraction(interaction: Interaction): AnimationSpec<Dp>? {
return when (interaction) {
is PressInteraction.Press -> DefaultOutgoingSpec
is DragInteraction.Start -> DefaultOutgoingSpec
is HoverInteraction.Enter -> HoveredOutgoingSpec
is FocusInteraction.Focus -> DefaultOutgoingSpec
else -> null
}
}
}
private val OutgoingSpecEasing: Easing = CubicBezierEasing(0.40f, 0.00f, 0.60f, 1.00f)
private val DefaultIncomingSpec =
TweenSpec<Dp>(
durationMillis = 120,
easing = FastOutSlowInEasing,
)
private val DefaultOutgoingSpec =
TweenSpec<Dp>(
durationMillis = 150,
easing = OutgoingSpecEasing,
)
private val HoveredOutgoingSpec =
TweenSpec<Dp>(
durationMillis = 120,
easing = OutgoingSpecEasing,
)

View File

@@ -0,0 +1,216 @@
package io.visus.solanim.ui.foundation
import androidx.compose.foundation.IndicationNodeFactory
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.material.ripple.RippleAlpha
import androidx.compose.material.ripple.createRippleModifierNode
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.Stable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorProducer
import androidx.compose.ui.graphics.isSpecified
import androidx.compose.ui.node.CompositionLocalConsumerModifierNode
import androidx.compose.ui.node.DelegatableNode
import androidx.compose.ui.node.DelegatingNode
import androidx.compose.ui.node.ObserverModifierNode
import androidx.compose.ui.node.currentValueOf
import androidx.compose.ui.node.observeReads
import androidx.compose.ui.unit.Dp
import io.visus.solanim.ui.LocalContentColor
@Stable
fun ripple(
bounded: Boolean = true,
radius: Dp = Dp.Unspecified,
color: Color = Color.Unspecified,
): IndicationNodeFactory {
return if (radius == Dp.Unspecified && color == Color.Unspecified) {
if (bounded) return DefaultBoundedRipple else DefaultUnboundedRipple
} else {
RippleNodeFactory(bounded, radius, color)
}
}
@Stable
fun ripple(
color: ColorProducer,
bounded: Boolean = true,
radius: Dp = Dp.Unspecified,
): IndicationNodeFactory {
return RippleNodeFactory(bounded, radius, color)
}
/** Default values used by [ripple]. */
object RippleDefaults {
/**
* Represents the default [RippleAlpha] that will be used for a ripple to indicate different
* states.
*/
val RippleAlpha: RippleAlpha =
RippleAlpha(
pressedAlpha = StateTokens.PressedStateLayerOpacity,
focusedAlpha = StateTokens.FocusStateLayerOpacity,
draggedAlpha = StateTokens.DraggedStateLayerOpacity,
hoveredAlpha = StateTokens.HoverStateLayerOpacity,
)
}
val LocalRippleConfiguration: ProvidableCompositionLocal<RippleConfiguration?> =
compositionLocalOf {
RippleConfiguration()
}
@Immutable
class RippleConfiguration(
val color: Color = Color.Unspecified,
val rippleAlpha: RippleAlpha? = null,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RippleConfiguration) return false
if (color != other.color) return false
if (rippleAlpha != other.rippleAlpha) return false
return true
}
override fun hashCode(): Int {
var result = color.hashCode()
result = 31 * result + (rippleAlpha?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "RippleConfiguration(color=$color, rippleAlpha=$rippleAlpha)"
}
}
@Stable
private class RippleNodeFactory
private constructor(
private val bounded: Boolean,
private val radius: Dp,
private val colorProducer: ColorProducer?,
private val color: Color,
) : IndicationNodeFactory {
constructor(
bounded: Boolean,
radius: Dp,
colorProducer: ColorProducer,
) : this(bounded, radius, colorProducer, Color.Unspecified)
constructor(bounded: Boolean, radius: Dp, color: Color) : this(bounded, radius, null, color)
override fun create(interactionSource: InteractionSource): DelegatableNode {
val colorProducer = colorProducer ?: ColorProducer { color }
return DelegatingThemeAwareRippleNode(interactionSource, bounded, radius, colorProducer)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RippleNodeFactory) return false
if (bounded != other.bounded) return false
if (radius != other.radius) return false
if (colorProducer != other.colorProducer) return false
return color == other.color
}
override fun hashCode(): Int {
var result = bounded.hashCode()
result = 31 * result + radius.hashCode()
result = 31 * result + colorProducer.hashCode()
result = 31 * result + color.hashCode()
return result
}
}
private class DelegatingThemeAwareRippleNode(
private val interactionSource: InteractionSource,
private val bounded: Boolean,
private val radius: Dp,
private val color: ColorProducer,
) : DelegatingNode(), CompositionLocalConsumerModifierNode, ObserverModifierNode {
private var rippleNode: DelegatableNode? = null
override fun onAttach() {
updateConfiguration()
}
override fun onObservedReadsChanged() {
updateConfiguration()
}
/**
* Handles [LocalRippleConfiguration] changing between null / non-null. Changes to
* [RippleConfiguration.color] and [RippleConfiguration.rippleAlpha] are handled as part of the
* ripple definition.
*/
private fun updateConfiguration() {
observeReads {
val configuration = currentValueOf(LocalRippleConfiguration)
if (configuration == null) {
removeRipple()
} else {
if (rippleNode == null) attachNewRipple()
}
}
}
private fun attachNewRipple() {
val calculateColor =
ColorProducer {
val userDefinedColor = color()
if (userDefinedColor.isSpecified) {
userDefinedColor
} else {
// If this is null, the ripple will be removed, so this should always be non-null in
// normal use
val rippleConfiguration = currentValueOf(LocalRippleConfiguration)
if (rippleConfiguration?.color?.isSpecified == true) {
rippleConfiguration.color
} else {
currentValueOf(LocalContentColor)
}
}
}
val calculateRippleAlpha = {
// If this is null, the ripple will be removed, so this should always be non-null in
// normal use
val rippleConfiguration = currentValueOf(LocalRippleConfiguration)
rippleConfiguration?.rippleAlpha ?: RippleDefaults.RippleAlpha
}
rippleNode =
delegate(
createRippleModifierNode(
interactionSource,
bounded,
radius,
calculateColor,
calculateRippleAlpha,
),
)
}
private fun removeRipple() {
rippleNode?.let { undelegate(it) }
rippleNode = null
}
}
private object StateTokens {
const val DraggedStateLayerOpacity = 0.16f
const val FocusStateLayerOpacity = 0.1f
const val HoverStateLayerOpacity = 0.08f
const val PressedStateLayerOpacity = 0.1f
}
private val DefaultBoundedRipple =
RippleNodeFactory(bounded = true, radius = Dp.Unspecified, color = Color.Unspecified)
private val DefaultUnboundedRipple =
RippleNodeFactory(bounded = false, radius = Dp.Unspecified, color = Color.Unspecified)

View File

@@ -0,0 +1,10 @@
package io.visus.solanim.ui.foundation
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.systemBars
import androidx.compose.runtime.Composable
val WindowInsets.Companion.systemBarsForVisualComponents: WindowInsets
@Composable
get() = systemBars

View File

@@ -0,0 +1,17 @@
package io.visus.solanim.ui
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}