탐색

v2.1.0
피드백

토스트

페이지 위에 잠깐 표시되며 자동으로 사라질 수 있는 메시지입니다.

이 페이지의 내용

토스트는 저장, 배포, 복사처럼 방금 일어난 일이나, 진행 중이며 끝나면 결과를 알려 줄 작업을 페이지 위에 잠깐 알리는 메시지입니다. 각 토스트는 고정 배치된 toast-region 안에 있는 비모달 <dialog>입니다. 대화 상자이므로 스크립트 없이 닫을 수 있으며, 나타나고 사라지는 동작은 스타일시트에서 CSS로 정의합니다.

토스트

<div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast toast-success" aria-labelledby="toast-deployed">    <svg class="icon toast-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">      <circle cx="8" cy="8" r="6" /><path d="M5 8L7.1041 9.8703A0.2 0.2 0 0 0 7.3832 9.8573L10.75 6.25" />    </svg>    <div class="toast-body">      <p class="toast-title" id="toast-deployed">Deployed to production</p>      <p class="toast-description">atlas.dev is live in 14 regions.</p>    </div>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M4 4L12 12" /><path d="M4 12L12 4" />        </svg>      </button>    </form>  </dialog></div>
import CheckCircleIcon from '@master/icons-react/native/16/soft/check-circle'import XIcon from '@master/icons-react/native/16/soft/x'<div className="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open className="toast toast-success" aria-labelledby="toast-deployed">    <CheckCircleIcon className="icon toast-icon" />    <div className="toast-body">      <p className="toast-title" id="toast-deployed">Deployed to production</p>      <p className="toast-description">atlas.dev is live in 14 regions.</p>    </div>    <form method="dialog" className="toast-close">      <button className="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon className="icon" />      </button>    </form>  </dialog></div>
<script>  import CheckCircleIcon from '@master/icons-svelte/native/16/soft/check-circle'  import XIcon from '@master/icons-svelte/native/16/soft/x'</script><div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast toast-success" aria-labelledby="toast-deployed">    <CheckCircleIcon class="icon toast-icon" />    <div class="toast-body">      <p class="toast-title" id="toast-deployed">Deployed to production</p>      <p class="toast-description">atlas.dev is live in 14 regions.</p>    </div>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon class="icon" />      </button>    </form>  </dialog></div>
<script setup>import CheckCircleIcon from '@master/icons-vue/native/16/soft/check-circle'import XIcon from '@master/icons-vue/native/16/soft/x'</script><template>  <div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">    <dialog open class="toast toast-success" aria-labelledby="toast-deployed">      <CheckCircleIcon class="icon toast-icon" />      <div class="toast-body">        <p class="toast-title" id="toast-deployed">Deployed to production</p>        <p class="toast-description">atlas.dev is live in 14 regions.</p>      </div>      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">          <XIcon class="icon" />        </button>      </form>    </dialog>  </div></template>
토스트의 버튼을 눌러 닫으세요. 스크립트는 사용하지 않습니다.

#표시 및 닫기

  • open 속성이 있는 토스트는 페이지가 로드될 때 표시됩니다. 양식이 POST로 제출된 뒤 서버에서 렌더링하는 메시지에 적합합니다.
  • 스크립트에서는 영역에 새 <dialog open class="toast">를 추가하거나, 영역 안에 있는 토스트에 open을 설정하세요. 두 경우 모두 @starting-style 규칙이 토스트 등장 동작의 시작 프레임을 지정합니다. show()는 호출하지 마세요. 사용자가 하던 작업에서 토스트 안으로 포커스를 옮깁니다.
  • 버튼을 <form method="dialog"> 요소로 감싸거나 버튼에 commandfor와 command="close"를 지정하면 버튼을 눌러 토스트를 닫을 수 있습니다. display 속성은 allow-discrete와 함께 전환되므로, 토스트가 차지하던 공간이 사라지기 전에 닫히는 동작이 재생됩니다.
  • 사라진 토스트는 문서에 그대로 남습니다. 메시지마다 토스트를 새로 추가하는 페이지에서는 toast 동작이 시간이 다 된 토스트와, 닫혀서 퇴장을 마친 토스트를 제거합니다(toast(region)). 같은 토스트를 다시 여는 페이지는 토스트를 남겨 두어야 하므로 attach()는 이 동작을 연결하지 않습니다.

#자동 닫기

toast-timed 클래스를 사용하면 토스트가 6초 후에 자동으로 닫힙니다. 시간은 display: none으로 끝나는 CSS 애니메이션으로 제어합니다. 포인터가 토스트 위에 있거나 키보드 포커스가 토스트 안에 있으면 애니메이션이 일시 정지되어 내용을 읽을 시간을 확보할 수 있습니다. 토스트 아래쪽의 가는 선은 남은 시간에 따라 줄어들고 타이머가 멈추면 함께 멈춥니다. 시간을 변경하려면 --toast-duration 사용자 지정 속성을 설정하세요. 작업 중 상태의 토스트에는 타이머가 없으며, 작업이 끝나야 타이머가 시작됩니다.

자동으로 닫히는 토스트

<div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast toast-timed" aria-label="Link copied">    <div class="toast-body">      <p class="toast-description">Link copied to the clipboard.</p>    </div>  </dialog></div>
<div className="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open className="toast toast-timed" aria-label="Link copied">    <div className="toast-body">      <p className="toast-description">Link copied to the clipboard.</p>    </div>  </dialog></div>
<div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast toast-timed" aria-label="Link copied">    <div class="toast-body">      <p class="toast-description">Link copied to the clipboard.</p>    </div>  </dialog></div>
<template>  <div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">    <dialog open class="toast toast-timed" aria-label="Link copied">      <div class="toast-body">        <p class="toast-description">Link copied to the clipboard.</p>      </div>    </dialog>  </div></template>
이 토스트는 6초 후에 닫힙니다. 다시 보려면 페이지를 새로고침하세요.

#동작 버튼

토스트에는 닫기 버튼 옆에 실행 취소나 보기처럼 동작 버튼 하나를 둘 수 있습니다. toast-action은 텍스트 뒤에 놓이며, btn btn-sm을 감싸는 <form method="dialog">입니다. 따라서 동작이 실행되면 토스트가 닫힙니다. 버튼에 value를 지정하세요. 그러면 대화 상자의 returnValue로 어느 버튼이 토스트를 닫았는지 알 수 있으므로, close 리스너 하나로 동작을 실행할 수 있습니다. 동작 버튼은 Tab 키로 접근할 수 있는 실제 버튼이며, 이 버튼에 포커스가 있거나 포인터가 토스트 위에 있는 동안에는 자동 닫기 타이머가 일시 정지됩니다.

토스트는 자동으로 사라지므로 사용자가 보지 못할 수도 있습니다. 따라서 토스트 안의 동작은 바로 가기일 뿐, 유일한 수단이 되어서는 안 됩니다. 삭제한 항목 복원이나 실패한 저장 재시도처럼 중요한 동작은 항목 자체의 메뉴, 휴지통, 실패한 폼 옆의 알림처럼 계속 남아 있는 곳에도 두세요. 상태를 지정하는 수정자는 아이콘에만 색을 적용하며 텍스트는 기본 글자색을 유지합니다.

동작 버튼

<div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast" aria-labelledby="toast-archived">    <div class="toast-body">      <p class="toast-title" id="toast-archived">Project archived</p>      <p class="toast-description">Atlas is hidden from the dashboard.</p>    </div>    <form method="dialog" class="toast-action">      <button class="btn btn-sm" value="undo">Undo</button>    </form>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M4 4L12 12" /><path d="M4 12L12 4" />        </svg>      </button>    </form>  </dialog>  <dialog open class="toast toast-danger" aria-labelledby="toast-failed">    <svg class="icon toast-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">      <circle cx="8" cy="8" r="6" transform="rotate(180 8 8)" /><circle cx="8" cy="5" r="0.5" fill="currentColor" stroke="none" transform="rotate(180 8 8)" /><path d="M8 8L8 11" transform="rotate(180 8 8)" />    </svg>    <div class="toast-body">      <p class="toast-title" id="toast-failed">The build failed</p>      <p class="toast-description">The install step exited with code 1.</p>    </div>    <form method="dialog" class="toast-action">      <button class="btn btn-sm" value="logs">View logs</button>    </form>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M4 4L12 12" /><path d="M4 12L12 4" />        </svg>      </button>    </form>  </dialog></div>
import XIcon from '@master/icons-react/native/16/soft/x'import AlertCircleIcon from '@master/icons-react/native/16/soft/alert-circle'<div className="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open className="toast" aria-labelledby="toast-archived">    <div className="toast-body">      <p className="toast-title" id="toast-archived">Project archived</p>      <p className="toast-description">Atlas is hidden from the dashboard.</p>    </div>    <form method="dialog" className="toast-action">      <button className="btn btn-sm" value="undo">Undo</button>    </form>    <form method="dialog" className="toast-close">      <button className="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon className="icon" />      </button>    </form>  </dialog>  <dialog open className="toast toast-danger" aria-labelledby="toast-failed">    <AlertCircleIcon className="icon toast-icon" />    <div className="toast-body">      <p className="toast-title" id="toast-failed">The build failed</p>      <p className="toast-description">The install step exited with code 1.</p>    </div>    <form method="dialog" className="toast-action">      <button className="btn btn-sm" value="logs">View logs</button>    </form>    <form method="dialog" className="toast-close">      <button className="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon className="icon" />      </button>    </form>  </dialog></div>
<script>  import XIcon from '@master/icons-svelte/native/16/soft/x'  import AlertCircleIcon from '@master/icons-svelte/native/16/soft/alert-circle'</script><div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast" aria-labelledby="toast-archived">    <div class="toast-body">      <p class="toast-title" id="toast-archived">Project archived</p>      <p class="toast-description">Atlas is hidden from the dashboard.</p>    </div>    <form method="dialog" class="toast-action">      <button class="btn btn-sm" value="undo">Undo</button>    </form>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon class="icon" />      </button>    </form>  </dialog>  <dialog open class="toast toast-danger" aria-labelledby="toast-failed">    <AlertCircleIcon class="icon toast-icon" />    <div class="toast-body">      <p class="toast-title" id="toast-failed">The build failed</p>      <p class="toast-description">The install step exited with code 1.</p>    </div>    <form method="dialog" class="toast-action">      <button class="btn btn-sm" value="logs">View logs</button>    </form>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon class="icon" />      </button>    </form>  </dialog></div>
<script setup>import XIcon from '@master/icons-vue/native/16/soft/x'import AlertCircleIcon from '@master/icons-vue/native/16/soft/alert-circle'</script><template>  <div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">    <dialog open class="toast" aria-labelledby="toast-archived">      <div class="toast-body">        <p class="toast-title" id="toast-archived">Project archived</p>        <p class="toast-description">Atlas is hidden from the dashboard.</p>      </div>      <form method="dialog" class="toast-action">        <button class="btn btn-sm" value="undo">Undo</button>      </form>      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">          <XIcon class="icon" />        </button>      </form>    </dialog>    <dialog open class="toast toast-danger" aria-labelledby="toast-failed">      <AlertCircleIcon class="icon toast-icon" />      <div class="toast-body">        <p class="toast-title" id="toast-failed">The build failed</p>        <p class="toast-description">The install step exited with code 1.</p>      </div>      <form method="dialog" class="toast-action">        <button class="btn btn-sm" value="logs">View logs</button>      </form>      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">          <XIcon class="icon" />        </button>      </form>    </dialog>  </div></template>
Tab 키로 Undo로 이동한 뒤 Enter 키를 누르거나 Dismiss를 눌러 보세요. 스크립트 없이 각 폼을 통해 해당 토스트가 닫힙니다.

#진행 중 상태와 제자리 갱신

토스트는 진행 중인 작업을 알린 뒤, 같은 자리에서 작업이 어떻게 끝났는지 알릴 수 있습니다. 작업이 진행되는 동안 토스트에는 aria-busy="true"를 지정하고, 아이콘 자리에 toast-icon을 지정한 스피너를 둡니다. 작업이 아무리 오래 걸려도 타이머는 흐르지 않습니다. 작업이 끝나면 같은 토스트의 텍스트, 상태, 아이콘을 바꾸고 aria-busy를 제거하세요. 토스트는 다시 등장하지 않고 쌓인 순서의 자리를 유지하며, 새 아이콘만 제자리에서 커지며 나타납니다.

진행 중 상태

<button class="btn" type="button" id="deploy-run">Deploy</button><div class="toast-region" id="deploy-region" role="region" aria-label="Notifications" aria-live="polite"></div><template id="deploy-pending">  <dialog open class="toast" aria-labelledby="deploy-title" aria-busy="true" aria-atomic="true">    <span class="spinner spinner-inline toast-icon" aria-hidden="true"></span>    <div class="toast-body">      <p class="toast-title" id="deploy-title">Deploying Atlas</p>      <p class="toast-description">Building for 14 regions.</p>    </div>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M4 4L12 12" /><path d="M4 12L12 4" />        </svg>      </button>    </form>    <template>      <svg class="icon toast-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">        <circle cx="8" cy="8" r="6" /><path d="M5 8L7.1041 9.8703A0.2 0.2 0 0 0 7.3832 9.8573L10.75 6.25" />      </svg>    </template>  </dialog></template><script>var region = document.getElementById('deploy-region')var count = 0document.getElementById('deploy-run').addEventListener('click', function () {  var toast = document.getElementById('deploy-pending').content.firstElementChild.cloneNode(true)  var title = toast.querySelector('.toast-title')  title.id = 'deploy-title-' + ++count  toast.setAttribute('aria-labelledby', title.id)  region.append(toast)  // When the work ends, the same toast says so: its icon, its words and its status change, and it is no longer busy.  setTimeout(function () {    toast.querySelector('.toast-icon').replaceWith(toast.querySelector('template').content.firstElementChild.cloneNode(true))    title.textContent = 'Deployed to production'    toast.querySelector('.toast-description').textContent = 'atlas.dev is live in 14 regions.'    toast.classList.add('toast-success', 'toast-timed')    toast.removeAttribute('aria-busy')  }, 2400)})// A toast that has run out, or was dismissed and has left, is removed.MasterUI.toast(region)</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
Deploy를 눌러 보세요. 토스트는 2초 동안 작업 중 상태로 있다가, 같은 자리에서 배포가 완료되었다고 알리고 6초 후에 사라집니다.

같은 토스트는 파일을 업로드하는 동안 개수가 바뀌거나, 실패에서 재시도로 바뀌는 것처럼 여러 번 바뀔 수 있습니다. 바뀔 때마다 타이머가 다시 시작되므로 사용자는 새 텍스트를 읽을 시간을 온전히 얻습니다. 중요하고 오래 걸리는 작업을 지켜보는 데는 작업 중 상태의 토스트가 적합하지 않습니다. 작업 옆에 두는 진행률은 그 자리에 계속 남아 있습니다.

#풍부한 콘텐츠

토스트에는 텍스트 외의 내용도 담을 수 있으며, 이미 그 내용을 그리는 컴포넌트를 그대로 사용합니다. 시작 부분의 아바타로 누가 무엇을 했는지, 본문의 파일로 무엇이 도착했는지 보여 주고, 아직 진행 중인 업로드에는 파일의 진행률을 표시합니다. 토스트는 자체 형태를 유지합니다. 그림은 상태 아이콘이 있을 자리에 놓이고, 파일은 텍스트와 같은 너비를 차지합니다.

아직 진행 중인 업로드는 toast-timed가 없는 토스트로 표시하므로 작업이 끝날 때까지 남아 있습니다. 완료를 알리는 토스트는 위에서 설명한 것처럼 같은 토스트를 그 자리에서 갱신한 것입니다. 중요한 내용은 다른 곳에서도 접근할 수 있게 하세요. 파일은 해당 폴더에서, 멘션은 해당 스레드에서 다시 찾을 수 있어야 합니다.

풍부한 콘텐츠

<div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast" aria-labelledby="toast-mention">    <span class="avatar avatar-sm"><img class="avatar-image" src="/demo/portrait-1.svg" alt></span>    <div class="toast-body">      <p class="toast-title" id="toast-mention">Ada mentioned you</p>      <p class="toast-description">“Can you look at the token audit before Friday?”</p>    </div>    <form method="dialog" class="toast-action">      <button class="btn btn-sm" value="reply">Reply</button>    </form>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M4 4L12 12" /><path d="M4 12L12 4" />        </svg>      </button>    </form>  </dialog>  <dialog open class="toast" aria-labelledby="toast-upload" aria-busy="true">    <div class="toast-body">      <p class="toast-title" id="toast-upload">Uploading 1 file</p>      <div class="file file-sm mt-xs">        <span class="file-page" aria-hidden="true">pdf</span>        <div class="file-body">          <p class="file-name">Q3 report.pdf</p>          <p class="file-meta">1.6 of 2.4 MB</p>        </div>        <progress class="file-progress" value="66" max="100" aria-label="Uploading Q3 report.pdf">          66%        </progress>      </div>    </div>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M4 4L12 12" /><path d="M4 12L12 4" />        </svg>      </button>    </form>  </dialog>  <dialog open class="toast toast-success" aria-labelledby="toast-shared">    <svg class="icon toast-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">      <circle cx="8" cy="8" r="6" /><path d="M5 8L7.1041 9.8703A0.2 0.2 0 0 0 7.3832 9.8573L10.75 6.25" />    </svg>    <div class="toast-body">      <p class="toast-title" id="toast-shared">Photo shared with Design</p>      <div class="file mt-xs">        <img class="file-thumb" src="/demo/harbor.svg" alt>        <div class="file-body">          <p class="file-name">harbor-at-dusk.jpg</p>          <p class="file-meta">1600 × 1000 · 480 KB</p>        </div>      </div>    </div>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M4 4L12 12" /><path d="M4 12L12 4" />        </svg>      </button>    </form>  </dialog></div>
import XIcon from '@master/icons-react/native/16/soft/x'import CheckCircleIcon from '@master/icons-react/native/16/soft/check-circle'<div className="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open className="toast" aria-labelledby="toast-mention">    <span className="avatar avatar-sm">      <img className="avatar-image" src="/demo/portrait-1.svg" alt="" />    </span>    <div className="toast-body">      <p className="toast-title" id="toast-mention">Ada mentioned you</p>      <p className="toast-description">“Can you look at the token audit before Friday?”</p>    </div>    <form method="dialog" className="toast-action">      <button className="btn btn-sm" value="reply">Reply</button>    </form>    <form method="dialog" className="toast-close">      <button className="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon className="icon" />      </button>    </form>  </dialog>  <dialog open className="toast" aria-labelledby="toast-upload" aria-busy="true">    <div className="toast-body">      <p className="toast-title" id="toast-upload">Uploading 1 file</p>      <div className="file file-sm mt-xs">        <span className="file-page" aria-hidden="true">pdf</span>        <div className="file-body">          <p className="file-name">Q3 report.pdf</p>          <p className="file-meta">1.6 of 2.4 MB</p>        </div>        <progress className="file-progress" value="66" max="100" aria-label="Uploading Q3 report.pdf">          66%        </progress>      </div>    </div>    <form method="dialog" className="toast-close">      <button className="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon className="icon" />      </button>    </form>  </dialog>  <dialog open className="toast toast-success" aria-labelledby="toast-shared">    <CheckCircleIcon className="icon toast-icon" />    <div className="toast-body">      <p className="toast-title" id="toast-shared">Photo shared with Design</p>      <div className="file mt-xs">        <img className="file-thumb" src="/demo/harbor.svg" alt="" />        <div className="file-body">          <p className="file-name">harbor-at-dusk.jpg</p>          <p className="file-meta">1600 × 1000 · 480 KB</p>        </div>      </div>    </div>    <form method="dialog" className="toast-close">      <button className="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon className="icon" />      </button>    </form>  </dialog></div>
<script>  import XIcon from '@master/icons-svelte/native/16/soft/x'  import CheckCircleIcon from '@master/icons-svelte/native/16/soft/check-circle'</script><div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">  <dialog open class="toast" aria-labelledby="toast-mention">    <span class="avatar avatar-sm"><img class="avatar-image" src="/demo/portrait-1.svg" alt></span>    <div class="toast-body">      <p class="toast-title" id="toast-mention">Ada mentioned you</p>      <p class="toast-description">“Can you look at the token audit before Friday?”</p>    </div>    <form method="dialog" class="toast-action">      <button class="btn btn-sm" value="reply">Reply</button>    </form>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon class="icon" />      </button>    </form>  </dialog>  <dialog open class="toast" aria-labelledby="toast-upload" aria-busy="true">    <div class="toast-body">      <p class="toast-title" id="toast-upload">Uploading 1 file</p>      <div class="file file-sm mt-xs">        <span class="file-page" aria-hidden="true">pdf</span>        <div class="file-body">          <p class="file-name">Q3 report.pdf</p>          <p class="file-meta">1.6 of 2.4 MB</p>        </div>        <progress class="file-progress" value="66" max="100" aria-label="Uploading Q3 report.pdf">          66%        </progress>      </div>    </div>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon class="icon" />      </button>    </form>  </dialog>  <dialog open class="toast toast-success" aria-labelledby="toast-shared">    <CheckCircleIcon class="icon toast-icon" />    <div class="toast-body">      <p class="toast-title" id="toast-shared">Photo shared with Design</p>      <div class="file mt-xs">        <img class="file-thumb" src="/demo/harbor.svg" alt>        <div class="file-body">          <p class="file-name">harbor-at-dusk.jpg</p>          <p class="file-meta">1600 × 1000 · 480 KB</p>        </div>      </div>    </div>    <form method="dialog" class="toast-close">      <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">        <XIcon class="icon" />      </button>    </form>  </dialog></div>
<script setup>import XIcon from '@master/icons-vue/native/16/soft/x'import CheckCircleIcon from '@master/icons-vue/native/16/soft/check-circle'</script><template>  <div class="toast-region" role="region" aria-label="Notifications" aria-live="polite">    <dialog open class="toast" aria-labelledby="toast-mention">      <span class="avatar avatar-sm">        <img class="avatar-image" src="/demo/portrait-1.svg" alt>      </span>      <div class="toast-body">        <p class="toast-title" id="toast-mention">Ada mentioned you</p>        <p class="toast-description">“Can you look at the token audit before Friday?”</p>      </div>      <form method="dialog" class="toast-action">        <button class="btn btn-sm" value="reply">Reply</button>      </form>      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">          <XIcon class="icon" />        </button>      </form>    </dialog>    <dialog open class="toast" aria-labelledby="toast-upload" aria-busy="true">      <div class="toast-body">        <p class="toast-title" id="toast-upload">Uploading 1 file</p>        <div class="file file-sm mt-xs">          <span class="file-page" aria-hidden="true">pdf</span>          <div class="file-body">            <p class="file-name">Q3 report.pdf</p>            <p class="file-meta">1.6 of 2.4 MB</p>          </div>          <progress class="file-progress" value="66" max="100" aria-label="Uploading Q3 report.pdf">            66%          </progress>        </div>      </div>      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">          <XIcon class="icon" />        </button>      </form>    </dialog>    <dialog open class="toast toast-success" aria-labelledby="toast-shared">      <CheckCircleIcon class="icon toast-icon" />      <div class="toast-body">        <p class="toast-title" id="toast-shared">Photo shared with Design</p>        <div class="file mt-xs">          <img class="file-thumb" src="/demo/harbor.svg" alt>          <div class="file-body">            <p class="file-name">harbor-at-dusk.jpg</p>            <p class="file-meta">1600 × 1000 · 480 KB</p>          </div>        </div>      </div>      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" aria-label="Dismiss">          <XIcon class="icon" />        </button>      </form>    </dialog>  </div></template>
누가 보냈는지, 무엇이 도착했는지, 업로드가 얼마나 진행되었는지를 각각 이미 그 내용을 그리는 컴포넌트로 보여 줍니다.

#토스트 영역

toast-region은 하단의 인라인 끝 모서리에 고정되며 가장 최근 토스트를 맨 아래에 쌓습니다. 영역 자체는 포인터 이벤트를 받지 않으므로 빈 부분 아래에 있는 페이지를 계속 조작할 수 있습니다. 좁은 화면에서는 화면 너비 전체를 차지합니다.

클래스배치
toast-region하단의 인라인 끝
toast-region-top상단. 토스트가 아래 방향으로 나타나며 가장 최근 토스트가 맨 위에 배치됩니다.
toast-region-center인라인 끝 대신 가운데에 배치

이 영역은 z-index가 지정된 일반 고정 배치 요소입니다. 열린 모달 대화 상자 위에 토스트를 표시하려면 영역에 popover="manual"를 지정하고 해당 영역에서 showPopover()를 한 번 호출하세요. 그러면 영역이 최상위 레이어에 배치됩니다.

#접근성

  • 토스트가 나타날 때 스크린 리더가 읽도록 aria-live="polite"를 지정해 라이브 영역으로 만들고, aria-label로 영역의 접근 가능한 이름을 지정하세요.
  • 각 토스트에는 제목을 가리키는 aria-labelledby 속성이나 aria-label 속성으로 접근 가능한 이름을 지정하세요.
  • 제자리에서 텍스트가 바뀌는 토스트에는 aria-atomic="true"를 지정하세요. 그러면 변경 내용이 조각조각이 아니라 토스트 전체로 한 번 안내됩니다. 작업 중 상태인 동안에는 스크린 리더가 작업이 끝날 때까지 안내를 보류할 수 있습니다.
  • 토스트는 작업 결과를 확인하는 용도입니다. 사용자가 토스트를 놓쳐도 필요한 정보나 기능에 접근할 수 있어야 하므로, 어떤 동작을 실행하는 유일한 수단을 토스트 안에 두지 마세요.
  • 토스트는 나타날 때 포커스를 가져가지 않습니다. 동작 버튼과 닫기 버튼은 탭 순서에 포함되며, 둘 중 하나에 포커스가 있는 동안에는 자동 닫기 타이머가 일시 정지됩니다.
  • 동작 줄이기가 설정되어 있으면 토스트는 제자리에서 서서히 나타나고 사라지며, 새 아이콘은 크기 변화 없이 서서히 나타납니다.

#React, Svelte 및 Vue

toast 컴포넌트는 토스트를 큐로 관리합니다. 어디서든 호출할 수 있는 toast() 함수와 큐의 내용을 표시하는 영역으로 구성되며, 영역은 한 번만 렌더링합니다. npx master-ui add toast를 사용해 프로젝트에 복사하세요. 컴포넌트의 구성과 사용법은 React, Svelte 및 Vue에서 확인할 수 있습니다.

  • toast(message)는 토스트를 표시하고 핸들을 반환합니다. update(message)는 다시 등장하지 않고 같은 토스트에 다른 내용을 표시하며 타이머를 다시 시작합니다. dismiss()는 토스트 자체의 버튼을 누른 것처럼 토스트를 닫습니다. 메시지에는 title, description, status, 밀리초 단위의 duration(false이면 토스트가 계속 남음), action이 있으며, 문자열을 전달하면 설명으로 사용합니다.
  • status: 'pending'은 스피너를 표시하고 aria-busy를 설정하며, 토스트가 갱신될 때까지 유지합니다.
  • action: { label, onClick }은 토스트가 제공하는 하나의 버튼입니다. onClick을 실행한 뒤 토스트를 닫습니다. 단, 핸들러가 event.preventDefault()를 호출하면 닫지 않습니다.
  • toast.promise(promise, { loading, success, error })는 loading을 진행 중 상태의 토스트로 표시한 뒤, 같은 토스트를 성공 시 success 메시지로, 실패 시 danger 상태의 error 메시지로 갱신합니다. 성공 메시지는 이행 값을, 실패 메시지는 거부 사유를 받는 함수로 지정할 수 있습니다. 전달한 프로미스를 반환하므로 완료를 기다리거나 후속 처리를 연결할 수 있습니다.
toast({ title: 'Project archived', action: { label: 'Undo', onClick: () => restore(project) } })await toast.promise(deploy(project), {  loading: { title: 'Deploying Atlas' },  success: (release) => ({ title: 'Deployed to production', description: `${release.url} is live.` }),  error: (error) => ({ title: 'The deploy failed', description: String(error), duration: false }),})
ui/toast.tsx
'use client'import { useEffect, useRef, useSyncExternalStore, type ComponentProps, type CSSProperties, type MouseEvent, type ReactNode } from 'react'export interface ToastAction {  /** The words on the button: Undo, View. */  label: ReactNode  /** Runs when the button is pressed, and the toast is dismissed after it unless this calls `event.preventDefault()`. */  onClick: (event: MouseEvent<HTMLButtonElement>) => void}export interface ToastMessage {  title?: ReactNode  description?: ReactNode  /**   * Colors the icon; give the icon itself in `icon`, with the classes `icon toast-icon`. `pending` says the   * work is under way: the toast shows a spinner instead and stays until it is updated or dismissed.   */  status?: 'pending' | 'info' | 'success' | 'warning' | 'danger'  icon?: ReactNode  /** How long the toast stays, in milliseconds. 6000 by default; `false` keeps it until it is dismissed. */  duration?: number | false  /** The one button the toast offers. It runs, then dismisses the toast. Keep the same action somewhere that stays. */  action?: ToastAction}export interface ToastHandle {  /** Says something else in the same toast, in its place, without a new entrance; its clock starts again. */  update(message: ToastMessage | string): void  /** Dismisses the toast: it leaves as one dismissed with its button does. */  dismiss(): void}export interface ToastPromiseMessages<T> {  /** What the toast says while the work is under way. */  loading: ToastMessage | string  /** What it says when the promise is fulfilled, or a function of the value; `success` unless it names a status. */  success: ToastMessage | string | ((value: T) => ToastMessage | string)  /** What it says when the promise is rejected, or a function of the reason; `danger` unless it names a status. */  error: ToastMessage | string | ((error: unknown) => ToastMessage | string)}interface Shown extends ToastMessage { id: number, version: number, leaving?: boolean }let shown: Shown[] = []let count = 0const listeners = new Set<() => void>()const none: Shown[] = []function publish(next: Shown[]) {  shown = next  listeners.forEach(listener => listener())}function subscribe(listener: () => void) {  listeners.add(listener)  return () => { listeners.delete(listener) }}const read = (message: ToastMessage | string): ToastMessage => typeof message === 'string' ? { description: message } : messageconst edit = (id: number, change: (toast: Shown) => Shown) => publish(shown.map(toast => toast.id === id ? change(toast) : toast))const remove = (id: number) => publish(shown.filter(toast => toast.id !== id))// A dismissed toast leaves through its transition before it is removed.function leave(id: number) {  if (!shown.some(toast => toast.id === id && !toast.leaving)) return  edit(id, toast => ({ ...toast, leaving: true }))  setTimeout(() => remove(id), 300)}/** * Show a toast in the `Toaster` of the page. Returns a handle that updates it in place or dismisses it. * @example const archived = toast({ title: 'Project archived', action: { label: 'Undo', onClick: restore } }) */export function toast(message: ToastMessage | string): ToastHandle {  // A server has no page to show a toast in, and what it queued would reach every reader.  if (typeof document === 'undefined') return { update() {}, dismiss() {} }  const id = ++count  publish([...shown, { ...read(message), id, version: 0 }])  return {    update: next => edit(id, toast => ({ ...read(next), id, version: toast.version + 1, leaving: toast.leaving })),    dismiss: () => leave(id),  }}/** * Show a pending toast while a promise runs, then say in the same toast how it ended. Returns the promise. * @example toast.promise(save(), { loading: 'Saving…', success: 'Saved.', error: (error) => `Not saved: ${error}` }) */toast.promise = function <T>(work: Promise<T>, messages: ToastPromiseMessages<T>): Promise<T> {  const handle = toast({ ...read(messages.loading), status: 'pending' })  const settle = <R,>(message: ToastMessage | string | ((result: R) => ToastMessage | string), result: R, status: 'success' | 'danger') => {    const said = read(typeof message === 'function' ? message(result) : message)    handle.update({ ...said, status: said.status ?? status })  }  work.then(value => settle(messages.success, value, 'success'), (error: unknown) => settle(messages.error, error, 'danger'))  return work}/** Starts a toast's clock again, and the hairline that shows it, so new words get their whole time. */function restart(dialog: HTMLDialogElement | null) {  for (const animation of dialog?.getAnimations?.({ subtree: true }) ?? []) {    if ((animation as CSSAnimation).animationName?.startsWith('toast-')) animation.currentTime = 0  }}function Toast({ toast: { id, version, leaving, title, description, status, icon, duration = 6000, action }, dismissLabel }: { toast: Shown, dismissLabel: string }) {  const dialog = useRef<HTMLDialogElement>(null)  useEffect(() => { if (version) restart(dialog.current) }, [version])  const pending = status === 'pending'  const timed = !pending && duration !== false  return (    <dialog      ref={dialog}      open={!leaving}      className={['toast', timed && 'toast-timed', status && !pending && `toast-${status}`].filter(Boolean).join(' ')}      aria-labelledby={`toast-${id}`}      aria-busy={pending || undefined}      aria-atomic="true"      style={timed ? { '--toast-duration': `${duration}ms` } as CSSProperties : undefined}      onClose={() => leave(id)}      // An expired toast has left already.      onAnimationEnd={event => event.animationName === 'toast-expire' && event.target === event.currentTarget && remove(id)}    >      {pending ? <span className="spinner spinner-inline toast-icon" aria-hidden="true" /> : icon}      <div className="toast-body">        {title !== undefined && <p className="toast-title" id={`toast-${id}`}>{title}</p>}        {description !== undefined && <p className="toast-description" id={title === undefined ? `toast-${id}` : undefined}>{description}</p>}      </div>      {action && (        <form method="dialog" className="toast-action">          <button className="btn btn-sm" onClick={action.onClick}>{action.label}</button>        </form>      )}      <form method="dialog" className="toast-close">        <button className="btn btn-quiet btn-square btn-sm" aria-label={dismissLabel}>          <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M4 4L12 12" /><path d="M4 12L12 4" /></svg>        </button>      </form>    </dialog>  )}export interface ToasterProps extends Omit<ComponentProps<'div'>, 'children'> {  /** The name of the region, for assistive technology. */  label?: string  /** The name of the button that dismisses a toast. */  dismissLabel?: string}/** The stack that shows the toasts. Render it once, anywhere in the page. */export function Toaster({ label = 'Notifications', dismissLabel = 'Dismiss', className, ...root }: ToasterProps) {  const toasts = useSyncExternalStore(subscribe, () => shown, () => none)  return (    <div className={className ? `toast-region ${className}` : 'toast-region'} role="region" aria-label={label} aria-live="polite" {...root}>      {toasts.map(each => <Toast toast={each} dismissLabel={dismissLabel} key={each.id} />)}    </div>  )}
ui/Toaster.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { Attachment } from 'svelte/attachments'  import type { HTMLAttributes } from 'svelte/elements'  export interface ToastAction {    /** The words on the button: Undo, View. */    label: string    /** Runs when the button is pressed, and the toast is dismissed after it unless this calls `event.preventDefault()`. */    onClick: (event: MouseEvent) => void  }  export interface ToastMessage {    title?: string    description?: string    /**     * Colors the icon; give the icon itself in `icon`, with the classes `icon toast-icon`. `pending` says the     * work is under way: the toast shows a spinner instead and stays until it is updated or dismissed.     */    status?: 'pending' | 'info' | 'success' | 'warning' | 'danger'    icon?: Snippet    /** How long the toast stays, in milliseconds. 6000 by default; `false` keeps it until it is dismissed. */    duration?: number | false    /** The one button the toast offers. It runs, then dismisses the toast. Keep the same action somewhere that stays. */    action?: ToastAction  }  export interface ToastHandle {    /** Says something else in the same toast, in its place, without a new entrance; its clock starts again. */    update(message: ToastMessage | string): void    /** Dismisses the toast: it leaves as one dismissed with its button does. */    dismiss(): void  }  export interface ToastPromiseMessages<T> {    /** What the toast says while the work is under way. */    loading: ToastMessage | string    /** What it says when the promise is fulfilled, or a function of the value; `success` unless it names a status. */    success: ToastMessage | string | ((value: T) => ToastMessage | string)    /** What it says when the promise is rejected, or a function of the reason; `danger` unless it names a status. */    error: ToastMessage | string | ((error: unknown) => ToastMessage | string)  }  export interface ToasterProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** The name of the region, for assistive technology. */    label?: string    /** The name of the button that dismisses a toast. */    dismissLabel?: string  }  interface Shown extends ToastMessage { id: number, version: number, leaving?: boolean }  let shown = $state.raw<Shown[]>([])  let count = 0  const read = (message: ToastMessage | string): ToastMessage => typeof message === 'string' ? { description: message } : message  const edit = (id: number, change: (toast: Shown) => Shown) => { shown = shown.map(toast => toast.id === id ? change(toast) : toast) }  const remove = (id: number) => { shown = shown.filter(toast => toast.id !== id) }  // A dismissed toast leaves through its transition before it is removed.  function leave(id: number) {    if (!shown.some(toast => toast.id === id && !toast.leaving)) return    edit(id, toast => ({ ...toast, leaving: true }))    setTimeout(() => remove(id), 300)  }  /**   * Show a toast in the `Toaster` of the page. Returns a handle that updates it in place or dismisses it.   * @example const archived = toast({ title: 'Project archived', action: { label: 'Undo', onClick: restore } })   */  export function toast(message: ToastMessage | string): ToastHandle {    // A server has no page to show a toast in, and what it queued would reach every reader.    if (typeof document === 'undefined') return { update() {}, dismiss() {} }    const id = ++count    shown = [...shown, { ...read(message), id, version: 0 }]    return {      update: next => edit(id, toast => ({ ...read(next), id, version: toast.version + 1, leaving: toast.leaving })),      dismiss: () => leave(id),    }  }  /**   * Show a pending toast while a promise runs, then say in the same toast how it ended. Returns the promise.   * @example toast.promise(save(), { loading: 'Saving…', success: 'Saved.', error: (error) => `Not saved: ${error}` })   */  toast.promise = function <T>(work: Promise<T>, messages: ToastPromiseMessages<T>): Promise<T> {    const handle = toast({ ...read(messages.loading), status: 'pending' })    const settle = <R>(message: ToastMessage | string | ((result: R) => ToastMessage | string), result: R, status: 'success' | 'danger') => {      const said = read(typeof message === 'function' ? message(result) : message)      handle.update({ ...said, status: said.status ?? status })    }    work.then(value => settle(messages.success, value, 'success'), (error: unknown) => settle(messages.error, error, 'danger'))    return work  }  /** Starts a toast's clock again, and the hairline that shows it, so new words get their whole time. */  const restart = (version: number): Attachment<HTMLDialogElement> => (dialog) => {    if (!version) return    for (const animation of dialog.getAnimations?.({ subtree: true }) ?? []) {      if ((animation as CSSAnimation).animationName?.startsWith('toast-')) animation.currentTime = 0    }  }</script><script lang="ts">  let { label = 'Notifications', dismissLabel = 'Dismiss', class: className, ...root }: ToasterProps = $props()  // A server renders no toast, and neither does the first render over its HTML: one shown before the page  // hydrated waits for it.  let mounted = $state(false)  $effect(() => { mounted = true })</script><!--  @component  The stack that shows the toasts. Render it once, anywhere in the page.--><div class={['toast-region', className]} role="region" aria-label={label} aria-live="polite" {...root}>  {#each mounted ? shown : [] as { id, version, leaving, title, description, status, icon, duration = 6000, action } (id)}    {@const pending = status === 'pending'}    {@const timed = !pending && duration !== false}    <!-- An expired toast has left already. -->    <dialog      open={!leaving}      class={['toast', timed && 'toast-timed', status && !pending && `toast-${status}`]}      aria-labelledby="toast-{id}"      aria-busy={pending || undefined}      aria-atomic="true"      style:--toast-duration={timed ? `${duration}ms` : undefined}      onclose={() => leave(id)}      onanimationend={(event) => { if (event.animationName === 'toast-expire' && event.target === event.currentTarget) remove(id) }}      {@attach restart(version)}    >      {#if pending}<span class="spinner spinner-inline toast-icon" aria-hidden="true"></span>{:else}{@render icon?.()}{/if}      <div class="toast-body">        {#if title !== undefined}<p class="toast-title" id="toast-{id}">{title}</p>{/if}        {#if description !== undefined}<p class="toast-description" id={title === undefined ? `toast-${id}` : undefined}>{description}</p>{/if}      </div>      {#if action}        <form method="dialog" class="toast-action">          <button class="btn btn-sm" onclick={action.onClick}>{action.label}</button>        </form>      {/if}      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" aria-label={dismissLabel}>          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4L12 12" /><path d="M4 12L12 4" /></svg>        </button>      </form>    </dialog>  {/each}</div>
ui/Toaster.vue
<script lang="ts">import { shallowRef } from 'vue'export interface ToastAction {  /** The words on the button: Undo, View. */  label: string  /** Runs when the button is pressed, and the toast is dismissed after it unless this calls `event.preventDefault()`. */  onClick: (event: MouseEvent) => void}export interface ToastMessage {  title?: string  description?: string  /**   * Colors the icon; give the icon itself in the `icon` slot of the `Toaster`, with the classes `icon toast-icon`.   * `pending` says the work is under way: the toast shows a spinner instead and stays until it is updated or dismissed.   */  status?: 'pending' | 'info' | 'success' | 'warning' | 'danger'  /** How long the toast stays, in milliseconds. 6000 by default; `false` keeps it until it is dismissed. */  duration?: number | false  /** The one button the toast offers. It runs, then dismisses the toast. Keep the same action somewhere that stays. */  action?: ToastAction}export interface ToastHandle {  /** Says something else in the same toast, in its place, without a new entrance; its clock starts again. */  update(message: ToastMessage | string): void  /** Dismisses the toast: it leaves as one dismissed with its button does. */  dismiss(): void}export interface ToastPromiseMessages<T> {  /** What the toast says while the work is under way. */  loading: ToastMessage | string  /** What it says when the promise is fulfilled, or a function of the value; `success` unless it names a status. */  success: ToastMessage | string | ((value: T) => ToastMessage | string)  /** What it says when the promise is rejected, or a function of the reason; `danger` unless it names a status. */  error: ToastMessage | string | ((error: unknown) => ToastMessage | string)}export interface ShownToast extends ToastMessage { id: number, version: number, leaving?: boolean }const shown = shallowRef<ShownToast[]>([])let count = 0const read = (message: ToastMessage | string): ToastMessage => typeof message === 'string' ? { description: message } : messageconst edit = (id: number, change: (toast: ShownToast) => ShownToast) => { shown.value = shown.value.map(toast => toast.id === id ? change(toast) : toast) }const remove = (id: number) => { shown.value = shown.value.filter(toast => toast.id !== id) }// A dismissed toast leaves through its transition before it is removed.function leave(id: number) {  if (!shown.value.some(toast => toast.id === id && !toast.leaving)) return  edit(id, toast => ({ ...toast, leaving: true }))  setTimeout(() => remove(id), 300)}/** * Show a toast in the `Toaster` of the page. Returns a handle that updates it in place or dismisses it. * @example const archived = toast({ title: 'Project archived', action: { label: 'Undo', onClick: restore } }) */export function toast(message: ToastMessage | string): ToastHandle {  // A server has no page to show a toast in, and what it queued would reach every reader.  if (typeof document === 'undefined') return { update() {}, dismiss() {} }  const id = ++count  shown.value = [...shown.value, { ...read(message), id, version: 0 }]  return {    update: next => edit(id, toast => ({ ...read(next), id, version: toast.version + 1, leaving: toast.leaving })),    dismiss: () => leave(id),  }}/** * Show a pending toast while a promise runs, then say in the same toast how it ended. Returns the promise. * @example toast.promise(save(), { loading: 'Saving…', success: 'Saved.', error: (error) => `Not saved: ${error}` }) */toast.promise = function <T>(work: Promise<T>, messages: ToastPromiseMessages<T>): Promise<T> {  const handle = toast({ ...read(messages.loading), status: 'pending' })  const settle = <R>(message: ToastMessage | string | ((result: R) => ToastMessage | string), result: R, status: 'success' | 'danger') => {    const said = read(typeof message === 'function' ? message(result) : message)    handle.update({ ...said, status: said.status ?? status })  }  work.then(value => settle(messages.success, value, 'success'), (error: unknown) => settle(messages.error, error, 'danger'))  return work}</script><script setup lang="ts">import { onMounted, type Directive } from 'vue'defineOptions({ inheritAttrs: false })const { label = 'Notifications', dismissLabel = 'Dismiss' } = defineProps<{  /** The name of the region, for assistive technology. */  label?: string  /** The name of the button that dismisses a toast. */  dismissLabel?: string}>()defineSlots<{  /** The icon of a toast, with the classes `icon toast-icon`. A pending toast shows a spinner instead. */  icon?: (scope: { toast: ShownToast }) => unknown}>()/* The stack that shows the toasts. Render it once, anywhere in the page. */// A server renders no toast, and neither does the first render over its HTML.const mounted = shallowRef(false)onMounted(() => { mounted.value = true })// An expired toast has left already.const expired = (event: AnimationEvent, id: number) => {  if (event.animationName === 'toast-expire' && event.target === event.currentTarget) remove(id)}/** Starts a toast's clock again, and the hairline that shows it, so new words get their whole time. */const vRestart: Directive<HTMLDialogElement, number> = {  updated(dialog, { value, oldValue }) {    if (value === oldValue) return    for (const animation of dialog.getAnimations?.({ subtree: true }) ?? []) {      if ((animation as CSSAnimation).animationName?.startsWith('toast-')) animation.currentTime = 0    }  },}const timed = (each: ShownToast) => each.status !== 'pending' && each.duration !== false</script><template>  <div class="toast-region" role="region" :aria-label="label" aria-live="polite" v-bind="$attrs">    <dialog      v-for="each in mounted ? shown : []"      :key="each.id"      v-restart="each.version"      :open="!each.leaving"      class="toast"      :class="{        'toast-timed': timed(each),        'toast-info': each.status === 'info',        'toast-success': each.status === 'success',        'toast-warning': each.status === 'warning',        'toast-danger': each.status === 'danger',      }"      :aria-labelledby="`toast-${each.id}`"      :aria-busy="each.status === 'pending' || undefined"      aria-atomic="true"      :style="timed(each) ? { '--toast-duration': `${each.duration ?? 6000}ms` } : undefined"      @close="leave(each.id)"      @animationend="expired($event, each.id)"    >      <span v-if="each.status === 'pending'" class="spinner spinner-inline toast-icon" aria-hidden="true" />      <slot v-else name="icon" :toast="each" />      <div class="toast-body">        <p v-if="each.title !== undefined" class="toast-title" :id="`toast-${each.id}`">{{ each.title }}</p>        <p v-if="each.description !== undefined" class="toast-description" :id="each.title === undefined ? `toast-${each.id}` : undefined">{{ each.description }}</p>      </div>      <form v-if="each.action" method="dialog" class="toast-action">        <button class="btn btn-sm" @click="each.action.onClick">{{ each.action.label }}</button>      </form>      <form method="dialog" class="toast-close">        <button class="btn btn-quiet btn-square btn-sm" :aria-label="dismissLabel">          <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4L12 12" /><path d="M4 12L12 4" /></svg>        </button>      </form>    </dialog>  </div></template>

#클래스

클래스설명
toast-region화면 하단의 끝 가장자리에 고정된 스택으로, 가장 최근 토스트가 마지막에 놓입니다. aria-live="polite"로 라이브 영역을 만들고 aria-label로 이름을 지정하세요. 스택 자체는 포인터 이벤트를 받지 않으며, 좁은 화면에서는 전체 너비를 차지합니다.
toast-region-top상단에 배치하는 토스트 스택입니다. 토스트는 아래쪽 방향으로 쌓이며 가장 최근 토스트가 맨 위에 표시됩니다적용할 클래스는 toast-region입니다
toast-region-center끝 가장자리 대신 중앙에 배치하는 스택입니다. toast-region-top과 함께 사용할 수 있습니다적용할 클래스는 toast-region입니다
toast영역 안의 dialog 요소에 표시하는 메시지입니다. 제목을 가리키는 aria-labelledby 또는 aria-label로 접근 가능한 이름을 지정하세요. 텍스트가 제자리에서 바뀔 때는 aria-atomic="true"를 지정해 변경 내용이 전체로 한 번만 안내되게 하세요.
toast-timed--toast-duration이 지나면 자동으로 사라집니다. 같은 영역의 토스트 중 하나에 호버하거나 포커스가 있는 동안에는 타이머가 일시 정지되고, 토스트가 처리 중인 동안에는 타이머가 흐르지 않으며, 하단의 가는 선은 남은 시간에 맞춰 줄어듭니다.적용할 클래스는 toast입니다
toast-info아이콘에 정보 색조를 적용합니다. 텍스트는 기본 글자색을 유지합니다.적용할 클래스는 toast입니다
toast-success아이콘에 성공 색조를 적용합니다. 텍스트는 기본 글자색을 유지합니다.적용할 클래스는 toast입니다
toast-warning아이콘에 경고 색조를 적용합니다. 텍스트는 기본 글자색을 유지합니다.적용할 클래스는 toast입니다
toast-danger아이콘에 위험 색조를 적용합니다. 텍스트는 기본 글자색을 유지합니다.적용할 클래스는 toast입니다
toast-icon상태 아이콘에서는 icon 옆에, 대기 중인 토스트의 스피너에서는 spinner 옆에 지정합니다. 텍스트 첫 줄의 가운데에 맞추고 상태 색상을 적용합니다. 이전 아이콘을 대신하는 새 아이콘은 커지면서 자리를 잡습니다.
toast-body텍스트를 담고 남은 너비를 모두 차지합니다. 뒤에 오는 버튼은 행 끝에 배치됩니다
toast-title무슨 일이 있었는지 짧게 전하는 강조 문구
toast-description제목 아래에 낮은 강조도로 표시하는 문장입니다. 제목 없는 토스트에서는 이 문장이 메시지 전체를 이룹니다.
toast-action토스트가 제공할 수 있는 단 하나의 동작(Undo, View)으로, 본문 뒤와 닫기 버튼 앞에 둡니다. btn btn-sm을 method="dialog" 폼으로 감싸거나, 버튼 자체에 commandfor와 command="close"를 지정해 동작이 실행된 뒤 토스트가 닫히게 하세요.
toast-close토스트를 닫는 method="dialog" 폼 또는 버튼으로, 끝쪽 패딩 영역에 배치합니다.

#사용자 지정 속성

속성기본값설명
--toast-durationtoast-timed가 표시되는 시간입니다. 설정하지 않으면 6s입니다toast에 설정합니다
--toast-inset1rem뷰포트 가장자리에서 영역까지의 거리toast-region에 설정합니다
--toast-gap.5rem토스트 사이 간격toast-region에 설정합니다

#소스

@master/ui/components/toast.css
/* * Toast: a brief message over the page about something that just happened. * Each toast is a non-modal <dialog>, so it can be dismissed without script by a form with method="dialog" or * a button with command="close", and it enters and leaves through @starting-style and discrete transitions. * A timed toast leaves by itself and waits while any toast of its stack is hovered or focused. Toasts stack in * a fixed region. * A pending toast (aria-busy="true") holds a spinner for its icon and keeps no clock until its work settles; * the same toast then says how it ended, in place, without a second entrance. One action button may sit * before the dismiss button. */@layer components.ui {  /*   * The stack. It takes no pointer events itself, so the page under its empty space stays usable.   * With popover="manual" and showPopover() it joins the top layer, above any open modal dialog.   * It keeps --toast-inset from the viewport's edges, or more where the device lays something over the page: the   * home indicator below, the status bar above and, in landscape, the notch at either side, which the device   * reports on both, as a drawer does.   */  .toast-region {    --toast-gap: .5rem;    --toast-inset: 1rem;    --toast-edge-top: max(var(--toast-inset), env(safe-area-inset-top));    --toast-edge-bottom: max(var(--toast-inset), env(safe-area-inset-bottom));    --toast-edge-inline: max(var(--toast-inset), env(safe-area-inset-left), env(safe-area-inset-right));    position: fixed;    inset: auto;    inset-block-end: var(--toast-edge-bottom);    inset-inline-end: var(--toast-edge-inline);    z-index: 100;    display: flex;    flex-direction: column;    gap: var(--toast-gap);    width: min(22.5rem, calc(100vw - var(--toast-edge-inline) * 2));    margin: 0;    padding: 0;    border: 0;    overflow: visible;    background: none;    pointer-events: none;    &.toast-region-top {      inset: auto;      inset-block-start: var(--toast-edge-top);      inset-inline-end: var(--toast-edge-inline);      flex-direction: column-reverse;    }    &.toast-region-center {      inset-inline: 0;      margin-inline: auto;    }    /* On a narrow screen the stack spans the width, wherever the modifiers put it. */    @media (width < 30rem) {      inset-inline: var(--toast-edge-inline);      width: auto;      &:is(.toast-region-top, .toast-region-center) {        inset-inline: var(--toast-edge-inline);      }    }  }  .toast {    --toast-shift: .75rem;    --icon-size: 1rem;    --surface-color: var(--color-surface-floating);    position: relative;    inset: auto;    flex: none;    align-items: flex-start;    gap: .625rem .75rem;    width: auto;    max-width: none;    margin: 0;    padding: .75rem .875rem;    border: 0;    border-radius: calc(var(--radius-control-lg) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: var(--color-surface-floating);    color: var(--color-text-body);    box-shadow: var(--shadow-floating);    font-size: .84375rem;    line-height: 1.5;    pointer-events: auto;    /* Closed is where it leaves to: it fades and drops back half as far as it came, faster than it arrived. */    opacity: 0;    scale: .985;    translate: 0 calc(var(--toast-shift) / 2);    transition-property: opacity, scale, translate, display;    transition-duration: var(--duration-quick);    transition-timing-function: var(--easing-glide);    transition-behavior: allow-discrete;    &[open] {      display: flex;      opacity: 1;      scale: 1;      translate: 0 0;      transition-duration: var(--duration-base);      @starting-style {        opacity: 0;        scale: .97;        translate: 0 var(--toast-shift);      }    }    /*     * Timed: after --toast-duration the toast leaves by itself. The clock stops while the pointer or the     * keyboard is on it, so a reader is never raced, and does not run at all while the toast is busy.     */    &.toast-timed[open]:not([aria-busy="true"]) {      animation: toast-expire var(--toast-duration, 6s) linear forwards;      /* A hairline along the foot runs out with the clock, and stops when the clock does. */      &::after {        content: '';        position: absolute;        inset-inline: .875rem;        inset-block-end: 0;        height: 1.5px;        border-radius: 999px;        background: var(--color-line-mark);        transform-origin: 0 50%;        animation: toast-clock var(--toast-duration, 6s) linear forwards;      }      &:dir(rtl)::after {        transform-origin: 100% 50%;      }      &:focus-within, &:focus-within::after {        animation-play-state: paused;      }      /* Only a pointer that hovers holds the clock: a tap leaves :hover stuck on a touch screen, which would stop it for good. */      @media (hover: hover) {        &:hover, &:hover::after {          animation-play-state: paused;        }      }    }    /*     * A status colors the toast's own icon, and only that: the words, the action and the dismiss button stay     * in ink, so the hue is handed to toast-icon instead of to every icon inside.     */    &.toast-info { --toast-hue: var(--color-info); }    &.toast-success { --toast-hue: var(--color-success); }    &.toast-warning { --toast-hue: var(--color-warning); }    &.toast-danger { --toast-hue: var(--color-danger); }    /* Pending: the work it reports is under way. Its spinner stays quiet; how the work ended takes the hue. */    &[aria-busy="true"] { --toast-hue: var(--color-text-muted); }    /* Reduced motion keeps the fade: no drop on the way in or out, nor when a timed toast expires. */    @media (prefers-reduced-motion: reduce) {      --toast-shift: 0px;      scale: none;      translate: none;      &.toast-timed[open]::after {        display: none;      }      &[open] {        scale: none;        translate: none;        @starting-style {          scale: none;          translate: none;        }      }    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;      &.toast-timed[open]:not([aria-busy="true"])::after {        background: CanvasText;      }    }  }  /*   * A reader on one toast holds the clock of every toast in the stack: one that ran out beside it would close   * the gap it leaves and move the toast under the pointer, and the next would be gone before it was reached.   */  .toast-region:focus-within .toast.toast-timed[open],  .toast-region:focus-within .toast.toast-timed[open]::after {    animation-play-state: paused;  }  @media (hover: hover) {    .toast-region:hover .toast.toast-timed[open],    .toast-region:hover .toast.toast-timed[open]::after {      animation-play-state: paused;    }  }  /* From the top the toast arrives downward. */  .toast-region-top .toast {    --toast-shift: -.75rem;    @media (prefers-reduced-motion: reduce) {      --toast-shift: 0px;    }  }  /*   * The icon centers on the first line of text. A spinner takes the same place and the same ink. When the   * icon is replaced, as a pending toast settles, the new one grows into place; the toast itself stays put.   */  .toast-icon {    --icon-color: var(--toast-hue);    margin-block: calc((1lh - var(--icon-size)) / 2);    color: var(--toast-hue, inherit);    transition-property: opacity, scale;    transition-duration: var(--duration-base);    transition-timing-function: var(--easing-glide);    @starting-style {      opacity: 0;      scale: .5;    }    /* With reduced motion the new icon fades in at its size. */    @media (prefers-reduced-motion: reduce) {      transition-property: opacity;    }  }  .toast-body {    display: grid;    flex: 1 1 0;    gap: .125rem;    min-width: 0;  }  .toast-title {    margin: 0;    color: var(--color-text-strong);    font-weight: var(--font-weight-control);    text-wrap: balance;    overflow-wrap: anywhere;  }  .toast-description {    margin: 0;    color: var(--color-text-muted);    text-wrap: pretty;    overflow-wrap: anywhere;  }  /*   * The action: one button that does what the toast offers (Undo, View) and dismisses it. It sits after the   * words, on the first line, and takes no more height than the dismiss button beside it. Both are small   * 32px buttons pulled 6px into the padding above and below, which centers them on the 20px first line and   * keeps them as clear of the top as of the foot of a toast of one line.   */  .toast-action {    flex: none;    margin-block: -.375rem;  }  /* The form or button that dismisses the toast sits at the end, pulled into the padding. */  /*   * The close button stands as far in from the toast's end as from its top, 6px each way, so its chip keeps the   * concentric corner: the inline padding is .125rem deeper than the block, so it reaches .125rem farther.   */  .toast-close {    flex: none;    margin-block: -.375rem;    margin-inline: 0 -.5rem;  }}@keyframes toast-clock {  to {    scale: 0 1;  }}/* The toast rests for most of its time, then leaves the way a closed one does and stops taking space. */@keyframes toast-expire {  0%, 96% {    opacity: 1;    translate: 0 0;    visibility: visible;  }  100% {    display: none;    opacity: 0;    translate: 0 calc(var(--toast-shift) / 2);    visibility: hidden;  }}