Giter Club home page Giter Club logo

compose-sonner's Introduction

Compose Sonner

Compose Sonner

Maven Central GitHub Workflow Status (with event)

An opinionated toast component for Compose Multiplatform.

This is a Compose implementation of sonner - an excellent toast library by emilkowalski.

Demo

WasmJs Demo

https://dokar3.github.io/compose-sonner/

Video

compose-sonner-small.mp4

Features

  • Almost the same as emilkowalski's React implementation: UI, Animations, and even the API. These include:
    • Stacked toasts and expanded toasts
    • Different types and rich colors
    • Transitions
    • Positions (Alignments)
    • Swipe down to dismiss
    • Close button and action button
    • Custom icons
    • Durations
  • Lazy and performant, you can display a large amount of toasts at once
  • Fully customizable, you can render your own Composable on it
  • Supports both Material 2 and Material 3 because it does not depend on them

Roadmaps

Usages

Installation

build.gradle(.kts)

implementation("io.github.dokar3:sonner:<VERSION>")

libs.versions.toml

sonner = { module = "io.github.dokar3:sonner", version = "<VERSION>" }

Basic

val toaster = rememberToasterState()

Button(onClick = { toaster.show("Hello world!") }) {
    Text("Show a toast")
}

Toaster(state = toaster)

Types

toaster.show(
    message = "Message",
    type = ToastType.[Normal | Success | Info | Warning | Error],
)

Dark theme

toaster.show(
    message = "Message",
    darkTheme = true,
)

Positions

Toaster(
    state = toaster,
    alignment = Alignment.[TopStart | TopCenter | TopEnd | BottomStart | BottomCener | BottomEnd],
)

Durations

toaster.show(
    message = "Message",
    duration = [ToasterDefaults.DurationLong | 5000.milliseconds | Duration.INFINITE],
)

Updates

const val TOAST_ID_LOADING = ANYTHING

toaster.show(message = "Loading", id = TOAST_ID_LOADING, duration = Duration.INFINITE)

toaster.show(message = "Success", id = TOAST_ID_LOADING)

Dismiss

toaster.dismiss(id)
toaster.dismiss(toast)
toaster.dismissAll()

Buttons

// Enable close buttons
Toaster(
    state = toaster,
    showCloseButton = true,
)

// Set an action button
toaster.show(
    message = "Message",
    action = TextToastAction(
        text = "Dismiss",
        onClick = { toaster.dismiss(it) },
    )
)

Icons

Toaster(
    state = toaster,
    iconSlot = { toast ->
        // ICON_LOADING can be anything, it's just a mark
        if (toast.icon == ICON_LAODING) {
            LoadingIcon()
        } else {
            // Fallback to the default icon slot
            ToasterDefaults.iconSlot(toast)
        }
    },
)

Dismiss pause

Toaster(
    state = toaster,
    dismissPause = ToastDismissPause.[Never | OnNotFront | OnInvisible],
)

Other

@Composable
fun Toaster(
    contentColor: @Composable (toast: Toast) -> Color,
    border: @Composable (toast: Toast) -> BorderStroke,
    background: @Composable (toast: Toast) -> Brush,
    shape: @Composable (toast: Toast) -> Shape,
    elevation: Dp,
    shadowAmbientColor: Color,
    shadowSpotColor: Color,
    contentPadding: PaddingValues,
    containerPadding: @Composable (toast: Toast) -> PaddingValues,
    widthPolicy: @Composable (toast: Toast) -> ToastWidthPolicy,
    offset: IntOffet,
)

Interact with ViewModel UiState

Define the mapping function

fun UiMessage.toToast(): Toast = when (this) {
    is UiMessage.Error -> Toast(id = id, message = message, type = ToastType.Error)
    is UiMessage.Success -> Toast(id = id, message = message, type = ToastType.Success)
}

Then

val toaster = rememberToasterState(
    onDismissed = { viewModel.removeUiMessageById(it.id as Long) },
)

val uiState by viewModel.uiState.collectAsState()

LaunchedEffect(viewModel, toaster) {
    // Listen to messages changes and map to toasts
    val toastsFlow = viewModel.uiState.map { it.uiMessages.map(UiMessage::toToast) }
    toaster.listenMany(toastsFlow)
}

Toaster(state = toaster)

Or use an adapter function

@Composable
fun UiMessageToaster(
    messages: List<UiMessage>,
    onRemoveMessage: (id: Long) -> Unit,
    modifier: Modifier = Modifier,
) {
    val toaster = rememberToasterState(
        onToastDismissed = { onRemoveMessage(it.id as Long) },
    )

    val currentMessages by rememberUpdatedState(messages)

    LaunchedEffect(toaster) {
        // Listen to State<List<UiMessage>> changes and map to toasts
        toaster.listenMany { currentMessages.map(UiMessage::toToast) }
    }

    Toaster(state = toaster, modifier = modifier)
}

@Composable
fun YourScreen(...) {
    val uiState by viewModel.uiState.collectAsState()

    ...

    UiMessageToaster(
        messages = uiState.uiMessages,
        onRemoveMessage = { viewModel.removeUiMessageById(it) },
    )
}

License

Copyright 2024 dokar3

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.

compose-sonner's People

Contributors

dokar3 avatar renovate[bot] avatar jamshedalamqaderi avatar shubhamsinghshubham777 avatar

Stargazers

Edge At Zero avatar amir avatar Sam Gammon avatar Murad Akhmedov avatar Huangkl avatar Orelvis Lago Vasallo avatar dalan avatar Vishnu Sanal T avatar Shabinder Singh avatar Utku Yıldız avatar Anurag Parmar avatar holmes zhang avatar Anurag Parmar (SSB Digital) avatar Aleksey Mikhailov avatar Naimul Kabir avatar Arqam Ahmad Siddiqui avatar jershell avatar  avatar  avatar Oscar Poémape avatar Andi Hasan A avatar Shohei Kawano avatar  avatar 嚴肅遊戲 avatar Samyak Jain avatar  avatar BHawk  avatar Alexander Localhostov avatar Qiu avatar Balázs Püspök-Kiss avatar Abdallah avatar  avatar  avatar jherrero avatar Halim Bimantara avatar Chetan Gupta avatar Jan Tennert avatar  avatar Dmitry avatar lin avatar Pradeep avatar Pradeep L S avatar Abbasali avatar  avatar  avatar Stijn avatar  avatar  avatar Savvas Dalkitsis avatar Patrício Cordeiro avatar zhuzhu avatar Harimurti Wibowo avatar WangKe avatar 1f2003d5 avatar  avatar Kosh Sergani avatar  avatar Jacob avatar Colin avatar Rnz Brngn avatar PP avatar Mohammad Anwar avatar JI HUN LEE avatar Dmitri Kuzmich avatar Daniel San Ferreira da Rocha avatar hamyn avatar boovana avatar tdkms avatar Mohammad Mohammadi avatar Vivien Mahé avatar Sean Proctor avatar 杨晓若 avatar Syed Aitizaz Ul Hassan avatar Miłosz Kałucki avatar Diego Beraldin avatar Shaun avatar Nick avatar Sooxin avatar blackwen avatar Boy Hoody avatar Nada Feteiha avatar Sayan Bera avatar hassaan avatar Anderson Canteiro avatar Calleb Joel Miquissene avatar Alper ÖZASLAN avatar Mahmoud Reda avatar Abhay avatar SurajSinh Rathod avatar AndrewAboAlhana avatar dicky7 avatar Aritra Das avatar Abhishek Saxena avatar Binay Shaw avatar Jaime Parra Gamboa avatar Yanneck Reiß avatar abdelhak avatar  avatar Can Önal avatar Yannick avatar

Watchers

Lucian avatar  avatar  avatar

compose-sonner's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/build.yaml
  • actions/checkout v4
  • actions/setup-java v4
  • gradle/gradle-build-action v3.5.0
.github/workflows/publish-library.yaml
  • actions/checkout v4
  • actions/setup-java v4
  • gradle/gradle-build-action v3.5.0
  • macos 14
.github/workflows/publish-wasmjs-demo.yaml
  • actions/checkout v4
  • actions/setup-java v4
  • gradle/gradle-build-action v3.5.0
  • actions/upload-pages-artifact v3
  • actions/deploy-pages v4
gradle
gradle.properties
settings.gradle.kts
build.gradle.kts
gradle/libs.versions.toml
  • org.jetbrains.kotlin:kotlin-test 2.0.0
  • androidx.activity:activity-compose 1.9.0
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.8.1
  • org.jetbrains.kotlinx:kotlinx-coroutines-test 1.8.1
  • com.android.application 8.5.1
  • com.android.library 8.5.1
  • org.jetbrains.compose 1.6.11
  • org.jetbrains.kotlin.multiplatform 2.0.0
  • org.jetbrains.kotlin.android 2.0.0
  • org.jetbrains.kotlin.plugin.compose 2.0.0
  • com.vanniktech.maven.publish 0.29.0
sample/build.gradle.kts
sonner/gradle.properties
sonner/build.gradle.kts
gradle-wrapper
gradle/wrapper/gradle-wrapper.properties
  • gradle 8.9

  • Check this box to trigger a request for Renovate to run again on this repository

iOS implementation

Hey @dokar3, it's a cool library you've got going on here 👏

As you mentioned in your comment (iOS target. Waiting for contributors because I don't have any Apple devices to run), I can try to help you out here as I have a Macbook. We can test the iOS implementation on an iOS simulator.

Would you like to create a new feature branch containing the iOS implementation that I can test out and give you any kind of feedback you'd like?

The desktop version is built for Java 20

Exception in thread "main" java.lang.UnsupportedClassVersionError: com/dokar/sonner/ToasterStateKt has been compiled by a more recent version of the Java Runtime (class file version 64.0), this version of the Java Runtime only recognizes class file versions up to 61.0

I'm trying to use this in a project that uses Java 17. I'm not ready to update because some of the tooling breaks with 21.

Could you switch from Java 20 to 17?

klib incorrectly contains resources of common source sets

https://youtrack.jetbrains.com/issue/KT-65315/KMP-Composite-compileIosMainKotlinMetadata-fails-with-Could-not-find-included-iOS-dependency#focus=Comments-27-9479402.0-0

resolution

val someResourceFile = ... // can be also a task that generates resources.
kotlin {
    // declared targets 
   sourceSets {
      yourTargetsMain {
          resources.srcDir(someResourceFile)
      }
   }
}

K2 below

/** 
 * Workaround for https://youtrack.jetbrains.com/issue/KT-65315
 * Please remove after upgrade to Kotlin 2.0
 */
tasks.withType(MetadataDependencyTransformationTask::class).configureEach {
    if (kotlinToolingVersion >= KotlinToolingVersion("2.0.0-RC1")) error("Please remove workaround for KT-65315")
    fun File.isValidDependency(): Boolean {
        if (extension != "klib") return true
        val klibManifestEntry = ZipFile(this).getEntry("default/manifest")
        return klibManifestEntry != null
    }

    val transformedLibrariesGetter = MetadataDependencyTransformationTask::class.java
        .getDeclaredMethod("getTransformedLibrariesIndexFile")
    transformedLibrariesGetter.isAccessible = true

    doLast {
        val transformedLibrariesFileProperty = transformedLibrariesGetter.invoke(this) as RegularFileProperty
        val transformedLibrariesFile = transformedLibrariesFileProperty.get().asFile

        val validTransformedLibraries = transformedLibrariesFile
            .readLines()
            .map(::File)
            .filter { it.isValidDependency() }
        transformedLibrariesFile.writeText(
            validTransformedLibraries.joinToString("\n") { it.absolutePath }
        )
    }
}

Dismissing a toast with an `action` when using `listenMany` has a weird animation

toastState.listenMany(
    errorMessages.map { entries ->
        entries.map { entry ->
            Toast(
                id = entry.key,
                message = entry.value.toString(),
                duration = ToasterDefaults.DurationLong,
                action = TextToastAction(
                    text = "Dismiss",
                    onClick = { toastState.dismiss(it.id) }
                )
            )
        }
    }
)

The toast is not equal to itself, because the TextToastAction is created each time. The updateOrShow has a problem in this case. I think showing a toast with the same id should leave it in place. That is, don't check if it's at the end and just always update it in place.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.