Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 3c76a010 authored by Chaohui Wang's avatar Chaohui Wang Committed by Android (Google) Code Review
Browse files

Merge "[Spa] Create MorphingTitleTopAppBar" into main

parents 217a1a2e 408660f0
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -295,7 +295,7 @@ private class SettingsTypography(settingsFontFamily: SettingsFontFamily) {
                    fontWeight = FontWeight.SemiBold,
                    fontSize = 22.sp,
                    lineHeight = 28.sp,
                    letterSpacing = 0.02.em,
                    letterSpacing = 0.sp,
                    hyphens = Hyphens.Auto,
                ),
            titleMedium =
+8 −9
Original line number Diff line number Diff line
@@ -49,6 +49,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.runtime.ProvidedValue
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
@@ -204,7 +205,7 @@ private fun topAppBarColors() =
 *   using the default material3 spec
 */
@Stable
private class TopAppBarColors(
internal class TopAppBarColors(
    val containerColor: Color,
    val scrolledContainerColor: Color,
    val navigationIconContentColor: Color,
@@ -542,13 +543,7 @@ private fun TopAppBarLayout(
                ProvideTextStyle(value = titleTextStyle) {
                    CompositionLocalProvider(
                        LocalContentColor provides titleContentColor,
                        LocalDensity provides
                            with(LocalDensity.current) {
                                Density(
                                    density = density,
                                    fontScale = if (titleScaleDisabled) 1f else fontScale,
                                )
                            },
                        localDensityDisableFontScale(),
                        content = title,
                    )
                }
@@ -636,7 +631,7 @@ private fun TopAppBarLayout(
 * after the fling settles.
 */
@OptIn(ExperimentalMaterial3Api::class)
private suspend fun settleAppBar(
internal suspend fun settleAppBar(
    state: TopAppBarState,
    velocity: Float,
    flingAnimationSpec: DecayAnimationSpec<Float>?,
@@ -686,6 +681,10 @@ private suspend fun settleAppBar(
    return Velocity(0f, remainingVelocity)
}

@Composable
internal fun localDensityDisableFontScale(): ProvidedValue<Density> =
    LocalDensity provides with(LocalDensity.current) { Density(density = density, fontScale = 1f) }

// An easing function used to compute the alpha value that is applied to the top title part of a
// Medium or Large app bar.
private val TopTitleAlphaEasing = CubicBezierEasing(.8f, 0f, .8f, .15f)
+314 −0
Original line number Diff line number Diff line
/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settingslib.spa.widget.scaffold

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.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
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.draw.drawBehind
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.isTraversalGroup
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.lerp as lerpTextStyle
import androidx.compose.ui.text.style.TextMotion
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.lerp as lerpDp
import androidx.compose.ui.util.lerp
import com.android.settingslib.spa.framework.theme.SettingsDimension
import com.android.settingslib.spa.framework.theme.SettingsSize
import com.android.settingslib.spa.framework.theme.SettingsSpace
import kotlin.math.roundToInt

private val safeDrawingWindowInsets: WindowInsets
    @Composable
    @NonRestartableComposable
    get() = WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top)

/** The morphing title LargeTopAppBar for Settings. */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
@Composable
internal fun MorphingTitleLargeTopAppBar(
    title: String,
    modifier: Modifier = Modifier,
    navigationIcon: @Composable () -> Unit = {},
    actions: @Composable RowScope.() -> Unit = {},
    scrollBehavior: TopAppBarScrollBehavior,
) {
    TwoRowsTopAppBar(
        titleText = title,
        expandedTextStyle =
            MaterialTheme.typography.displaySmallEmphasized.copy(textMotion = TextMotion.Animated),
        collapsedTextStyle =
            MaterialTheme.typography.titleLargeEmphasized.copy(textMotion = TextMotion.Animated),
        titleBottomPadding = LargeTitleBottomPadding,
        expandedTitleMaxLines = 2,
        collapsedTitleMaxLines = 1,
        modifier = modifier,
        navigationIcon = navigationIcon,
        actions = actions,
        colors = topAppBarColors(),
        windowInsets = safeDrawingWindowInsets,
        pinnedHeight = ContainerHeight,
        scrollBehavior = scrollBehavior,
    )
}

@Composable
private fun topAppBarColors() =
    TopAppBarColors(
        containerColor = MaterialTheme.colorScheme.surfaceContainer,
        scrolledContainerColor = MaterialTheme.colorScheme.surfaceContainer,
        navigationIconContentColor = MaterialTheme.colorScheme.onSurface,
        titleContentColor = MaterialTheme.colorScheme.onSurface,
        actionIconContentColor = MaterialTheme.colorScheme.primary,
    )

/**
 * A two-rows top app bar that is designed to be called by the Large and Medium top app bar
 * composables.
 *
 * @throws [IllegalArgumentException] if the given [MaxHeight] is equal or smaller than the
 *   [pinnedHeight]
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TwoRowsTopAppBar(
    modifier: Modifier = Modifier,
    titleText: String,
    expandedTextStyle: TextStyle,
    collapsedTextStyle: TextStyle,
    titleBottomPadding: Dp,
    expandedTitleMaxLines: Int,
    collapsedTitleMaxLines: Int,
    navigationIcon: @Composable () -> Unit,
    actions: @Composable RowScope.() -> Unit,
    windowInsets: WindowInsets,
    colors: TopAppBarColors,
    pinnedHeight: Dp,
    scrollBehavior: TopAppBarScrollBehavior,
) {
    if (MaxHeight <= pinnedHeight) {
        throw IllegalArgumentException(
            "A TwoRowsTopAppBar max height should be greater than its pinned height"
        )
    }
    val density = LocalDensity.current
    val pinnedHeightPx: Float = density.run { pinnedHeight.toPx() }
    val titleBottomPaddingPx: Int = density.run { titleBottomPadding.roundToPx() }
    val maxHeightPx = density.run { MaxHeight.toPx() }
    val heightOffsetLimit = pinnedHeightPx - maxHeightPx

    LaunchedEffect(heightOffsetLimit) { scrollBehavior.state.heightOffsetLimit = heightOffsetLimit }

    var hasCollapsedInitially by rememberSaveable { mutableStateOf(false) }
    LaunchedEffect(scrollBehavior) {
        if (!hasCollapsedInitially) {
            scrollBehavior.collapse()
            hasCollapsedInitially = true
        }
    }

    val collapsedFraction = scrollBehavior.state.collapsedFraction
    val appBarContainerColor = colors.containerColor(collapsedFraction)

    val actionsRow =
        @Composable {
            Row(
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically,
                content = actions,
            )
        }

    val appBarDragModifier =
        if (!scrollBehavior.isPinned) {
            Modifier.draggable(
                orientation = Orientation.Vertical,
                state =
                    rememberDraggableState { delta -> scrollBehavior.state.heightOffset += delta },
                onDragStopped = { velocity ->
                    settleAppBar(
                        scrollBehavior.state,
                        velocity,
                        scrollBehavior.flingAnimationSpec,
                        scrollBehavior.snapAnimationSpec,
                    )
                },
            )
        } else {
            Modifier
        }

    val currentAppBarHeightPx = maxHeightPx + scrollBehavior.state.heightOffset

    // Interpolated properties for the single title
    val interpolatedTextStyle =
        lerpTextStyle(expandedTextStyle, collapsedTextStyle, collapsedFraction)
    val expandedTitlePaddingStart = SettingsSpace.small4 // Left padding
    val collapsedTitlePaddingStart =
        expandedTitlePaddingStart + SettingsSize.medium3 + SettingsSpace.small3 // Icon + padding
    val interpolatedPaddingStart =
        lerpDp(expandedTitlePaddingStart, collapsedTitlePaddingStart, collapsedFraction)
    val currentMaxLines =
        if (collapsedFraction < 0.5f) expandedTitleMaxLines else collapsedTitleMaxLines

    Box(
        modifier =
            modifier
                .then(appBarDragModifier)
                .drawBehind { drawRect(color = appBarContainerColor) }
                .semantics { isTraversalGroup = true }
                .pointerInput(Unit) {}
    ) {
        Layout(
            content = {
                Box(Modifier.layoutId("navigationIcon").padding(start = SettingsSpace.small3)) {
                    CompositionLocalProvider(
                        LocalContentColor provides colors.navigationIconContentColor,
                        content = navigationIcon,
                    )
                }

                Box(Modifier.layoutId("title")) {
                    ProvideTextStyle(value = interpolatedTextStyle) {
                        CompositionLocalProvider(
                            LocalContentColor provides colors.titleContentColor,
                            localDensityDisableFontScale(),
                        ) {
                            Text(
                                text = titleText,
                                modifier =
                                    Modifier.padding(end = SettingsDimension.itemPaddingEnd)
                                        .semantics { heading() },
                                overflow = TextOverflow.Ellipsis,
                                maxLines = currentMaxLines,
                            )
                        }
                    }
                }

                Box(Modifier.layoutId("actionIcons").padding(end = TopAppBarHorizontalPadding)) {
                    CompositionLocalProvider(
                        LocalContentColor provides colors.actionIconContentColor,
                        content = actionsRow,
                    )
                }
            },
            modifier = Modifier.windowInsetsPadding(windowInsets).clipToBounds(),
        ) { measurables, constraints ->
            val navigationIconPlaceable =
                measurables
                    .first { it.layoutId == "navigationIcon" }
                    .measure(constraints.copy(minWidth = 0))
            val actionIconsPlaceable =
                measurables
                    .first { it.layoutId == "actionIcons" }
                    .measure(constraints.copy(minWidth = 0))

            val titleHorizontalPaddingPx =
                density.run {
                    interpolatedPaddingStart.toPx() + SettingsDimension.itemPaddingEnd.toPx()
                }
            val titleMaxWidth =
                (constraints.maxWidth -
                        collapsedFraction * actionIconsPlaceable.width -
                        titleHorizontalPaddingPx)
                    .roundToInt()
                    .coerceAtLeast(0)

            val titlePlaceable =
                measurables
                    .first { it.layoutId == "title" }
                    .measure(Constraints.fixedWidth(titleMaxWidth))

            val layoutWidth = constraints.maxWidth
            val layoutHeight = currentAppBarHeightPx.roundToInt().coerceAtLeast(0)

            layout(layoutWidth, layoutHeight) {
                navigationIconPlaceable.placeRelative(
                    x = 0,
                    y = ((pinnedHeightPx - navigationIconPlaceable.height) / 2f).roundToInt(),
                )

                actionIconsPlaceable.placeRelative(
                    x = layoutWidth - actionIconsPlaceable.width,
                    y = ((pinnedHeightPx - actionIconsPlaceable.height) / 2f).roundToInt(),
                )

                // Calculate Y position for the title
                val titleYCollapsed = (pinnedHeightPx - titlePlaceable.height) / 2f

                // For expanded Y, consider titleBottomPadding.
                // Align the bottom of the title text box (titlePlaceable.height)
                // with titleBottomPaddingPx from the overall layoutHeight when fully expanded
                // (maxHeightPx).
                val titleYExpanded = maxHeightPx - titlePlaceable.height - titleBottomPaddingPx

                val interpolatedTitleY = lerp(titleYExpanded, titleYCollapsed, collapsedFraction)

                // Calculate X position for the title
                // Similar to TopAppBarLayout: place after nav icon, respecting TopAppBarTitleInset
                val titleX = density.run { interpolatedPaddingStart.toPx() }

                titlePlaceable.placeRelative(
                    x = titleX.roundToInt(),
                    y = interpolatedTitleY.roundToInt(),
                )
            }
        }
    }
}

private val MaxHeight = 179.dp
private val LargeTitleBottomPadding = 28.dp
private val TopAppBarHorizontalPadding = 4.dp
+22 −9
Original line number Diff line number Diff line
@@ -24,6 +24,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.window.embedding.ActivityEmbeddingController
import com.android.settingslib.spa.framework.compose.localActivity
import com.android.settingslib.spa.framework.theme.isSpaExpressiveEnabled

@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -33,13 +34,27 @@ internal fun SettingsTopAppBar(
    isFirstLayerPageWhenEmbedded: Boolean,
    actions: @Composable RowScope.() -> Unit,
) {
    if (isSpaExpressiveEnabled) {
        MorphingTitleLargeTopAppBar(
            title = title,
            navigationIcon = { NavigationIcon(isFirstLayerPageWhenEmbedded) },
            actions = actions,
            scrollBehavior = scrollBehavior,
        )
    } else {
        CustomizedLargeTopAppBar(
            title = title,
        navigationIcon = { if (shouldShowNavigateBack(isFirstLayerPageWhenEmbedded)) NavigateBack() },
            navigationIcon = { NavigationIcon(isFirstLayerPageWhenEmbedded) },
            actions = actions,
            scrollBehavior = scrollBehavior,
        )
    }
}

@Composable
private fun NavigationIcon(isFirstLayerPageWhenEmbedded: Boolean) {
    if (shouldShowNavigateBack(isFirstLayerPageWhenEmbedded)) NavigateBack()
}

/** Whether the current page should show the navigate back button. */
@Composable
@@ -57,7 +72,5 @@ private fun shouldShowNavigateBack(isFirstLayerPageWhenEmbedded: Boolean): Boole

@OptIn(ExperimentalMaterial3Api::class)
internal fun TopAppBarScrollBehavior.collapse() {
    with(state) {
        heightOffset = heightOffsetLimit
    }
    with(state) { heightOffset = heightOffsetLimit }
}