Toast (토스트)
토스트는 일시적으로 표시되는 간결한 메시지예요. 작업이 성공했음을 알리거나 오류를 안내할 때 화면 일부에 잠깐 나타났다가 사라지는 알림 형태입니다.
출처: 문서
본문
Import (불러오기)
import { Toast, toaster } from "@kobalte/core/toast";
// or
import { Root, toaster, ... } from "@kobalte/core/toast";
// or (deprecated)
import { Toast, toaster } from "@kobalte/core";
Features (기능)
- 자동으로 닫혀요.
- 호버(hover), 포커스, 창이 흐려질 때 닫힘을 일시 중지해요.
- 토스트 영역으로 점프하는 단축키를 지원해요.
- 스와이프 제스처로 닫기를 지원해요.
- 스와이프 제스처 애니메이션을 위한 CSS 변수를 제공해요.
- 표시할 토스트의 개수를 제한할 수 있어요.
- 토스트 안에서 promise를 관리할 수 있어요.
- 토스트를 프로그래밍 방식으로 제거하거나 업데이트할 수 있어요.
- 여러 개의 토스트 영역을 지원해요.
Anatomy (구조)
토스트 영역(region)은 다음의 부분들로 이루어져요:
- Toast.Region: 토스트가 나타나는 고정된 영역이에요. 사용자는 단축키를 눌러 뷰포트로 점프할 수 있어요.
- Toast.List: 렌더링된 모든 토스트를 담는 목록이에요.
<Toast.Region>
<Toast.List />
</Toast.Region>
토스트는 다음의 부분들로 이루어져요:
- Toast: 토스트의 루트 컨테이너예요.
- Toast.CloseButton: 토스트를 닫는 버튼이에요.
- Toast.Title: 토스트가 열릴 때 알려주는 접근 가능한 제목이에요.
- Toast.Description: 토스트가 열릴 때 알려주는 선택적 접근 가능한 설명이에요.
- Toast.ProgressTrack: 토스트의 수명을 시각적으로 나타내는 컴포넌트예요.
- Toast.ProgressFill: 토스트의 남은 수명을 시각적으로 나타내는 컴포넌트예요.
<Toast>
<Toast.CloseButton />
<Toast.Title />
<Toast.Description />
<Toast.ProgressTrack>
<Toast.ProgressFill />
</Toast.ProgressTrack>
</Toast>
Example (예제)
기본 예제를 통해 토스트의 구조와 스타일링 방식을 확인해 보세요. 인터랙티브한 미리보기는 출처 문서에서 직접 확인할 수 있어요.
Usage (사용법)
Showing a toast (토스트 표시하기)
토스트를 만들려면 toaster.show() 메서드를 사용하고, 생성된 toastId를 Toast.Root에 전달하세요.
const id = toaster.show(props => <Toast toastId={props.toastId}>...</Toast>);
Updating a toast (토스트 업데이트하기)
toaster.update() 메서드를 사용하면 토스트 id와 렌더링할 새 컴포넌트를 제공해 토스트를 업데이트할 수 있어요.
toaster.update(id, props => <Toast toastId={props.toastId}>...</Toast>);
참고: 항상
toastId를Toast에 전달해야 해요.Toast는toaster나 자신이 표현해야 하는 토스트에 대해 아무것도 알지 못하기 때문입니다.
Dismissing a toast (토스트 닫기)
toaster.dismiss() 메서드를 사용하면 토스트 id를 제공해 토스트를 닫을 수 있어요.
toaster.dismiss(id);
Clearing the toast stack and queue (스택과 큐 비우기)
toaster.clear() 메서드를 사용하면 모든 토스트를 닫아요.
toaster.clear();
Handling promises (promise 처리)
toaster API는 toaster.promise() 메서드를 제공하여 promise가 resolve되거나 reject될 때 토스트를 업데이트할 수 있게 해줘요.
toastId 외에도 props에는 다음 속성들이 포함됩니다:
- state: promise의 상태로,
"pending" | "fulfilled" | "rejected"일 수 있어요. - data: promise가 fulfilled일 때 반환된 데이터(있다면)예요.
- error: promise가 rejected일 때 반환된 오류(있다면)예요.
toaster.promise(promise, props => (
<Toast toastId={props.toastId}>
<Switch>
<Match when={props.state === "pending"}>Loading</Match>
<Match when={props.state === "fulfilled"}>{props.data}</Match>
<Match when={props.state === "rejected"}>{props.error}</Match>
</Switch>
</Toast>
));
Pausing the toasts (토스트 일시 중지)
Toast.Region 컴포넌트는 포함된 토스트를 일시 중지하기 위해 다음 prop을 노출해요.
pauseOnInteractionprop은 토스트가 호버되거나 포커스될 때 닫힘 타임아웃을 일시 중지해요.pauseOnPageIdleprop은 문서가 포커스를 잃거나 페이지가 유휴 상태일 때(예: 새 브라우저 탭으로 전환) 닫힘 타임아웃을 일시 중지해요.
<Toast.Region pauseOnPageIdle pauseOnInteraction>
<Toast.List />
</Toast.Region>
Limiting the number of visible toasts (표시할 토스트 개수 제한)
Toast.Region의 limit prop을 사용하면 동시에 표시할 토스트의 개수를 제한할 수 있어요. 제한에 도달한 뒤 추가된 모든 토스트는 큐에 들어가고, 표시된 토스트가 닫히면 표시돼요.
<Toast.Region limit={3}>
<Toast.List />
</Toast.Region>
Progress bar fill width (진행 막대 채움 너비)
토스트의 남은 수명(백분율)에 해당하는 CSS 사용자 지정 속성 --kb-toast-progress-fill-width를 제공해요. 토스트 지속 시간을 보여주는 선형 진행 막대를 만들고 있다면, 이 값을 사용해 CSS에서 Toast.ProgressFill 컴포넌트의 너비를 설정할 수 있어요.
/* style.css*/
.toast__progress-fill {
background-color: hsl(200 98% 39%);
border-radius: 3px;
height: 100%;
width: var(--kb-toast-progress-fill-width);
transition: width 250ms linear;
}
Animating swipe gesture (스와이프 제스처 애니메이션)
CSS 사용자 지정 속성 --kb-toast-swipe-move-[x|y]와 --kb-toast-swipe-end-[x|y]를 제공하며, data-swipe="[start|move|cancel|end]" 속성과 함께 사용해 닫기 위한 스와이프 제스처를 애니메이션할 수 있어요.
// index.tsx
import { Toast, toaster } from "@kobalte/core/toast";
import "./style.css";
function App() {
const showToast = () => {
toaster.show(props => (
<Toast toastId={props.toastId} class="toast">
...
</Toast>
));
};
return (
<>
<button onClick={showToast}>Show toast</button>
<Portal>
<Toast.Region swipeDirection="right">
<Toast.List />
</Toast.Region>
</Portal>
</>
);
}
/* style.css */
.toast[data-swipe="move"] {
transform: translateX(var(--kb-toast-swipe-move-x));
}
.toast[data-swipe="cancel"] {
transform: translateX(0);
transition: transform 200ms ease-out;
}
.toast[data-swipe="end"] {
animation: slideRight 100ms ease-out;
}
@keyframes slideRight {
from {
transform: translateX(var(--kb-toast-swipe-end-x));
}
to {
transform: translateX(100%);
}
}
Abstracting the toaster API (toaster API 추상화)
토스트 라이브러리에서는 성공이나 오류 같은 다양한 타입의 토스트를 표시하는 메서드를 두는 것이 흔해요. Kobalte에서는 아래처럼 toaster API를 추상화하여 이렇게 할 수 있어요.
// toast.tsx
import { Toast, toaster } from "@kobalte/core/toast";
import { JSX } from "solid-js/jsx-runtime";
import { Switch, Match } from "solid-js/web";
function show(message: string) {
return toaster.show(props => (
<Toast toastId={props.toastId} class="toast">
{message}
</Toast>
));
}
function success(message: string) {
return toaster.show(props => (
<Toast toastId={props.toastId} class="toast toast--success">
{message}
</Toast>
));
}
function error(message: string) {
return toaster.show(props => (
<Toast toastId={props.toastId} class="toast toast--error">
{message}
</Toast>
));
}
function promise<T, U>(
promise: Promise<T> | (() => Promise<T>),
options: {
loading?: JSX.Element;
success?: (data: T) => JSX.Element;
error?: (error: U) => JSX.Element;
},
) {
return toaster.promise(promise, props => (
<Toast
toastId={props.toastId}
classList={{
toast: true,
"toast-loading": props.state === "pending",
"toast-success": props.state === "fulfilled",
"toast-error": props.state === "rejected",
}}
>
<Switch>
<Match when={props.state === "pending"}>{options.loading}</Match>
<Match when={props.state === "fulfilled"}>{options.success?.(props.data)}</Match>
<Match when={props.state === "rejected"}>{options.error?.(props.error)}</Match>
</Switch>
</Toast>
));
}
function custom(jsx: () => JSX.Element) {
return toaster.show(props => <Toast toastId={props.toastId}>{jsx}</Toast>);
}
function dismiss(id: number) {
return toaster.dismiss(id);
}
export const toast = {
show,
success,
error,
promise,
custom,
dismiss,
};
그런 다음 애플리케이션 안에서 자신만의 toast API를 사용하세요:
// App.tsx
import { toast } from "./toast";
function App() {
const showToast = () => {
toast.success("Event has been created");
};
return (
<>
<button onClick={showToast}>Show toast</button>
<Portal>
<Toast.Region>
<Toast.List />
</Toast.Region>
</Portal>
</>
);
}
Multiple regions (여러 영역)
toaster.show()의 region 옵션을 사용하면 동시에 여러 영역에 토스트를 표시할 수 있어요. region을 제공하지 않으면 기본 영역이 사용됩니다.
toaster.show(props => <Toast toastId={props.toastId}>...</Toast>, {
region: "custom-region-id",
});
애플리케이션 안에서 사용자 지정 영역을 추가하세요:
<Portal>
{/* Default region */}
<Toast.Region>
<Toast.List />
</Toast.Region>
<Toast.Region regionId="custom-region-id">
<Toast.List />
</Toast.Region>
</Portal>
API reference (API 참조)
toaster
| Method | Description |
|---|---|
| show | (toastComponent: ToastComponent, options?: ShowToastOptions) => number Adds a new toast to the visible toasts or queue depending on current state, region and limit, and return the id of the created toast. |
| update | (id: number, toastComponent: ToastComponent) => void Update the toast of the given id with a new rendered component. |
| promise | (promise: Promise<T> | (() => Promise<T>), toastComponent: ToastPromiseComponent<T, U>, options?: ShowToastOptions) => number Adds a new promise-based toast to the visible toasts or queue depending on current state and limit, and return the id of the created toast. |
| dismiss | (id: number) => void Removes toast with given id from visible toasts and queue. |
| clear | () => void Removes all toasts from visible toasts and queue. |
Toast.Region
| Prop | Description |
|---|---|
| aria-label | string default: "Notifications ({hotkey})" A label for the toast region to provide context for screen reader users when navigating page landmarks. Can contain a {hotkey} placeholder which will be replaced for you. |
| hotkey | string[] default: alt + T The keys to use as the keyboard shortcut that will move focus to the toast region. Use event.code value for each key from keycode.info. For meta keys, use ctrlKey, shiftKey, altKey and/or metaKey. |
| duration | number default: 5000 The time in milliseconds that should elapse before automatically closing each toast. |
| limit | number default: 3 The maximum amount of toasts that can be displayed at the same time. |
| swipeDirection | "up" | "down" | "left" | "right" default: "right" The direction of the pointer swipe that should close the toast. |
| swipeThreshold | number default: 50 The distance in pixels that the swipe gesture must travel before a close is triggered. |
| pauseOnInteraction | boolean default: true Whether the toasts close timeout should pause when a toast is hovered or focused. |
| pauseOnPageIdle | boolean default: true Whether the toasts close timeout should pause when the document loses focus or the page is idle (e.g. switching to a new browser tab). |
| topLayer | boolean default: true Whether the toast region is marked as a "top layer", so that it: - is not aria-hidden when opening an overlay. - allows focus even outside a containing focus scope. - doesn't dismiss overlays when clicking on it, even though it is outside. |
| regionId | string The custom id of the region used for multiple regions. |
| translations | ToastRegionIntlTranslations Localization strings. |
Toast
Toast는 @kobalte/core/toast의 Root 임포트(그리고 더 이상 사용되지 않는 Toast.Root)와 동일해요.
| Prop | Description |
|---|---|
| toastId | number The id of the toast provided by the toaster. |
| priority | "high" | "low" default: "high" Control the sensitivity of the toast for accessibility purposes. For toasts that are the result of a user action, choose high. Toasts generated from background tasks should use low. |
| duration | number The time in milliseconds that should elapse before automatically closing the toast. This will override the value supplied to Toast.Region. |
| persistent | boolean Whether the toast should ignore duration and disappear only by a user action. |
| onPause | () => void Event handler called when the dismiss timer is paused. This occurs when the pointer is moved over the region or the region is focused. |
| onResume | () => void Event handler called when the dismiss timer is resumed. This occurs when the pointer is moved away from the region or the region is blurred. |
| onSwipeStart | (event: SwipeEvent) => voidEvent handler called when starting a swipe interaction. |
| onSwipeMove | (event: SwipeEvent) => void Event handler called during a swipe interaction. |
| onSwipeCancel | (event: SwipeEvent) => void Event handler called when a swipe interaction is cancelled. |
| onSwipeEnd | (event: SwipeEvent) => void Event handler called at the end of a swipe interaction. |
| onEscapeKeyDown | (event: KeyboardEvent) => void Event handler called when the escape key is down. It can be prevented by calling event.preventDefault. |
| translations | ToastIntlTranslations Localization strings. |
| Data attribute | Description |
|---|---|
| data-opened | Present when the toast is open. |
| data-closed | Present when the toast disappear. |
| data-swipe | The state of the swipe, can be "start" | "move" | "cancel" | "end". |
| data-swipe-direction | The direction of the pointer swipe that should close the toast. |
| CSS custom property | Description |
|---|---|
| --kb-toast-swipe-move-x | The offset position of the toast when horizontally swiping. |
| --kb-toast-swipe-move-y | The offset position of the toast when vertically swiping. |
| --kb-toast-swipe-end-x | The offset end position of the toast after horizontally swiping. |
| --kb-toast-swipe-end-y | The offset end position of the toast after vertically swiping. |
Rendered elements (렌더링되는 요소)
| Component | Default rendered element |
|---|---|
Toast |
li |
Toast.CloseButton |
button |
Toast.Title |
div |
Toast.Description |
div |
Toast.ProgressTrack |
div |
Toast.ProgressFill |
div |
Toast.Region |
div |
Toast.List |
ol |
Accessibility (접근성)
Keyboard Interactions (키보드 상호작용)
| Key | Description |
|---|---|
| Alt + T | Focuses toasts region. |
| Tab | Moves focus to the next focusable element. |
| Shift + Tab | Moves focus to the previous focusable element. |
| Space | When focus is on a Toast.CloseButton, closes the toast. |
| Enter | When focus is on a Toast.CloseButton, closes the toast. |
| Esc | When focus is on a toast, closes the toast. |
더 알아보기 (Learn more)
- Kobalte 시작하기 — 프로젝트 설정
- Themes 컴포넌트 — 토스트 스타일링 문서