Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/runtime/components/Toaster.vue
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ export interface ToasterProps extends Omit<ToastProviderProps, 'swipeDirection'>
* @defaultValue true
*/
portal?: boolean | string | HTMLElement
/**
* Maximum number of toasts to display at once.
* @defaultValue 5
*/
max?: number
class?: any
ui?: Toaster['slots']
}
Expand All @@ -41,11 +46,11 @@ export default {
</script>

<script setup lang="ts">
import { ref, computed, toRef } from 'vue'
import { ref, computed, toRef, provide } from 'vue'
import { ToastProvider, ToastViewport, ToastPortal, useForwardProps } from 'reka-ui'
import { reactivePick } from '@vueuse/core'
import { useAppConfig } from '#imports'
import { useToast } from '../composables/useToast'
import { useToast, toastMaxInjectionKey } from '../composables/useToast'
import { usePortal } from '../composables/usePortal'
import { omit } from '../utils'
import { tv } from '../utils/tv'
Expand All @@ -55,13 +60,16 @@ const props = withDefaults(defineProps<ToasterProps>(), {
expand: true,
portal: true,
duration: 5000,
progress: true
progress: true,
max: 5
})
defineSlots<ToasterSlots>()

const { toasts, remove } = useToast()
const appConfig = useAppConfig() as Toaster['AppConfig']

provide(toastMaxInjectionKey, toRef(() => props.max))

const providerProps = useForwardProps(reactivePick(props, 'duration', 'label', 'swipeThreshold'))
const portalProps = usePortal(toRef(() => props.portal))

Expand Down
9 changes: 6 additions & 3 deletions src/runtime/composables/useToast.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ref, nextTick } from 'vue'
import { ref, nextTick, type InjectionKey, type Ref, inject } from 'vue'
import { useState } from '#imports'
import type { ToastProps, ToastEmits } from '../types'
import type { EmitsToProps } from '../types/utils'
Expand All @@ -8,9 +8,12 @@ export interface Toast extends Omit<ToastProps, 'defaultOpen'>, EmitsToProps<Toa
onClick?: (toast: Toast) => void
}

export const toastMaxInjectionKey: InjectionKey<Ref<number | undefined>> = Symbol('nuxt-ui.toast-max')

export function useToast() {
const toasts = useState<Toast[]>('toasts', () => [])
const maxToasts = 5
const maxToasts = inject(toastMaxInjectionKey, undefined)

const running = ref(false)
const queue: Toast[] = []

Expand All @@ -28,7 +31,7 @@ export function useToast() {

await nextTick()

toasts.value = [...toasts.value, toast].slice(-maxToasts)
toasts.value = [...toasts.value, toast].slice(-(maxToasts?.value ?? 5))
}

running.value = false
Expand Down
Loading