feat(Toast): new component (#50)

This commit is contained in:
Benjamin Canac
2024-04-10 18:22:09 +02:00
committed by GitHub
parent 90f18a3505
commit 3da1e1a518
13 changed files with 566 additions and 12 deletions

View File

@@ -1,4 +1,9 @@
export default defineAppConfig({
toaster: {
position: 'bottom-right' as const,
expand: true,
duration: 60000
},
ui: {
primary: 'sky',
gray: 'cool'

View File

@@ -7,6 +7,8 @@ useHead({
}
})
const appConfig = useAppConfig()
const components = [
'accordion',
'avatar',
@@ -31,6 +33,7 @@ const components = [
'switch',
'tabs',
'textarea',
'toast',
'tooltip'
]
@@ -40,7 +43,7 @@ function upperName (name: string) {
</script>
<template>
<UApp>
<UApp :toaster="appConfig.toaster">
<div class="min-h-screen w-screen flex flex-col items-center justify-center overflow-y-auto">
<UNavigationMenu :links="components.map(component => ({ label: upperName(component), to: `/${component}` }))" class="border-b border-gray-200 dark:border-gray-800 overflow-x-auto px-2" />

124
playground/pages/toast.vue Normal file
View File

@@ -0,0 +1,124 @@
<script setup lang="ts">
import theme from '#build/ui/toaster'
const positions = Object.keys(theme.variants.position)
const { toasts, add, update, remove } = useToast()
const appConfig = useAppConfig()
const count = ref(1)
const last = computed(() => toasts.value[toasts.value.length - 1])
const templates = (id: number) => [{
title: 'Toast',
description: `This is the toast ${id}`
}, {
title: `Toast ${id}`
}, {
description: `This is the toast ${id}`
}, {
title: 'Toast',
description: `This is the toast ${id}`,
icon: 'i-heroicons-rocket-launch'
}, {
title: `Toast ${id}`,
icon: 'i-heroicons-rocket-launch'
}, {
description: `This is the toast ${id}`,
icon: 'i-heroicons-rocket-launch'
}, {
title: 'Toast',
description: `This is the toast ${id}`,
avatar: {
src: 'https://avatars.githubusercontent.com/u/739984?v=4'
}
}, {
title: 'Toast',
description: `This is the toast ${id}`,
avatar: {
src: 'https://avatars.githubusercontent.com/u/739984?v=4'
},
actions: [{
label: 'Action',
click () {
console.log(`Toast ${id} action clicked`)
}
}]
}, {
title: `Toast ${id}`,
icon: 'i-heroicons-rocket-launch',
actions: [{
label: 'Action 1',
color: 'gray' as const,
click () {
console.log(`Toast ${id} action 1 clicked`)
}
}, {
label: 'Action 2',
color: 'black' as const,
click () {
console.log(`Toast ${id} action 2 clicked`)
}
}]
}, {
description: `This is the toast ${id}`,
icon: 'i-heroicons-rocket-launch',
actions: [{
label: 'Action',
color: 'primary' as const,
variant: 'outline' as const,
click () {
console.log(`Toast ${id} action clicked`)
}
}]
}]
function addToast () {
const id = count.value++
const template = templates(id)[Math.floor(Math.random() * templates(id).length)]
add({
id,
...template,
click (toast) {
console.log(`Toast ${toast.id} clicked`)
}
})
}
function updateToast () {
if (!last.value) {
return
}
update(last.value.id, {
title: 'Toast updated',
description: `This is the updated toast ${count.value++}`
})
}
function removeToast () {
if (!last.value) {
return
}
remove(last.value.id)
}
</script>
<template>
<div class="flex flex-col items-center gap-8">
<div>
<URadioGroup v-model="appConfig.toaster.position" :options="positions" />
<UCheckbox v-model="appConfig.toaster.expand" label="Expand" class="mt-1" />
<UInput v-model="appConfig.toaster.duration" label="Duration" type="number" class="mt-1" />
</div>
<div class="flex items-center gap-2">
<UButton label="Add new" color="gray" @click="addToast" />
<UButton label="Update last" color="gray" @click="updateToast" />
<UButton label="Remove last" color="gray" @click="removeToast" />
</div>
</div>
</template>

View File

@@ -1,33 +1,35 @@
<script lang="ts">
import type { ConfigProviderProps, ToastProviderProps, TooltipProviderProps } from 'radix-vue'
import type { ConfigProviderProps, TooltipProviderProps } from 'radix-vue'
import type { ToasterProps } from '#ui/types'
export interface ProviderProps extends ConfigProviderProps {
tooltip?: TooltipProviderProps
toast?: ToastProviderProps
toaster?: ToasterProps | null
}
</script>
<script setup lang="ts">
import { toRef } from 'vue'
import { ConfigProvider, ToastProvider, TooltipProvider, useForwardProps } from 'radix-vue'
import { ConfigProvider, TooltipProvider, useForwardProps } from 'radix-vue'
import { reactivePick } from '@vueuse/core'
import { useId } from '#imports'
import { UToaster } from '#components'
const props = withDefaults(defineProps<ProviderProps>(), {
useId: () => useId()
})
const configProps = useForwardProps(reactivePick(props, 'dir', 'scrollBody', 'useId'))
const tooltipProps = toRef(() => props.tooltip as TooltipProviderProps)
const toastProps = toRef(() => props.toast as ToastProviderProps)
const configProviderProps = useForwardProps(reactivePick(props, 'dir', 'scrollBody', 'useId'))
const tooltipProps = toRef(() => props.tooltip)
const toasterProps = toRef(() => props.toaster)
</script>
<template>
<ConfigProvider v-bind="configProps">
<ConfigProvider v-bind="configProviderProps">
<TooltipProvider v-bind="tooltipProps">
<ToastProvider v-bind="toastProps">
<slot />
</ToastProvider>
<slot />
<UToaster v-if="toaster !== null" v-bind="toasterProps" />
</TooltipProvider>
</ConfigProvider>
</template>

View File

@@ -0,0 +1,106 @@
<script lang="ts">
import { isVNode, type VNode } from 'vue'
import { tv, type VariantProps } from 'tailwind-variants'
import type { ToastRootProps, ToastRootEmits } from 'radix-vue'
import type { AppConfig } from '@nuxt/schema'
import _appConfig from '#build/app.config'
import theme from '#build/ui/toast'
import type { AvatarProps, ButtonProps, IconProps } from '#ui/types'
const appConfig = _appConfig as AppConfig & { ui: { toast: Partial<typeof theme> } }
const toast = tv({ extend: tv(theme), ...(appConfig.ui?.toast || {}) })
type ToastVariants = VariantProps<typeof toast>
export interface ToastProps extends Omit<ToastRootProps, 'asChild' | 'forceMount'> {
title?: string
description?: string | VNode | (() => VNode)
icon?: IconProps['name']
avatar?: AvatarProps
color?: ToastVariants['color']
actions?: (ButtonProps & { click?: () => void })[]
close?: ButtonProps | null
class?: any
ui?: Partial<typeof toast.slots>
}
export interface ToastEmits extends ToastRootEmits { }
</script>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ToastRoot, ToastTitle, ToastDescription, ToastAction, ToastClose, useForwardPropsEmits } from 'radix-vue'
import { reactivePick } from '@vueuse/core'
import { useAppConfig } from '#imports'
import { UIcon, UAvatar } from '#components'
const props = defineProps<ToastProps>()
const emits = defineEmits<ToastEmits>()
const appConfig = useAppConfig()
const rootProps = useForwardPropsEmits(reactivePick(props, 'as', 'defaultOpen', 'duration', 'open', 'type'), emits)
const multiline = computed(() => !!props.title && !!props.description)
const ui = computed(() => tv({ extend: toast, slots: props.ui })({
color: props.color
}))
const el = ref()
const height = ref(0)
onMounted(() => {
if (!el.value) {
return
}
setTimeout(() => {
height.value = el.value.$el.getBoundingClientRect().height
}, 0)
})
defineExpose({
height
})
</script>
<template>
<ToastRoot ref="el" v-bind="rootProps" :class="ui.root({ class: props.class, multiline })" :style="{ '--height': height }">
<UAvatar v-if="avatar" size="2xl" v-bind="avatar" :class="ui.avatar()" />
<UIcon v-else-if="icon" :name="icon" :class="ui.icon()" />
<div :class="ui.wrapper()">
<ToastTitle v-if="title" :class="ui.title()">
{{ title }}
</ToastTitle>
<template v-if="description">
<ToastDescription v-if="isVNode(description)" :as="description" />
<ToastDescription v-else :class="ui.description()">
{{ description }}
</ToastDescription>
</template>
<div v-if="multiline && actions?.length" :class="ui.actions({ multiline: true })">
<ToastAction v-for="(action, index) in actions" :key="index" :alt-text="action.label || 'Action'" as-child @click.stop>
<UButton size="xs" color="white" v-bind="action" />
</ToastAction>
</div>
</div>
<div v-if="(!multiline && actions?.length) || close !== null" :class="ui.actions({ multiline: false })">
<template v-if="!multiline">
<ToastAction v-for="(action, index) in actions" :key="index" :alt-text="action.label || 'Action'" as-child @click.stop>
<UButton size="xs" color="white" v-bind="action" />
</ToastAction>
</template>
<ToastClose as-child>
<UButton v-if="close !== null" :icon="appConfig.ui.icons.close" size="sm" color="gray" variant="link" aria-label="Close" v-bind="close" :class="ui.close()" @click.stop />
</ToastClose>
</div>
<div :class="ui.progress()" />
<div :class="ui.mask()" />
</ToastRoot>
</template>

View File

@@ -0,0 +1,116 @@
<script lang="ts">
import { tv, type VariantProps } from 'tailwind-variants'
import type { ToastProviderProps } from 'radix-vue'
import type { AppConfig } from '@nuxt/schema'
import _appConfig from '#build/app.config'
import theme from '#build/ui/toaster'
const appConfig = _appConfig as AppConfig & { ui: { toaster: Partial<typeof theme> } }
const toaster = tv({ extend: tv(theme), ...(appConfig.ui?.toaster || {}) })
type ToasterVariants = VariantProps<typeof toaster>
export interface ToasterProps extends Omit<ToastProviderProps, 'swipeDirection'> {
position?: ToasterVariants['position']
expand?: boolean
class?: any
ui?: Partial<typeof toaster.slots>
}
</script>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { ToastProvider, ToastViewport, useForwardProps } from 'radix-vue'
import { reactivePick } from '@vueuse/core'
import { useToast } from '#imports'
import { UToast } from '#components'
import { omit } from '#ui/utils'
const props = withDefaults(defineProps<ToasterProps>(), { expand: true })
const providerProps = useForwardProps(reactivePick(props, 'duration', 'label', 'swipeThreshold'))
const { toasts, remove } = useToast()
const swipeDirection = computed(() => {
switch (props.position) {
case 'top-center':
return 'up'
case 'top-right':
case 'bottom-right':
return 'right'
case 'bottom-center':
return 'down'
case 'top-left':
case 'bottom-left':
return 'left'
}
return 'right'
})
const ui = computed(() => tv({ extend: toaster, slots: props.ui })({
position: props.position,
swipeDirection: swipeDirection.value
}))
function onUpdateOpen (value: boolean, id: string | number) {
if (value) {
return
}
remove(id)
}
const hovered = ref(false)
const expanded = computed(() => props.expand || hovered.value)
const refs = ref<{ height: number }[]>([])
const height = computed(() => refs.value.reduce((acc, { height }) => acc + height + 16, 0) - 16)
const frontHeight = computed(() => refs.value[refs.value.length - 1]?.height || 0)
function getOffset (index: number) {
return refs.value.slice(index + 1).reduce((acc, { height }) => acc + height + 16, 0)
}
</script>
<template>
<ToastProvider :swipe-direction="swipeDirection" v-bind="providerProps">
<UToast
v-for="(toast, index) of toasts"
:key="toast.id"
ref="refs"
v-bind="omit(toast, ['id'])"
:data-expanded="expanded"
:data-front="!expanded && index === toasts.length - 1"
:style="{
'--index': (index - toasts.length) + toasts.length,
'--before': toasts.length - 1 - index,
'--offset': getOffset(index),
'--scale': expanded ? '1' : 'calc(1 - var(--before) * var(--scale-factor))',
'--translate': expanded ? 'calc(var(--offset) * var(--translate-factor))' : 'calc(var(--before) * var(--gap))',
'--transform': 'translateY(var(--translate)) scale(var(--scale))'
}"
:class="[ui.base(), {
'cursor-pointer': !!toast.click
}]"
@update:open="onUpdateOpen($event, toast.id)"
@click="toast.click && toast.click(toast)"
/>
<ToastViewport
:data-expanded="expanded"
:class="ui.viewport({ class: props.class })"
:style="{
'--scale-factor': '0.05',
'--translate-factor': position?.startsWith('top') ? '1px' : '-1px',
'--gap': position?.startsWith('top') ? '16px' : '-16px',
'--front-height': `${frontHeight}px`,
'--height': `${height}px`
}"
@mouseenter="hovered = true"
@mouseleave="hovered = false"
/>
</ToastProvider>
</template>

View File

@@ -0,0 +1,59 @@
import type { ToastProps } from '#ui/types'
import { useState } from '#imports'
export interface Toast extends Omit<ToastProps, 'defaultOpen'> {
id: string | number
click?: (toast: Toast) => void
}
export function useToast () {
const toasts = useState<Toast[]>('toasts', () => [])
function add (toast: Partial<Toast>): Toast {
const body = {
id: new Date().getTime().toString(),
open: true,
...toast
}
const index = toasts.value.findIndex((t: Toast) => t.id === body.id)
if (index === -1) {
toasts.value.push(body)
}
toasts.value = toasts.value.slice(-5)
return body
}
function update (id: string | number, toast: Partial<Toast>) {
const index = toasts.value.findIndex((t: Toast) => t.id === id)
if (index !== -1) {
toasts.value[index] = {
...toasts.value[index],
...toast
}
}
}
function remove (id: string | number) {
const index = toasts.value.findIndex((t: Toast) => t.id === id)
if (index !== -1) {
toasts.value[index] = {
...toasts.value[index],
open: false
}
}
setTimeout(() => {
toasts.value = toasts.value.filter((t: Toast) => t.id !== id)
}, 200)
}
return {
toasts,
add,
update,
remove
}
}

View File

@@ -23,4 +23,6 @@ export * from '../components/Slideover.vue'
export * from '../components/Switch.vue'
export * from '../components/Tabs.vue'
export * from '../components/Textarea.vue'
export * from '../components/Toast.vue'
export * from '../components/Toaster.vue'
export * from '../components/Tooltip.vue'

View File

@@ -35,6 +35,23 @@ export function addTemplates (options: ModuleOptions, nuxt: Nuxt) {
to { height: var(--radix-collapsible-content-height); }
}
@keyframes toast-slide-down {
from { transform: var(--transform); }
to { transform: translateY(calc((var(--offset) - var(--height)) * -1px)); }
}
@keyframes toast-slide-up {
from { transform: var(--transform); }
to { transform: translateY(calc((var(--offset) - var(--height)) * 1px)); }
}
@keyframes toast-slide-left {
from { transform: translateX(0) translateY(var(--translate)); }
to { transform: translateX(-100%) translateY(var(--translate)); }
}
@keyframes toast-slide-right {
from { transform: translateX(0) translateY(var(--translate)); }
to { transform: translateX(100%) translateY(var(--translate)); }
}
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
@@ -172,7 +189,11 @@ export function addTemplates (options: ModuleOptions, nuxt: Nuxt) {
let json = JSON.stringify(result, null, 2)
for (const variant of variants) {
json = json.replaceAll(new RegExp(`("${variant}": "[0-9a-z-]+")`, 'g'), '$1 as const')
json = json.replace(new RegExp(`("${variant}": "[^"]+")`, 'g'), '$1 as const')
json = json.replace(new RegExp(`("${variant}": \\[\\s*)((?:"[^"]+",?\\s*)+)(\\])`, 'g'), (_, before, match, after) => {
const replaced = match.replace(/("[^"]+")/g, '$1 as const')
return `${before}${replaced}${after}`
})
}
return `export default ${json}`

View File

@@ -22,4 +22,6 @@ export { default as slideover } from './slideover'
export { default as switch } from './switch'
export { default as tabs } from './tabs'
export { default as textarea } from './textarea'
export { default as toast } from './toast'
export { default as toaster } from './toaster'
export { default as tooltip } from './tooltip'

33
src/theme/toast.ts Normal file
View File

@@ -0,0 +1,33 @@
export default (config: { colors: string[] }) => ({
slots: {
root: 'relative overflow-hidden bg-white dark:bg-gray-900 shadow-lg rounded-lg ring ring-gray-200 dark:ring-gray-800 p-4 flex gap-2.5',
wrapper: 'w-0 flex-1 flex flex-col gap-1',
title: 'text-sm font-medium text-gray-900 dark:text-white',
description: 'text-sm text-gray-500 dark:text-gray-400',
icon: 'shrink-0 size-5',
avatar: 'shrink-0',
actions: 'flex gap-1.5 shrink-0',
progress: 'absolute inset-0 rounded-lg border-b-2 z-[-1]',
mask: 'absolute top-0 inset-0 bottom-[2px] bg-white dark:bg-gray-900 z-[-1]',
close: 'p-1'
},
variants: {
color: Object.fromEntries(config.colors.map((color: string) => [color, {
icon: `text-${color}-500 dark:text-${color}-400`,
progress: `border-${color}-500 dark:border-${color}-400`
}])),
multiline: {
true: {
root: 'items-start',
actions: 'items-start mt-1'
},
false: {
root: 'items-center',
actions: 'items-center'
}
}
},
defaultVariants: {
color: 'primary'
}
})

56
src/theme/toaster.ts Normal file
View File

@@ -0,0 +1,56 @@
export default {
slots: {
viewport: 'fixed flex flex-col w-[calc(100%-2rem)] sm:w-96 z-[100] data-[expanded=true]:h-[--height]',
base: 'absolute inset-x-0 z-[--index] transform-[--transform] data-[expanded=false]:data-[front=false]:h-[--front-height] data-[expanded=false]:data-[front=false]:*:invisible data-[swipe=move]:transition-none transition-[transform,height] will-change-[transform,height] duration-200 ease-out'
},
variants: {
position: {
'top-left': {
viewport: 'left-4'
},
'top-center': {
viewport: 'left-1/2 transform -translate-x-1/2'
},
'top-right': {
viewport: 'right-4'
},
'bottom-left': {
viewport: 'left-4'
},
'bottom-center': {
viewport: 'left-1/2 transform -translate-x-1/2'
},
'bottom-right': {
viewport: 'right-4'
}
},
swipeDirection: {
up: 'data-[swipe=end]:animate-[toast-slide-up_200ms_ease-out]',
right: 'data-[swipe=end]:animate-[toast-slide-right_200ms_ease-out]',
down: 'data-[swipe=end]:animate-[toast-slide-down_200ms_ease-out]',
left: 'data-[swipe=end]:animate-[toast-slide-left_200ms_ease-out]'
}
},
compoundVariants: [{
position: ['top-left', 'top-center', 'top-right'],
class: {
viewport: 'top-4',
base: 'top-0 data-[state=open]:animate-[slide-in-from-top_200ms_ease-in-out] data-[state=closed]:animate-[toast-slide-up_200ms_ease-in-out]'
}
}, {
position: ['bottom-left', 'bottom-center', 'bottom-right'],
class: {
viewport: 'bottom-4',
base: 'bottom-0 data-[state=open]:animate-[slide-in-from-bottom_200ms_ease-in-out] data-[state=closed]:animate-[toast-slide-down_200ms_ease-in-out]'
}
}, {
swipeDirection: ['left', 'right'],
class: 'data-[swipe=move]:translate-x-[--radix-toast-swipe-move-x] data-[swipe=end]:translate-x-[--radix-toast-swipe-end-x] data-[swipe=cancel]:translate-x-0'
}, {
swipeDirection: ['up', 'down'],
class: 'data-[swipe=move]:translate-y-[--radix-toast-swipe-move-y] data-[swipe=end]:translate-y-[--radix-toast-swipe-end-y] data-[swipe=cancel]:translate-y-0'
}],
defaultVariants: {
position: 'bottom-right'
}
}

View File

@@ -0,0 +1,25 @@
import { defineComponent } from 'vue'
import { describe, it, expect } from 'vitest'
import App from '../../src/runtime/components/App.vue'
import Toast, { type ToastProps } from '../../src/runtime/components/Toast.vue'
import ComponentRender from '../component-render'
const ToastWrapper = defineComponent({
components: {
UApp: App,
UToast: Toast
},
inheritAttrs: false,
template: '<UApp><UToast v-bind="$attrs" /></UApp>'
})
describe('Toast', () => {
it.each([
['basic case', {}],
['with class', { props: { class: '' } }],
['with ui', { props: { ui: {} } }]
])('renders %s correctly', async (nameOrHtml: string, options: { props?: ToastProps, slots?: any }) => {
const html = await ComponentRender(nameOrHtml, options, ToastWrapper)
expect(html).toMatchSnapshot()
})
})