All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.androidx.compose.material3.MappedInteractionSource.kt Maven / Gradle / Ivy

There is a newer version: 1.0.9
Show newest version
/*
 * Copyright 2022 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 androidx.compose.material3

import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.ui.geometry.Offset
import kotlinx.coroutines.flow.map

/**
 * Adapts an [InteractionSource] from one component to another by mapping any interactions by a
 * given offset. Namely used for the pill indicator in [NavigationBarItem] and [NavigationRailItem].
 */
internal class MappedInteractionSource(
    underlyingInteractionSource: InteractionSource,
    private val delta: Offset
) : InteractionSource {
    private val mappedPresses =
        mutableMapOf()

    override val interactions = underlyingInteractionSource.interactions.map { interaction ->
        when (interaction) {
            is PressInteraction.Press -> {
                val mappedPress = mapPress(interaction)
                mappedPresses[interaction] = mappedPress
                mappedPress
            }
            is PressInteraction.Cancel -> {
                val mappedPress = mappedPresses.remove(interaction.press)
                if (mappedPress == null) {
                    interaction
                } else {
                    PressInteraction.Cancel(mappedPress)
                }
            }
            is PressInteraction.Release -> {
                val mappedPress = mappedPresses.remove(interaction.press)
                if (mappedPress == null) {
                    interaction
                } else {
                    PressInteraction.Release(mappedPress)
                }
            }
            else -> interaction
        }
    }

    private fun mapPress(press: PressInteraction.Press): PressInteraction.Press =
        PressInteraction.Press(press.pressPosition - delta)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy