Feedback · Toast

Toast

Toast component is used to give timely feedback to user's operations. It could be the result feedback of the operation, such as success, failure, error, warning, etc.

Demos

How to import

<script setup lang="ts">
    import { Toast } from '@fibrous/semi-ui-vue';
</script>

The static methods render outside the component tree. Optionally call app.use(Toast): static toasts then render with that app's context, so they can read the values from app.provide() and globally registered components. The static methods of Toast, Notification and Modal share this record, so installing any one of them covers all three; with several apps installed, the last one wins.

Basic Usage

Calling Toast's related methods to show timely feedback to user's operations. It is recommended to set the stack property to apply the stacking style to multiple Toasts on the same screen, and expand them by hovering, which can effectively prevent multiple parallel Toasts at one time.



Code
<script setup lang="ts">
    import { throttle } from 'es-toolkit';
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    const opts = {
        content: 'Hi, Bytedance dance dance',
        duration: 3,
        stack: true,
    };
    const throttleOpts = {
        content: 'Hi, Bytedance dance dance',
        duration: 10,
        onClose: () => throttled.cancel(),
        stack: true,
    };
    const throttled = throttle(() => Toast.info(throttleOpts), 10000, { edges: ['leading'] });
</script>

<template>
    <div>
        <Button @click="Toast.info(opts)">Display Toast</Button>
        <br />
        <br />
        <Button @click="throttled">Throttled Toast</Button>
    </div>
</template>

Other Types

Use different methods to show different Toast including success, warning, error and info.





Code
<script setup lang="ts">
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    const opts = {
        content: 'Hi, Bytedance dance dance',
        duration: 3,
    };
</script>

<template>
    <Button style="color: var(--semi-color-success)" @click="Toast.success('Hi,Bytedance dance dance')"> Success </Button>
    <br />
    <br />
    <Button type="warning" @click="Toast.warning(opts)">Warning</Button>
    <br />
    <br />
    <Button type="danger" @click="Toast.error(opts)">Error</Button>
</template>

Colored Background

You could use theme for a colored background style. Default is normal.







Code
<script setup lang="ts">
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    const opts = {
        content: 'Hi, Bytedance dance dance',
        duration: 3,
        theme: 'light',
    } as const;
</script>

<template>
    <Button @click="Toast.info(opts)">Info</Button>
    <br />
    <br />
    <Button style="color: var(--semi-color-success)" @click="Toast.success(opts)">Success</Button>
    <br />
    <br />
    <Button type="warning" @click="Toast.warning(opts)">Warning</Button>
    <br />
    <br />
    <Button type="danger" @click="Toast.error(opts)">Error</Button>
</template>

Stacking styles

With stack, the Toasts on screen stack once there are more than the threshold, and expand on hover. true sets the threshold to 3, and a number sets a custom one; a stack shows its front 3 layers only.

Code
<script setup lang="ts">
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    const opts = {
        content: 'Hi, Bytedance dance dance',
        duration: 10,
        stack: true,
    };
</script>

<template>
    <Button @click="Toast.info(opts)">多次点击</Button>
</template>

Informational feedback

content and icon accept a string, a VNode or a function returning VNodeChild; the Typography texts below are built as VNodes with h().

Delay

Use duration to set up time delay. By default it closes after 3 seconds.

Code
<script setup lang="ts">
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    const opts = {
        content: 'Hi, Bytedance dance dance',
        duration: 10,
    };
</script>

<template>
    <Button @click="Toast.info(opts)">Close After 10s</Button>
</template>

Manual Close

Set duration to 0 if you do not want the Toast to close by itself. In this case, it could only be closed manually.



Code
<script setup lang="ts">
    import { ref } from 'vue';
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    const toastId = ref<string | null>(null);

    function destroy() {
        toastId.value = null;
    }

    const opts = {
        content: 'Not auto close',
        duration: 0,
        onClose: destroy,
    };

    function show() {
        if (toastId.value) {
            return;
        }
        toastId.value = Toast.info(opts);
    }

    function hide() {
        if (toastId.value) {
            Toast.close(toastId.value);
        }
        destroy();
    }
</script>

<template>
    <Button type="primary" @click="show">Show Toast</Button>
    <br />
    <br />
    <Button type="primary" @click="hide">Hide Toast</Button>
</template>

Update Toast Content

Use unique Toast id to update toast content.

Code
<script setup lang="ts">
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    function show() {
        const id = 'toastid';
        Toast.info({ content: 'Update Content By Id', id });
        setTimeout(() => {
            Toast.success({ content: 'Id By Content Update', id });
        }, 1000);
    }
</script>

<template>
    <Button type="primary" @click="show">Update Content By Id</Button>
</template>

Destroy all

Globally Destroy:

  • Toast.destroyAll()

Consume Context

You could use Toast.useToast() to create a Holder that could access context. Created toast will be inserted to where <Holder /> is placed and inherits the provides, ConfigProvider and locale there.

Toast.useToast() returns the tuple [toast, Holder]: info, success, warning, error and open of the toast object take the Options without type and id and return the toastId; close(toastId) closes one manually. A function passed as content or icon is rendered as a functional component inside the toast, so it can inject. Positioning options such as top, zIndex and getPopupContainer have no effect in the hook. ConfigProvider and LocaleProvider provide at component level, which the static Toast cannot read; use useToast() when you need them.

Code
<script setup lang="ts">
    import { inject, provide, type InjectionKey } from 'vue';
    import { Button, Toast } from '@fibrous/semi-ui-vue';

    const reachableKey: InjectionKey<string> = Symbol('reachable');
    provide(reachableKey, 'Light');

    const [toast, Holder] = Toast.useToast();
    // The function is rendered as a functional component inside the toast, so it can inject from where Holder sits
    const config = {
        duration: 0,
        content: () => `ReachableContext: ${inject(reachableKey)}`,
    };
</script>

<template>
    <div>
        <Button @click="toast.success(config)">Hook Toast</Button>
    </div>
    <Holder />
</template>

Create Toast with different configurations

  • ToastFactory.create(config) => Toast
    If you need Toast with different configs in your application, you can use ToastFactory.create(config)to create a new Toast:


custom container
Code
<script setup lang="ts">
    import { onBeforeUnmount } from 'vue';
    import { Button, Toast, ToastFactory } from '@fibrous/semi-ui-vue';

    const ToastInCustomContainer = ToastFactory.create({
        getPopupContainer: () => document.getElementById('custom-toast-container') as HTMLElement,
    });
    onBeforeUnmount(() => ToastInCustomContainer.destroyAll());
</script>

<template>
    <div>
        <Button @click="Toast.info('Toast')">Default Toast</Button>
        <br />
        <br />
        <Button @click="ToastInCustomContainer.info('Toast in some container')">Toast in custom container</Button>
        <div id="custom-toast-container">custom container</div>
    </div>
</template>

API Reference

The static methods provided are as follows: Display: You can pass in options object or string directly. Methods return the value of toastId: const toastId = Toast.info({ /*...options*/ })

The global configuration is set before any method call, and takes effect only once

  • Toast.config(config)
  • Toast.resetConfig() restores the global configuration to its defaults; only toasts shown afterwards are affected. An instance created by ToastFactory.create(config) is restored to the config it was created with

Show Toast Directly

  • Toast.info(options || string)
  • Toast.error(options || string)
  • Toast.warning(options || string)
  • Toast.success(options || string)

info error warning success return the toastId, can be used for manually closing

  • Toast.close(toastId) Close Manually

Options

Toast Options supports the following APIs as well as the APIs in Config

PropertiesInstructionstypeDefault
contentToast content; a function is rendered as a functional component inside the toast and can injectstring | VNode | (() => VNodeChild)''
iconCustom iconsstring | VNode | (() => VNodeChild)
showCloseToggle Whether show close buttonbooleantrue
textMaxWidthMaximum width of contentnumber | string450
onCloseCallback function when closing toast() => void
stackStack the Toasts on screen once there are more than this many; true means 3, false never stacksboolean | numberfalse
idCustom ToastIdstring
motionWhether to animate entering and leavingbooleantrue
classClass namestring | object | array
styleInline styleStyleValue

Undeclared options such as data-* land on .semi-toast, in stack mode too.

Config

The following API supports global configuration to change the default configuration of the current Toast

PropertiesInstructionstypeDefault
bottomPop-up position bottomnumber | string-
leftPop-up position leftnumber | string-
rightPop-up position rightnumber | string-
topPop-up position topnumber | string-
zIndexZ-index valuenumber1010
themeStyle of background fill, one of light, normalstringnormal
durationAutomatic close delay, no auto-close when set to 0number3
getPopupContainerSpecifies the parent DOM, and the bullet layer will be rendered to the DOM, you need to set container and inner .semi-toast-wrapper 'position: relative` This will change the DOM tree position, but not the view's rendering position.() => HTMLElement() => document.body

Accessibility

ARIA

  • The role of Toast depends on its type: alert for warning and error, status for info, success and a Toast without type
  • status Toasts are read by a persistent aria-live="polite" region owned by the list; the Toast itself is aria-live="off", and only the text of content is announced. warning and error still announce themselves as alert

Keyboard and Focus

  • The close button is a native button: focus it with Tab, and activate it with Enter or Space
  • A Toast does not take focus when it appears
  • When the pointer or keyboard focus enters a Toast, its auto-close timer pauses and a stack expands; both resume when it leaves

Content Guidelines

Ticket transferred
  • Keep it simple
  • Do not use periods at the end of sentences
  • Explain using the noun + verb format
✅ Recommended usage❌ Deprecated usage
Language addedNew language has been added successfully
Ticket transfer failedCan't transfer ticket
  • Provide prompt message for action
    • only provide one action
    • Don't use actions like "read" like OK, Got it, Dismiss, Cancel
✅ Recommended usage❌ Deprecated usage

Design Tokens

These are the component's internal Sass variables and cannot be overridden. To customize styles, override the --semi-* CSS variables (see the Design Token page) or write unlayered CSS rules.
Sass variableValueUsage
$animation_duration-toast-show300ms
$animation_duration-toast-hide300ms
$animation_function-toast-showcubic-bezier(0.22, 0.57, 0.02, 1.2)
$animation_function-toast-hidecubic-bezier(0.22, 0.57, 0.02, 1.2)
$animation_delay-toast-show0s
$animation_delay-toast-hide0s
$animation_opacity-toast-show0
$animation_opacity-toast-hide0
$animation_transform_translateY-toast-show-100%
$animation_transform_translateY-toast-hide-100%
$animation_duration-toast-stack300ms
$animation_function-toast-stackcubic-bezier(0.22, 0.57, 0.02, 1.2)
$color-toast-bg-defaultvar(--semi-color-bg-3)提示背景颜色 - 默认
$color-toast-text-defaultvar(--semi-color-text-0)提示文字颜色 - 默认
$color-toast_warning-iconvar(--semi-color-warning)警告提示图标颜色
$color-toast_success-iconvar(--semi-color-success)成功提示图标颜色
$color-toast_info-iconvar(--semi-color-info)通知提示图标颜色
$color-toast_danger-iconvar(--semi-color-danger)错误提示图标颜色
$color-toast_warning_light-bgvar(--semi-color-warning-light-default)多色样式 警告提示背景颜色
$color-toast_warning_light-icon$color-toast_warning-icon多色样式 警告提示图标颜色
$color-toast_warning_light-bordervar(--semi-color-warning)多色样式 警告提示描边颜色
$color-toast_success_light-bgvar(--semi-color-success-light-default)多色样式 成功提示背景颜色
$color-toast_success_light-icon$color-toast_success-icon多色样式 成功提示图标颜色
$color-toast_success_light-bordervar(--semi-color-success)多色样式 成功提示描边颜色
$color-toast_info_light-bgvar(--semi-color-info-light-default)多色样式 通知提示背景颜色
$color-toast_info_light-icon$color-toast_info-icon多色样式 通知提示图标颜色
$color-toast_info_light-bordervar(--semi-color-info)多色样式 通知提示描边颜色
$color-toast_danger_light-bgvar(--semi-color-danger-light-default)多色样式 错误提示背景颜色
$color-toast_danger_light-icon$color-toast_danger-icon多色样式 错误提示图标颜色
$color-toast_danger_light-bordervar(--semi-color-danger)多色样式 错误提示描边颜色
$spacing-toast_wrapper-top0通知容器顶部位置
$spacing-toast_content-paddingY$spacing-base-tight通知内容垂直内边距
$spacing-toast_content-paddingX$spacing-tight通知内容水平内边距
$spacing-toast_content-paddingTop$spacing-toast_content-paddingY通知内容 top 内边距
$spacing-toast_content-paddingBottom$spacing-toast_content-paddingY通知内容 bottom 内边距
$spacing-toast_content-paddingLeft$spacing-toast_content-paddingX通知内容 left 内边距
$spacing-toast_content-paddingRight$spacing-toast_content-paddingX通知内容 right 内边距
$spacing-toast_content-margin$spacing-base-tight通知内容外边距
$spacing-toast_content_close_btn-marginTop-2px通知关闭按钮顶部外边距
$spacing-toast_content_text-marginLeft$spacing-base-tight通知文本左侧外边距
$spacing-toast_content_text-marginRight$spacing-base-tight通知文本右侧外边距
$spacing-toast-perspective-originY280px通知透视原点 Y 轴位置
$spacing-toast-perspective280px通知透视距离
$width-toast_wrapper100%通知容器整体宽度
$width-toast_light-border1px多色样式 通知描边宽度
$radius-toast_contentvar(--semi-border-radius-medium)通知圆角
$font-toast_content-fontWeight$font-weight-bold通知文本字重