탐색

v2.1.0
오버레이

대화 상자

스크립트 없이 열고 닫는 오버레이 시트 형태의 네이티브 모달입니다.

이 페이지의 내용

대화 상자는 표면 계층에서 가장 높은 표면입니다. 페이지를 어둡고 흐릿하게 만드는 배경막 위에 오버레이 시트가 놓입니다. 네이티브 <dialog>에 .dialog 클래스를 적용하세요. commandfor와 command="show-modal"이 지정된 버튼으로 열면 브라우저가 대화 상자를 최상위 레이어에 표시하고, 포커스를 대화 상자 안에 유지하며, Esc 키로 닫을 수 있게 하므로 스크립트가 필요 없습니다.

대화 상자

<button type="button" class="btn" commandfor="delete-project" command="show-modal">  Delete project</button><dialog id="delete-project" class="dialog" closedby="any" aria-labelledby="delete-project-title">  <header class="dialog-header">    <h2 class="dialog-title" id="delete-project-title">Delete this project?</h2>    <p class="dialog-description">      Atlas and its 14 deployments are removed, and its domains stop resolving at once.    </p>  </header>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="delete-project" command="close">Cancel</button>    <button type="button" class="btn btn-primary" commandfor="delete-project" command="close">      Delete project    </button>  </footer></dialog>
<>  <button type="button" className="btn" {...{ commandfor: 'delete-project', command: 'show-modal' }}>    Delete project  </button>  <dialog id="delete-project" className="dialog" closedby="any" aria-labelledby="delete-project-title">    <header className="dialog-header">      <h2 className="dialog-title" id="delete-project-title">Delete this project?</h2>      <p className="dialog-description">        Atlas and its 14 deployments are removed, and its domains stop resolving at once.      </p>    </header>    <footer className="dialog-footer">      <button type="button" className="btn" {...{ commandfor: 'delete-project', command: 'close' }}>        Cancel      </button>      <button type="button" className="btn btn-primary" {...{ commandfor: 'delete-project', command: 'close' }}>        Delete project      </button>    </footer>  </dialog></>
<button type="button" class="btn" commandfor="delete-project" command="show-modal">  Delete project</button><dialog id="delete-project" class="dialog" closedby="any" aria-labelledby="delete-project-title">  <header class="dialog-header">    <h2 class="dialog-title" id="delete-project-title">Delete this project?</h2>    <p class="dialog-description">      Atlas and its 14 deployments are removed, and its domains stop resolving at once.    </p>  </header>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="delete-project" command="close">Cancel</button>    <button type="button" class="btn btn-primary" commandfor="delete-project" command="close">      Delete project    </button>  </footer></dialog>
<template>  <button type="button" class="btn" commandfor="delete-project" command="show-modal">    Delete project  </button>  <dialog id="delete-project" class="dialog" closedby="any" aria-labelledby="delete-project-title">    <header class="dialog-header">      <h2 class="dialog-title" id="delete-project-title">Delete this project?</h2>      <p class="dialog-description">        Atlas and its 14 deployments are removed, and its domains stop resolving at once.      </p>    </header>    <footer class="dialog-footer">      <button type="button" class="btn" commandfor="delete-project" command="close">Cancel</button>      <button type="button" class="btn btn-primary" commandfor="delete-project" command="close">        Delete project      </button>    </footer>  </dialog></template>

#열기와 닫기

속성 세 개로 모달에 필요했던 스크립트를 대체할 수 있습니다.

  • 버튼에 commandfor="id"와 command="show-modal"을 함께 지정하면 대화 상자가 모달로 열립니다. command="close"는 대화 상자를 닫고 처음 열었던 버튼으로 포커스를 돌려보냅니다.
  • 대화 상자에 closedby="any"를 지정하면 배경막을 클릭해 닫을 수 있습니다. Esc 키로는 이 속성과 관계없이 항상 닫을 수 있습니다. 실수로 클릭했을 때 작업 내용이 사라지면 안 되는 경우에는 이 속성을 생략하세요. 이 속성을 지원하지 않는 브라우저에서도 Esc 키와 닫기 버튼은 동작합니다.
  • 대화 상자 안의 <form method="dialog"> 폼을 제출하면 대화 상자가 닫힙니다. 어느 버튼으로 제출했는지는 대화 상자의 returnValue로 확인할 수 있습니다.

모달 대화 상자가 열려 있는 동안에는 뒤쪽 페이지와 상호작용하거나 페이지를 스크롤할 수 없습니다.

#폼이 있는 대화 상자

dialog-body에는 헤더와 푸터 사이의 콘텐츠가 들어갑니다. 이 영역은 남은 높이를 채우며, 콘텐츠가 뷰포트에 들어갈 수 있는 높이를 넘으면 시트 안에서 스크롤됩니다. dialog-close는 모서리에 눈에 잘 띄지 않는 정사각형 버튼을 배치합니다. 이 버튼에 접근 가능한 이름을 지정하세요.

폼이 있는 대화 상자

<button type="button" class="btn btn-primary" commandfor="invite" command="show-modal">  Invite member</button><dialog id="invite" class="dialog" aria-labelledby="invite-title">  <header class="dialog-header">    <h2 class="dialog-title" id="invite-title">Invite a member</h2>    <p class="dialog-description">They receive an email with a link that expires in seven days.</p>  </header>  <form class="dialog-body flex flex-col gap-md" method="dialog" id="invite-form">    <label class="field">      Email <input class="input" type="email" placeholder="ada@example.com" required autofocus>    </label>    <label class="field">      Role <select class="select">        <option class="select-option">Member</option>        <option class="select-option">Admin</option>        <option class="select-option">Billing</option>      </select>    </label>  </form>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="invite" command="close">Cancel</button>    <button type="submit" class="btn btn-primary" form="invite-form">Send invite</button>  </footer>  <button type="button" class="btn btn-quiet btn-square btn-sm dialog-close" commandfor="invite" command="close" aria-label="Close">    <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></dialog>
import XIcon from '@master/icons-react/native/16/soft/x'<>  <button type="button" className="btn btn-primary" {...{ commandfor: 'invite', command: 'show-modal' }}>    Invite member  </button>  <dialog id="invite" className="dialog" aria-labelledby="invite-title">    <header className="dialog-header">      <h2 className="dialog-title" id="invite-title">Invite a member</h2>      <p className="dialog-description">        They receive an email with a link that expires in seven days.      </p>    </header>    <form className="dialog-body flex flex-col gap-md" method="dialog" id="invite-form">      <label className="field">        Email <input className="input" type="email" placeholder="ada@example.com" required autoFocus />      </label>      <label className="field">        Role <select className="select">          <option className="select-option">Member</option>          <option className="select-option">Admin</option>          <option className="select-option">Billing</option>        </select>      </label>    </form>    <footer className="dialog-footer">      <button type="button" className="btn" {...{ commandfor: 'invite', command: 'close' }}>        Cancel      </button>      <button type="submit" className="btn btn-primary" form="invite-form">Send invite</button>    </footer>    <button type="button" className="btn btn-quiet btn-square btn-sm dialog-close" {...{ commandfor: 'invite', command: 'close' }} aria-label="Close">      <XIcon className="icon" />    </button>  </dialog></>
<script>  import XIcon from '@master/icons-svelte/native/16/soft/x'</script><button type="button" class="btn btn-primary" commandfor="invite" command="show-modal">  Invite member</button><dialog id="invite" class="dialog" aria-labelledby="invite-title">  <header class="dialog-header">    <h2 class="dialog-title" id="invite-title">Invite a member</h2>    <p class="dialog-description">They receive an email with a link that expires in seven days.</p>  </header>  <form class="dialog-body flex flex-col gap-md" method="dialog" id="invite-form">    <label class="field">      Email <input class="input" type="email" placeholder="ada@example.com" required autofocus>    </label>    <label class="field">      Role <select class="select">        <option class="select-option">Member</option>        <option class="select-option">Admin</option>        <option class="select-option">Billing</option>      </select>    </label>  </form>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="invite" command="close">Cancel</button>    <button type="submit" class="btn btn-primary" form="invite-form">Send invite</button>  </footer>  <button type="button" class="btn btn-quiet btn-square btn-sm dialog-close" commandfor="invite" command="close" aria-label="Close">    <XIcon class="icon" />  </button></dialog>
<script setup>import XIcon from '@master/icons-vue/native/16/soft/x'</script><template>  <button type="button" class="btn btn-primary" commandfor="invite" command="show-modal">    Invite member  </button>  <dialog id="invite" class="dialog" aria-labelledby="invite-title">    <header class="dialog-header">      <h2 class="dialog-title" id="invite-title">Invite a member</h2>      <p class="dialog-description">        They receive an email with a link that expires in seven days.      </p>    </header>    <form class="dialog-body flex flex-col gap-md" method="dialog" id="invite-form">      <label class="field">        Email <input class="input" type="email" placeholder="ada@example.com" required autofocus>      </label>      <label class="field">        Role <select class="select">          <option class="select-option">Member</option>          <option class="select-option">Admin</option>          <option class="select-option">Billing</option>        </select>      </label>    </form>    <footer class="dialog-footer">      <button type="button" class="btn" commandfor="invite" command="close">Cancel</button>      <button type="submit" class="btn btn-primary" form="invite-form">Send invite</button>    </footer>    <button type="button" class="btn btn-quiet btn-square btn-sm dialog-close" commandfor="invite" command="close" aria-label="Close">      <XIcon class="icon" />    </button>  </dialog></template>

#크기

대화 상자의 기본 너비는 28rem입니다. 한 문장으로 확인을 요청할 때 쓰는 dialog-sm의 너비는 22rem이며, dialog-lg의 너비는 40rem입니다. 좁은 화면에서는 모든 크기가 뷰포트 가장자리에서 1rem의 여백을 유지합니다. 푸터는 컨테이너 쿼리를 통해 대화 상자 자체의 너비에 맞춰 배치를 바꿉니다. 너비가 22rem 미만이면 주 동작 버튼을 맨 위에 두고, 각 버튼이 전체 너비를 차지하도록 세로로 배치합니다.

크기

<button type="button" class="btn" commandfor="size-sm" command="show-modal">Small</button><button type="button" class="btn" commandfor="size-lg" command="show-modal">Large</button><dialog id="size-sm" class="dialog dialog-sm" closedby="any" aria-labelledby="size-sm-title">  <header class="dialog-header">    <h2 class="dialog-title" id="size-sm-title">Sign out?</h2>    <p class="dialog-description">Unsaved drafts stay on this device.</p>  </header>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="size-sm" command="close">Stay</button>    <button type="button" class="btn btn-primary" commandfor="size-sm" command="close">      Sign out    </button>  </footer></dialog><dialog id="size-lg" class="dialog dialog-lg" closedby="any" aria-labelledby="size-lg-title">  <header class="dialog-header">    <h2 class="dialog-title" id="size-lg-title">Release notes</h2>    <p class="dialog-description">      Version 2.1 adds overlays that need no script: dialogs, popovers, menus and tooltips.    </p>  </header>  <footer class="dialog-footer">    <button type="button" class="btn btn-primary" commandfor="size-lg" command="close">Done</button>  </footer></dialog>
<>  <button type="button" className="btn" {...{ commandfor: 'size-sm', command: 'show-modal' }}>    Small  </button>  <button type="button" className="btn" {...{ commandfor: 'size-lg', command: 'show-modal' }}>    Large  </button>  <dialog id="size-sm" className="dialog dialog-sm" closedby="any" aria-labelledby="size-sm-title">    <header className="dialog-header">      <h2 className="dialog-title" id="size-sm-title">Sign out?</h2>      <p className="dialog-description">Unsaved drafts stay on this device.</p>    </header>    <footer className="dialog-footer">      <button type="button" className="btn" {...{ commandfor: 'size-sm', command: 'close' }}>        Stay      </button>      <button type="button" className="btn btn-primary" {...{ commandfor: 'size-sm', command: 'close' }}>        Sign out      </button>    </footer>  </dialog>  <dialog id="size-lg" className="dialog dialog-lg" closedby="any" aria-labelledby="size-lg-title">    <header className="dialog-header">      <h2 className="dialog-title" id="size-lg-title">Release notes</h2>      <p className="dialog-description">        Version 2.1 adds overlays that need no script: dialogs, popovers, menus and tooltips.      </p>    </header>    <footer className="dialog-footer">      <button type="button" className="btn btn-primary" {...{ commandfor: 'size-lg', command: 'close' }}>        Done      </button>    </footer>  </dialog></>
<button type="button" class="btn" commandfor="size-sm" command="show-modal">Small</button><button type="button" class="btn" commandfor="size-lg" command="show-modal">Large</button><dialog id="size-sm" class="dialog dialog-sm" closedby="any" aria-labelledby="size-sm-title">  <header class="dialog-header">    <h2 class="dialog-title" id="size-sm-title">Sign out?</h2>    <p class="dialog-description">Unsaved drafts stay on this device.</p>  </header>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="size-sm" command="close">Stay</button>    <button type="button" class="btn btn-primary" commandfor="size-sm" command="close">      Sign out    </button>  </footer></dialog><dialog id="size-lg" class="dialog dialog-lg" closedby="any" aria-labelledby="size-lg-title">  <header class="dialog-header">    <h2 class="dialog-title" id="size-lg-title">Release notes</h2>    <p class="dialog-description">      Version 2.1 adds overlays that need no script: dialogs, popovers, menus and tooltips.    </p>  </header>  <footer class="dialog-footer">    <button type="button" class="btn btn-primary" commandfor="size-lg" command="close">Done</button>  </footer></dialog>
<template>  <button type="button" class="btn" commandfor="size-sm" command="show-modal">Small</button>  <button type="button" class="btn" commandfor="size-lg" command="show-modal">Large</button>  <dialog id="size-sm" class="dialog dialog-sm" closedby="any" aria-labelledby="size-sm-title">    <header class="dialog-header">      <h2 class="dialog-title" id="size-sm-title">Sign out?</h2>      <p class="dialog-description">Unsaved drafts stay on this device.</p>    </header>    <footer class="dialog-footer">      <button type="button" class="btn" commandfor="size-sm" command="close">Stay</button>      <button type="button" class="btn btn-primary" commandfor="size-sm" command="close">        Sign out      </button>    </footer>  </dialog>  <dialog id="size-lg" class="dialog dialog-lg" closedby="any" aria-labelledby="size-lg-title">    <header class="dialog-header">      <h2 class="dialog-title" id="size-lg-title">Release notes</h2>      <p class="dialog-description">        Version 2.1 adds overlays that need no script: dialogs, popovers, menus and tooltips.      </p>    </header>    <footer class="dialog-footer">      <button type="button" class="btn btn-primary" commandfor="size-lg" command="close">        Done      </button>    </footer>  </dialog></template>

#드로어

dialog-drawer는 페이지를 계속 볼 수 있도록 필터, 상세 정보, 설정을 인라인 끝 가장자리에 표시하는 패널입니다. 모서리와 그림자가 잘리지 않도록 뷰포트 가장자리에서 안쪽으로 8px 떨어져 떠 있으며, 배치된 쪽 가장자리에서 슬라이드되어 들어옵니다.

드로어

<button type="button" class="btn" commandfor="filters" command="show-modal">Filters</button><dialog id="filters" class="dialog dialog-drawer" closedby="any" aria-labelledby="filters-title">  <header class="dialog-header">    <h2 class="dialog-title" id="filters-title">Filters</h2>    <p class="dialog-description">Narrow the list of deployments.</p>  </header>  <div class="dialog-body flex flex-col gap-md">    <label class="field">Branch <input class="input" value="main"></label>    <label class="check"><input type="checkbox" class="checkbox" checked> Production only</label>  </div>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="filters" command="close">Reset</button>    <button type="button" class="btn btn-primary" commandfor="filters" command="close">      Apply    </button>  </footer></dialog>
<>  <button type="button" className="btn" {...{ commandfor: 'filters', command: 'show-modal' }}>    Filters  </button>  <dialog id="filters" className="dialog dialog-drawer" closedby="any" aria-labelledby="filters-title">    <header className="dialog-header">      <h2 className="dialog-title" id="filters-title">Filters</h2>      <p className="dialog-description">Narrow the list of deployments.</p>    </header>    <div className="dialog-body flex flex-col gap-md">      <label className="field">Branch <input className="input" defaultValue="main" /></label>      <label className="check">        <input type="checkbox" className="checkbox" defaultChecked /> Production only      </label>    </div>    <footer className="dialog-footer">      <button type="button" className="btn" {...{ commandfor: 'filters', command: 'close' }}>        Reset      </button>      <button type="button" className="btn btn-primary" {...{ commandfor: 'filters', command: 'close' }}>        Apply      </button>    </footer>  </dialog></>
<button type="button" class="btn" commandfor="filters" command="show-modal">Filters</button><dialog id="filters" class="dialog dialog-drawer" closedby="any" aria-labelledby="filters-title">  <header class="dialog-header">    <h2 class="dialog-title" id="filters-title">Filters</h2>    <p class="dialog-description">Narrow the list of deployments.</p>  </header>  <div class="dialog-body flex flex-col gap-md">    <label class="field">Branch <input class="input" value="main"></label>    <label class="check"><input type="checkbox" class="checkbox" checked> Production only</label>  </div>  <footer class="dialog-footer">    <button type="button" class="btn" commandfor="filters" command="close">Reset</button>    <button type="button" class="btn btn-primary" commandfor="filters" command="close">      Apply    </button>  </footer></dialog>
<template>  <button type="button" class="btn" commandfor="filters" command="show-modal">Filters</button>  <dialog id="filters" class="dialog dialog-drawer" closedby="any" aria-labelledby="filters-title">    <header class="dialog-header">      <h2 class="dialog-title" id="filters-title">Filters</h2>      <p class="dialog-description">Narrow the list of deployments.</p>    </header>    <div class="dialog-body flex flex-col gap-md">      <label class="field">Branch <input class="input" value="main"></label>      <label class="check"><input type="checkbox" class="checkbox" checked> Production only</label>    </div>    <footer class="dialog-footer">      <button type="button" class="btn" commandfor="filters" command="close">Reset</button>      <button type="button" class="btn btn-primary" commandfor="filters" command="close">        Apply      </button>    </footer>  </dialog></template>

#인라인 시작 위치

dialog-drawer-start 클래스를 추가하면 드로어가 인라인 시작 가장자리에 배치되며 너비는 18rem입니다. 탐색 메뉴를 배치하기에 알맞은 위치입니다. 좁은 레이아웃에서 숨겨진 사이드바는 이 드로어로 다시 표시됩니다. 앱 셸을 참고하세요.

인라인 시작 드로어

<button type="button" class="btn" commandfor="nav-drawer" command="show-modal">  Open navigation</button><dialog id="nav-drawer" class="dialog dialog-drawer dialog-drawer-start" closedby="any" aria-label="Navigation">  <div class="dialog-body">    <nav class="nav" aria-label="Workspace">      <a class="nav-item" href="#" aria-current="page">Overview</a>      <a class="nav-item" href="#">Projects</a>      <a class="nav-item" href="#">Domains</a>      <a class="nav-item" href="#">Settings</a>    </nav>  </div></dialog>
<>  <button type="button" className="btn" {...{ commandfor: 'nav-drawer', command: 'show-modal' }}>    Open navigation  </button>  <dialog id="nav-drawer" className="dialog dialog-drawer dialog-drawer-start" closedby="any" aria-label="Navigation">    <div className="dialog-body">      <nav className="nav" aria-label="Workspace">        <a className="nav-item" href="#" aria-current="page">Overview</a>        <a className="nav-item" href="#">Projects</a>        <a className="nav-item" href="#">Domains</a>        <a className="nav-item" href="#">Settings</a>      </nav>    </div>  </dialog></>
<button type="button" class="btn" commandfor="nav-drawer" command="show-modal">  Open navigation</button><dialog id="nav-drawer" class="dialog dialog-drawer dialog-drawer-start" closedby="any" aria-label="Navigation">  <div class="dialog-body">    <nav class="nav" aria-label="Workspace">      <a class="nav-item" href="#" aria-current="page">Overview</a>      <a class="nav-item" href="#">Projects</a>      <a class="nav-item" href="#">Domains</a>      <a class="nav-item" href="#">Settings</a>    </nav>  </div></dialog>
<template>  <button type="button" class="btn" commandfor="nav-drawer" command="show-modal">    Open navigation  </button>  <dialog id="nav-drawer" class="dialog dialog-drawer dialog-drawer-start" closedby="any" aria-label="Navigation">    <div class="dialog-body">      <nav class="nav" aria-label="Workspace">        <a class="nav-item" href="#" aria-current="page">Overview</a>        <a class="nav-item" href="#">Projects</a>        <a class="nav-item" href="#">Domains</a>        <a class="nav-item" href="#">Settings</a>      </nav>    </div>  </dialog></template>

#시트

dialog-sheet는 작은 화면에서 짧은 작업을 처리하거나 선택지 목록을 보여 줄 때 사용하며, 엄지손가락이 닿기 쉬운 화면 하단에서 올라옵니다. 시트는 --dialog-width로 정한 최대 너비까지 가로 공간을 채우며, 화면 가장자리에 닿는 아래쪽 모서리는 직각입니다. env(safe-area-inset-bottom) 값을 사용해 홈 인디케이터와 겹치지 않도록 여백을 확보합니다.

시트

<button type="button" class="btn" commandfor="share-sheet" command="show-modal">Share</button><dialog id="share-sheet" class="dialog dialog-sheet" closedby="any" aria-labelledby="share-sheet-title">  <header class="dialog-header">    <h2 class="dialog-title" id="share-sheet-title">Share this project</h2>    <p class="dialog-description">Anyone with the link can view the latest deployment.</p>  </header>  <div class="dialog-body">    <div class="input-group">      <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">      <button type="button" class="btn">Copy</button>    </div>  </div>  <footer class="dialog-footer">    <button type="button" class="btn btn-primary" commandfor="share-sheet" command="close">      Done    </button>  </footer></dialog>
<>  <button type="button" className="btn" {...{ commandfor: 'share-sheet', command: 'show-modal' }}>    Share  </button>  <dialog id="share-sheet" className="dialog dialog-sheet" closedby="any" aria-labelledby="share-sheet-title">    <header className="dialog-header">      <h2 className="dialog-title" id="share-sheet-title">Share this project</h2>      <p className="dialog-description">Anyone with the link can view the latest deployment.</p>    </header>    <div className="dialog-body">      <div className="input-group">        <input className="input-group-field" defaultValue="https://atlas.dev/p/9f2c" readOnly aria-label="Link" />        <button type="button" className="btn">Copy</button>      </div>    </div>    <footer className="dialog-footer">      <button type="button" className="btn btn-primary" {...{ commandfor: 'share-sheet', command: 'close' }}>        Done      </button>    </footer>  </dialog></>
<button type="button" class="btn" commandfor="share-sheet" command="show-modal">Share</button><dialog id="share-sheet" class="dialog dialog-sheet" closedby="any" aria-labelledby="share-sheet-title">  <header class="dialog-header">    <h2 class="dialog-title" id="share-sheet-title">Share this project</h2>    <p class="dialog-description">Anyone with the link can view the latest deployment.</p>  </header>  <div class="dialog-body">    <div class="input-group">      <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">      <button type="button" class="btn">Copy</button>    </div>  </div>  <footer class="dialog-footer">    <button type="button" class="btn btn-primary" commandfor="share-sheet" command="close">      Done    </button>  </footer></dialog>
<template>  <button type="button" class="btn" commandfor="share-sheet" command="show-modal">Share</button>  <dialog id="share-sheet" class="dialog dialog-sheet" closedby="any" aria-labelledby="share-sheet-title">    <header class="dialog-header">      <h2 class="dialog-title" id="share-sheet-title">Share this project</h2>      <p class="dialog-description">Anyone with the link can view the latest deployment.</p>    </header>    <div class="dialog-body">      <div class="input-group">        <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">        <button type="button" class="btn">Copy</button>      </div>    </div>    <footer class="dialog-footer">      <button type="button" class="btn btn-primary" commandfor="share-sheet" command="close">        Done      </button>    </footer>  </dialog></template>

#스와이프

드로어나 시트에 dialog-swipe를 추가하면 손가락, 트랙패드, 마우스 입력을 따라 움직이며, 패널을 가장자리 밖으로 밀어 닫을 수 있습니다. 대화 상자는 패널이 움직이는 트랙이 되며, 투명하고 뷰포트만큼 커집니다. 대화 상자에 있던 모든 내용은 표면 스타일이 적용되는 dialog-panel 안에 넣으세요. 시트에는 dialog-handle을 추가합니다. 이 요소는 위쪽 가장자리에 놓이는 짧은 홈으로, 잡을 위치를 알려 줍니다. drawer 동작을 연결하세요. attach()는 모든 dialog-swipe를 찾아 연결합니다.

스와이프로 닫는 시트

<button type="button" class="btn" commandfor="share-swipe" command="show-modal">Share</button><dialog id="share-swipe" class="dialog dialog-sheet dialog-swipe" closedby="any" aria-labelledby="share-swipe-title">  <div class="dialog-panel">    <div class="dialog-handle" aria-hidden="true"></div>    <header class="dialog-header">      <h2 class="dialog-title" id="share-swipe-title">Share this project</h2>      <p class="dialog-description">Anyone with the link can view the latest deployment.</p>    </header>    <div class="dialog-body">      <div class="input-group">        <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">        <button type="button" class="btn">Copy</button>      </div>    </div>    <footer class="dialog-footer">      <button type="button" class="btn btn-primary" commandfor="share-swipe" command="close">        Done      </button>    </footer>  </div></dialog><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root}>      <button type="button" className="btn" {...{ commandfor: 'share-swipe', command: 'show-modal' }}>        Share      </button>      <dialog id="share-swipe" className="dialog dialog-sheet dialog-swipe" closedby="any" aria-labelledby="share-swipe-title">        <div className="dialog-panel">          <div className="dialog-handle" aria-hidden="true"></div>          <header className="dialog-header">            <h2 className="dialog-title" id="share-swipe-title">Share this project</h2>            <p className="dialog-description">Anyone with the link can view the latest deployment.</p>          </header>          <div className="dialog-body">            <div className="input-group">              <input className="input-group-field" defaultValue="https://atlas.dev/p/9f2c" readOnly aria-label="Link" />              <button type="button" className="btn">Copy</button>            </div>          </div>          <footer className="dialog-footer">            <button type="button" className="btn btn-primary" {...{ commandfor: 'share-swipe', command: 'close' }}>              Done            </button>          </footer>        </div>      </dialog>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div {@attach attach}>  <button type="button" class="btn" commandfor="share-swipe" command="show-modal">Share</button>  <dialog id="share-swipe" class="dialog dialog-sheet dialog-swipe" closedby="any" aria-labelledby="share-swipe-title">    <div class="dialog-panel">      <div class="dialog-handle" aria-hidden="true"></div>      <header class="dialog-header">        <h2 class="dialog-title" id="share-swipe-title">Share this project</h2>        <p class="dialog-description">Anyone with the link can view the latest deployment.</p>      </header>      <div class="dialog-body">        <div class="input-group">          <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">          <button type="button" class="btn">Copy</button>        </div>      </div>      <footer class="dialog-footer">        <button type="button" class="btn btn-primary" commandfor="share-swipe" command="close">          Done        </button>      </footer>    </div>  </dialog></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root">    <button type="button" class="btn" commandfor="share-swipe" command="show-modal">Share</button>    <dialog id="share-swipe" class="dialog dialog-sheet dialog-swipe" closedby="any" aria-labelledby="share-swipe-title">      <div class="dialog-panel">        <div class="dialog-handle" aria-hidden="true"></div>        <header class="dialog-header">          <h2 class="dialog-title" id="share-swipe-title">Share this project</h2>          <p class="dialog-description">Anyone with the link can view the latest deployment.</p>        </header>        <div class="dialog-body">          <div class="input-group">            <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">            <button type="button" class="btn">Copy</button>          </div>        </div>        <footer class="dialog-footer">          <button type="button" class="btn btn-primary" commandfor="share-swipe" command="close">            Done          </button>        </footer>      </div>    </dialog>  </div></template>
시트를 연 뒤 홈이나 제목을 잡고 아래로 드래그하거나 튕기듯 밀어서 놓아 보세요. 절반이 안 되게 끌다가 놓으면 제자리로 돌아갑니다. 휴대전화에서는 스와이프하세요.

드로어도 놓여 있는 가장자리 쪽으로 같은 방식으로 스와이프하며, 손잡이가 필요 없습니다. 패널 전체를 잡을 수 있습니다.

스와이프로 닫는 드로어

<button type="button" class="btn" commandfor="filters-swipe" command="show-modal">Filters</button><dialog id="filters-swipe" class="dialog dialog-drawer dialog-swipe" closedby="any" aria-labelledby="filters-swipe-title">  <div class="dialog-panel">    <header class="dialog-header">      <h2 class="dialog-title" id="filters-swipe-title">Filters</h2>      <p class="dialog-description">Narrow the list of deployments.</p>    </header>    <div class="dialog-body flex flex-col gap-md">      <label class="field">Branch <input class="input" value="main"></label>      <label class="check"><input type="checkbox" class="checkbox" checked> Production only</label>    </div>    <footer class="dialog-footer">      <button type="button" class="btn" commandfor="filters-swipe" command="close">Reset</button>      <button type="button" class="btn btn-primary" commandfor="filters-swipe" command="close">        Apply      </button>    </footer>  </div></dialog><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root}>      <button type="button" className="btn" {...{ commandfor: 'filters-swipe', command: 'show-modal' }}>        Filters      </button>      <dialog id="filters-swipe" className="dialog dialog-drawer dialog-swipe" closedby="any" aria-labelledby="filters-swipe-title">        <div className="dialog-panel">          <header className="dialog-header">            <h2 className="dialog-title" id="filters-swipe-title">Filters</h2>            <p className="dialog-description">Narrow the list of deployments.</p>          </header>          <div className="dialog-body flex flex-col gap-md">            <label className="field">Branch <input className="input" defaultValue="main" /></label>            <label className="check">              <input type="checkbox" className="checkbox" defaultChecked /> Production only            </label>          </div>          <footer className="dialog-footer">            <button type="button" className="btn" {...{ commandfor: 'filters-swipe', command: 'close' }}>              Reset            </button>            <button type="button" className="btn btn-primary" {...{ commandfor: 'filters-swipe', command: 'close' }}>              Apply            </button>          </footer>        </div>      </dialog>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div {@attach attach}>  <button type="button" class="btn" commandfor="filters-swipe" command="show-modal">Filters</button>  <dialog id="filters-swipe" class="dialog dialog-drawer dialog-swipe" closedby="any" aria-labelledby="filters-swipe-title">    <div class="dialog-panel">      <header class="dialog-header">        <h2 class="dialog-title" id="filters-swipe-title">Filters</h2>        <p class="dialog-description">Narrow the list of deployments.</p>      </header>      <div class="dialog-body flex flex-col gap-md">        <label class="field">Branch <input class="input" value="main"></label>        <label class="check">          <input type="checkbox" class="checkbox" checked> Production only        </label>      </div>      <footer class="dialog-footer">        <button type="button" class="btn" commandfor="filters-swipe" command="close">Reset</button>        <button type="button" class="btn btn-primary" commandfor="filters-swipe" command="close">          Apply        </button>      </footer>    </div>  </dialog></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root">    <button type="button" class="btn" commandfor="filters-swipe" command="show-modal">      Filters    </button>    <dialog id="filters-swipe" class="dialog dialog-drawer dialog-swipe" closedby="any" aria-labelledby="filters-swipe-title">      <div class="dialog-panel">        <header class="dialog-header">          <h2 class="dialog-title" id="filters-swipe-title">Filters</h2>          <p class="dialog-description">Narrow the list of deployments.</p>        </header>        <div class="dialog-body flex flex-col gap-md">          <label class="field">Branch <input class="input" value="main"></label>          <label class="check">            <input type="checkbox" class="checkbox" checked> Production only          </label>        </div>        <footer class="dialog-footer">          <button type="button" class="btn" commandfor="filters-swipe" command="close">            Reset          </button>          <button type="button" class="btn btn-primary" commandfor="filters-swipe" command="close">            Apply          </button>        </footer>      </div>    </dialog>  </div></template>
패널을 가장자리 쪽으로 드래그하거나 옆의 배경막을 눌러 보세요.

스와이프는 다음과 같이 구성됩니다.

  • 패널은 브라우저가 움직입니다. 트랙은 스냅 지점이 있는 스크롤 컨테이너입니다. 스냅 지점은 열린 상태에서 멈추는 위치와, 패널을 밀어 닫을 때 이동하는 위치입니다. 닫히는 쪽에는 가장자리 바깥으로 뷰포트 크기만큼 이어지는 구간이 있습니다. 손가락, 트랙패드, 휠로 트랙을 스크롤하므로 손의 움직임을 따라가는 것, 튕기듯 밀었을 때의 관성, 멈출 위치를 정하는 것은 모두 브라우저가 처리합니다. 트랙은 패널을 끝에 둔 역방향 플렉스 라인이므로 스크립트 없이도 열린 상태의 위치에서 시작합니다.
  • 스크롤로 할 수 없는 일은 동작이 처리합니다. 패널이 어떤 방식으로든 트랙을 벗어나면 대화 상자를 닫습니다. closedby="any"의 기능도 되살립니다. 브라우저가 클릭을 감지하는 배경막을 트랙이 덮기 때문에, 패널 옆을 누르면 동작이 대화 상자를 닫습니다. 드래그로 스크롤할 수 없는 마우스로도 손잡이나 컨트롤 또는 본문이 아닌 부분을 잡아 패널을 끌 수 있게 하고, 놓으면 튕긴 방향의 위치나 더 가까운 위치로 보냅니다. 정밀한 포인터가 패널을 잡고 있는 동안에는 트랙의 스냅이 멈춥니다. 남은 배경막의 비율을 --dialog-scrim에 기록하므로 패널이 멀어질수록 배경막이 옅어집니다.
  • 대화 상자는 여전히 대화 상자입니다. Esc 키, 닫기 버튼, 포커스 가두기, 대화 상자를 연 버튼으로 돌아가는 포커스, 들어오고 나가는 슬라이드 효과는 다른 드로어나 시트와 같습니다.
  • 스크롤되는 본문은 자체 스크롤을 유지합니다. dialog-body 안에서 휠을 굴리면 본문이 스크롤되고, 마우스로 드래그하면 텍스트를 선택할 수 있습니다. 터치 화면에서는 본문의 맨 위에 닿은 뒤에도 계속 드래그하면 시트가 움직입니다.

스와이프는 바로 가기일 뿐입니다. 닫기 버튼이나 대화 상자를 닫는 동작을 남겨 두고, Esc 키도 유지하세요.

#디텐트

스와이프하는 시트에 dialog-detents를 추가하면 시트가 두 높이에 멈춥니다. 처음 열리는 높이인 뷰포트의 절반과 전체 높이입니다. 드래그하거나 튕기듯 밀면 두 높이 사이를 이동합니다. 전체 높이에서 아래로 튕기면 절반 높이에서 멈추며, 절반 높이에서 아래로 튕기면 시트가 닫힙니다. 손잡이는 접근 가능한 이름이 있는 <button>으로 만드세요. 누르거나 Enter 또는 Space 키를 누르면 시트가 다른 높이로 이동하고, ↑ 키는 전체 높이로 늘리며, ↓ 키는 절반 높이로 줄입니다. 손잡이의 aria-expanded는 시트가 전체 높이인지를 나타냅니다.

디텐트가 있는 시트

<button type="button" class="btn" commandfor="comments-sheet" command="show-modal">Comments</button><dialog id="comments-sheet" class="dialog dialog-sheet dialog-swipe dialog-detents" closedby="any" aria-labelledby="comments-sheet-title">  <div class="dialog-panel">    <button type="button" class="dialog-handle" aria-label="Sheet height"></button>    <header class="dialog-header">      <h2 class="dialog-title" id="comments-sheet-title">Comments</h2>      <p class="dialog-description">Five people reviewed this deployment.</p>    </header>    <div class="dialog-body flex flex-col gap-md">      <p class="m(0)">Ada: the build on main is green again.</p>      <p class="m(0)">Grace: the preview for the pricing page loads in 1.2s.</p>      <p class="m(0)">Linus: the cache headers on the fonts are right now.</p>      <p class="m(0)">Margaret: the rollback plan is in the runbook.</p>      <p class="m(0)">Alan: ship it after the 3pm check.</p>    </div>    <button type="button" class="btn btn-quiet btn-square btn-sm dialog-close" commandfor="comments-sheet" command="close" aria-label="Close">      <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>  </div></dialog><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import XIcon from '@master/icons-react/native/16/soft/x'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root}>      <button type="button" className="btn" {...{ commandfor: 'comments-sheet', command: 'show-modal' }}>        Comments      </button>      <dialog id="comments-sheet" className="dialog dialog-sheet dialog-swipe dialog-detents" closedby="any" aria-labelledby="comments-sheet-title">        <div className="dialog-panel">          <button type="button" className="dialog-handle" aria-label="Sheet height"></button>          <header className="dialog-header">            <h2 className="dialog-title" id="comments-sheet-title">Comments</h2>            <p className="dialog-description">Five people reviewed this deployment.</p>          </header>          <div className="dialog-body flex flex-col gap-md">            <p className="m(0)">Ada: the build on main is green again.</p>            <p className="m(0)">Grace: the preview for the pricing page loads in 1.2s.</p>            <p className="m(0)">Linus: the cache headers on the fonts are right now.</p>            <p className="m(0)">Margaret: the rollback plan is in the runbook.</p>            <p className="m(0)">Alan: ship it after the 3pm check.</p>          </div>          <button type="button" className="btn btn-quiet btn-square btn-sm dialog-close" {...{ commandfor: 'comments-sheet', command: 'close' }} aria-label="Close">            <XIcon className="icon" />          </button>        </div>      </dialog>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import XIcon from '@master/icons-svelte/native/16/soft/x'</script><div {@attach attach}>  <button type="button" class="btn" commandfor="comments-sheet" command="show-modal">    Comments  </button>  <dialog id="comments-sheet" class="dialog dialog-sheet dialog-swipe dialog-detents" closedby="any" aria-labelledby="comments-sheet-title">    <div class="dialog-panel">      <button type="button" class="dialog-handle" aria-label="Sheet height"></button>      <header class="dialog-header">        <h2 class="dialog-title" id="comments-sheet-title">Comments</h2>        <p class="dialog-description">Five people reviewed this deployment.</p>      </header>      <div class="dialog-body flex flex-col gap-md">        <p class="m(0)">Ada: the build on main is green again.</p>        <p class="m(0)">Grace: the preview for the pricing page loads in 1.2s.</p>        <p class="m(0)">Linus: the cache headers on the fonts are right now.</p>        <p class="m(0)">Margaret: the rollback plan is in the runbook.</p>        <p class="m(0)">Alan: ship it after the 3pm check.</p>      </div>      <button type="button" class="btn btn-quiet btn-square btn-sm dialog-close" commandfor="comments-sheet" command="close" aria-label="Close">        <XIcon class="icon" />      </button>    </div>  </dialog></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import XIcon from '@master/icons-vue/native/16/soft/x'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root">    <button type="button" class="btn" commandfor="comments-sheet" command="show-modal">      Comments    </button>    <dialog id="comments-sheet" class="dialog dialog-sheet dialog-swipe dialog-detents" closedby="any" aria-labelledby="comments-sheet-title">      <div class="dialog-panel">        <button type="button" class="dialog-handle" aria-label="Sheet height"></button>        <header class="dialog-header">          <h2 class="dialog-title" id="comments-sheet-title">Comments</h2>          <p class="dialog-description">Five people reviewed this deployment.</p>        </header>        <div class="dialog-body flex flex-col gap-md">          <p class="m(0)">Ada: the build on main is green again.</p>          <p class="m(0)">Grace: the preview for the pricing page loads in 1.2s.</p>          <p class="m(0)">Linus: the cache headers on the fonts are right now.</p>          <p class="m(0)">Margaret: the rollback plan is in the runbook.</p>          <p class="m(0)">Alan: ship it after the 3pm check.</p>        </div>        <button type="button" class="btn btn-quiet btn-square btn-sm dialog-close" commandfor="comments-sheet" command="close" aria-label="Close">          <XIcon class="icon" />        </button>      </div>    </dialog>  </div></template>
시트는 절반 높이로 열립니다. 위로 드래그하거나 손잡이를 누르거나, Tab 키로 손잡이로 이동한 뒤 ↑ 키와 ↓ 키를 눌러 보세요.

절반 높이에서는 시트의 아래쪽 절반이 푸터까지 포함해 가장자리 아래에 가려져 있습니다. 따라서 디텐트는 목록, 댓글, 지도처럼 둘러보는 용도이면서 작업 버튼이 위쪽에 있는 시트에 적합합니다. 뷰포트의 절반보다 낮은 시트는 전체 높이 하나에만 멈추며, 손잡이도 이를 알립니다.

#기능을 지원하지 않을 때

  • 스크립트가 실행되지 않으면 가장자리 바깥의 구간은 멈출 위치가 되지 않습니다(@media (scripting: enabled)). 패널을 놓으면 원래 위치로 되돌아가며, Esc 키와 닫기 버튼으로 대화 상자를 닫을 수 있습니다. 스크립트가 실행되는 곳에서는 반드시 동작을 연결하세요. 그렇지 않으면 놓은 패널이 화면 밖에 머무르고 페이지는 계속 비활성 상태로 남습니다.
  • 동작이 없으면 대화 상자가 닫힐 때까지 배경막이 옅어지지 않습니다. 배경막은 스크롤 기반 애니메이션을 사용하지 않습니다. 역방향 스크롤 컨테이너에서는 Chromium과 WebKit이 스크롤 타임라인과 뷰 타임라인을 서로 반대 방향으로 실행하기 때문입니다.
  • scroll-initial-target을 지원하는 브라우저(Chromium)에서는 디텐트가 있는 시트가 스크립트 실행 전부터 절반 높이로 열립니다. 다른 브라우저에서는 동작이 시트를 옮길 때까지 전체 높이로 열립니다.

스와이프는 Chromium과 WebKit에서 마우스와 휠로, Chromium에서는 터치로도 검증했습니다. 스크롤 스냅, 역방향 플렉스 스크롤, scrollend는 모든 최신 브라우저에서 지원됩니다.

#모션

대화 상자는 원래 크기의 97%로, 제자리보다 0.5rem 아래에서 시작해 280ms 동안 서서히 나타납니다. 사라지는 데는 160ms가 걸립니다. 스타일시트는 열기와 닫기 전환을 모두 CSS로 정의합니다. @starting-style은 처음 렌더링되는 프레임의 상태를 지정하고, display와 overlay는 allow-discrete로 전환되므로 대화 상자가 최상위 레이어를 벗어나기 전에 닫기 애니메이션이 재생됩니다. 동작 줄이기가 활성화되면 페이드 효과만 남습니다.

#접근성

  • aria-labelledby 속성이 대화 상자의 dialog-title을 가리키도록 지정해 대화 상자에 접근 가능한 이름을 부여하세요.
  • show-modal로 열면 포커스가 대화 상자 안으로 이동하고, 닫으면 대화 상자를 열었던 버튼으로 돌아갑니다. 사용자가 처음 사용할 필드에 autofocus 속성을 지정하세요. 데이터를 삭제하는 등 되돌리기 어려운 동작을 확인하는 대화 상자에서는 안전한 동작에 지정하세요.
  • command와 commandfor는 최신 Chrome, Edge, Firefox, Safari에서 지원됩니다. 이전 브라우저에서는 클릭 핸들러에서 dialog.showModal() 메서드를 호출하세요. 스타일시트는 그대로 사용합니다.
  • 스와이프만으로 닫을 수 있게 하지 마세요. 닫기 버튼이나 대화 상자를 닫는 동작을 남겨 두세요. Esc 키로도 여전히 닫을 수 있습니다. 디텐트가 있는 시트에서 손잡이는 "시트 높이"처럼 접근 가능한 이름이 있는 버튼입니다. 드래그할 때와 마찬가지로 버튼을 누르거나 키를 사용해 높이를 바꿀 수 있습니다. 디텐트가 없으면 손잡이는 보조 기술에서 숨겨진 홈입니다. 손잡이의 조작 영역은 64×24px이며, 터치 화면에서는 높이가 44px입니다.

#React, Svelte, Vue

dialog 컴포넌트는 애플리케이션 상태에 따라 대화 상자를 열고 닫으며, 브라우저에서 대화 상자가 열리거나 닫히면 이를 알립니다. 대화 상자를 여는 요소와 내부 요소는 페이지의 마크업에서 직접 정의합니다. 컴포넌트는 모든 대화 상자에 drawer 동작을 연결하므로, dialog-swipe와 dialog-panel을 갖춘 드로어나 시트는 스와이프로 닫을 수 있으며, 다른 방식으로 닫힐 때와 마찬가지로 컴포넌트가 이를 알립니다. dialog-swipe가 없는 대화 상자에서는 이 동작이 아무 일도 하지 않습니다. npx master-ui add dialog로 컴포넌트를 프로젝트에 복사하세요. 컴포넌트의 구성과 사용법은 React, Svelte, Vue에서 확인할 수 있습니다.

ui/dialog.tsx
'use client'import { useEffect, useId, useReducer, useRef, type ComponentProps, type ReactNode } from 'react'import { drawer } from '@master/ui/behaviors/drawer.js'export interface DialogProps extends Omit<ComponentProps<'dialog'>, 'open' | 'ref'> {  /** Whether the dialog is open, when this component is told. Leave it out and the trigger opens it. */  open?: boolean  onOpenChange?: (open: boolean) => void  /** The button that opens the dialog: spread what it is given on a button of your own. */  trigger?: (attributes: { commandfor: string, command: 'show-modal' }) => ReactNode}/** * A modal dialog. The browser opens it from the trigger, traps focus and closes it on Esc; this component * only opens and closes it from `open`, and says when the browser did. Its children are the contract's * parts: `dialog-header`, `dialog-body`, `dialog-footer`. A button inside closes it with * `commandfor={id}` and `command="close"`, or from a form with `method="dialog"`. * * A drawer or a sheet with `dialog-swipe` in its `className` holds a `dialog-panel` and is let go of to * close; the drawer behavior, attached to every dialog, closes it and says so here like any other close. */export function Dialog({ open, onOpenChange, trigger, className, id, children, ...dialog }: DialogProps) {  const generated = useId()  const name = id ?? generated  const element = useRef<HTMLDialogElement>(null)  const heard = useRef(onOpenChange)  /** What the owner knows: the last state it set or was told. */  const known = useRef(false)  const [tick, again] = useReducer((count: number) => count + 1, 0)  useEffect(() => { heard.current = onOpenChange })  useEffect(() => {    const root = element.current    if (!root || open === undefined) return    known.current = open    if (open && !root.open) root.showModal()    else if (!open && root.open) root.close()  }, [open, tick])  useEffect(() => {    const root = element.current    if (!root) return    const controller = new AbortController()    const report = () => {      if (root.open !== known.current) heard.current?.(known.current = root.open)      // An `open` this component is told wins: if its owner did not take the change, the dialog goes back.      again()    }    for (const type of ['toggle', 'close']) root.addEventListener(type, report, { signal: controller.signal })    const detach = drawer(root)    return () => {      controller.abort()      detach()    }  }, [])  return (    <>      {trigger?.({ commandfor: name, command: 'show-modal' })}      <dialog id={name} className={className ? `dialog ${className}` : 'dialog'} ref={element} {...{ closedby: 'any' }} {...dialog}>{children}</dialog>    </>  )}
ui/Dialog.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLDialogAttributes } from 'svelte/elements'  export interface DialogProps extends Omit<HTMLDialogAttributes, 'open'> {    /** Whether the dialog is open. Bind it, or leave it out and the trigger opens it. */    open?: boolean    onOpenChange?: (open: boolean) => void    /** The button that opens the dialog: spread what it is given on a button of your own. */    trigger?: Snippet<[{ commandfor: string, command: 'show-modal' }]>  }</script><script lang="ts">  import type { Attachment } from 'svelte/attachments'  import { drawer } from '@master/ui/behaviors/drawer.js'  let { open = $bindable(), onOpenChange, trigger, class: className, id, children, ...dialog }: DialogProps = $props()  const generated = $props.id()  const name = $derived(id ?? generated)  /** What the owner knows: the last state it set or was told. */  let known = false  const presence: Attachment<HTMLDialogElement> = (root) => {    const controller = new AbortController()    const report = () => {      if (root.open === known) return      open = known = root.open      onOpenChange?.(known)    }    for (const type of ['toggle', 'close']) root.addEventListener(type, report, { signal: controller.signal })    const detach = drawer(root)    $effect(() => {      if (open === undefined) return      known = open      if (open && !root.open) root.showModal()      else if (!open && root.open) root.close()    })    return () => {      controller.abort()      detach()    }  }</script><!--  @component  A modal dialog. The browser opens it from the trigger, traps focus and closes it on Esc; this component  only opens and closes it from `open`, and says when the browser did. Its children are the contract's  parts: `dialog-header`, `dialog-body`, `dialog-footer`. A button inside closes it with  `commandfor={id}` and `command="close"`, or from a form with `method="dialog"`.  A drawer or a sheet with `dialog-swipe` in its `class` holds a `dialog-panel` and is let go of to close;  the drawer behavior, attached to every dialog, closes it and says so here like any other close.-->{@render trigger?.({ commandfor: name, command: 'show-modal' })}<dialog id={name} class={['dialog', className]} closedby="any" {@attach presence} {...dialog}>{@render children?.()}</dialog>
ui/Dialog.vue
<script setup lang="ts">import { computed, nextTick, onBeforeUnmount, onMounted, useId, useTemplateRef, watch } from 'vue'import { drawer } from '@master/ui/behaviors/drawer.js'defineOptions({ inheritAttrs: false })const { id } = defineProps<{  id?: string}>()/** Whether the dialog is open: `v-model:open`. Leave it out and the trigger opens it. */const open = defineModel<boolean>('open')defineSlots<{  /** The button that opens the dialog: bind what it is given on a button of your own. */  trigger?: (attributes: { commandfor: string, command: 'show-modal' }) => unknown  default?: () => unknown}>()/* * A modal dialog. The browser opens it from the trigger, traps focus and closes it on Esc; this component * only opens and closes it from `open`, and says when the browser did. Its default slot is the contract's * parts: `dialog-header`, `dialog-body`, `dialog-footer`. A button inside closes it with * `commandfor` and `command="close"`, or from a form with `method="dialog"`. * * A drawer or a sheet with `dialog-swipe` in its `class` holds a `dialog-panel` and is let go of to close; * the drawer behavior, attached to every dialog, closes it and says so here like any other close. */const generated = useId()const name = computed(() => id ?? generated)const root = useTemplateRef<HTMLDialogElement>('root')/** What the owner knows: the last state it set or was told. */let known = falseconst sync = () => {  const dialog = root.value  if (!dialog || open.value === undefined) return  known = open.value  if (open.value && !dialog.open) dialog.showModal()  else if (!open.value && dialog.open) dialog.close()}const report = () => {  const dialog = root.value  if (!dialog) return  if (dialog.open !== known) open.value = known = dialog.open  // An `open` this component is told wins: if its owner did not take the change, the dialog goes back.  void nextTick(sync)}let detach: (() => void) | undefinedonMounted(() => {  if (root.value) detach = drawer(root.value)  sync()})onBeforeUnmount(() => detach?.())watch(open, sync, { flush: 'post' })</script><template>  <slot name="trigger" v-bind="{ commandfor: name, command: 'show-modal' as const }" />  <dialog :id="name" class="dialog" closedby="any" ref="root" v-bind="$attrs" @toggle="report" @close="report"><slot /></dialog></template>

#클래스

클래스설명
dialog오버레이 표면에는 aria-labelledby 또는 aria-label로 접근 가능한 이름을 지정한 dialog 요소를 사용합니다. 너비는 28rem이며 뷰포트 가장자리와 1rem 간격을 유지합니다
dialog-sm한 문장으로 된 확인 메시지에 쓰는 22rem 너비입니다. 기본값은 28rem입니다.적용할 클래스는 dialog입니다
dialog-lg너비는 40rem이며 기본값은 28rem입니다.적용할 클래스는 dialog입니다
dialog-drawer페이지를 보면서 작업할 수 있도록 인라인 끝 가장자리에 배치하는 너비 24rem의 패널입니다. 뷰포트 가장자리에서 8px 안쪽에 떠 있으며, 배치된 쪽 가장자리에서 슬라이드해 들어옵니다.적용할 클래스는 dialog입니다
dialog-drawer-startdialog-drawer와 함께 사용하면 탐색 메뉴를 담는 패널이 inline-start 가장자리에 18rem 너비로 배치됩니다.적용할 클래스는 dialog입니다
dialog-sheet아래쪽 가장자리에서 위로 올라오는 패널입니다. 아래쪽 모서리는 직각이며 홈 인디케이터와 겹치지 않습니다.적용할 클래스는 dialog입니다
dialog-swipedialog-drawer 또는 dialog-sheet와 함께 사용합니다. 대화 상자가 뷰포트 크기의 투명한 트랙이 되고, 그 안의 dialog-panel이 손가락, 트랙패드, 휠, 마우스를 따라 움직이며 놓으면 닫힙니다. drawer 동작을 연결하세요.적용할 클래스는 dialog입니다
dialog-detentsdialog-sheet 및 dialog-swipe와 함께 사용합니다. 시트는 가능한 최대 높이를 가지며, 뷰포트의 절반이 보이도록 열리고 절반 높이나 전체 높이에서 멈춥니다.적용할 클래스는 dialog입니다
dialog-paneldialog-swipe 안의 드로어 또는 시트 자체입니다. 표면 스타일을 적용하며 헤더, 본문, 푸터, 닫기 버튼을 담습니다.
dialog-handle잡기 손잡이로, 시트 위쪽 가장자리의 짧은 홈이며 dialog-panel의 시작 부분에 둡니다. dialog-detents가 적용된 시트에서는 기능을 나타내는 이름을 붙인 버튼으로 만들며, 동작이 이 버튼으로 시트를 움직이고 aria-expanded를 설정합니다. 그 외에는 aria-hidden="true"를 지정한 div로 만듭니다.
dialog-header시트 상단에 제목과 설명을 배치합니다
dialog-title대화 상자의 aria-labelledby가 이 제목을 참조하도록 지정하세요
dialog-description제목의 의미를 설명하는 문장으로, 제목 아래에 낮은 강조도로 표시합니다.
dialog-body헤더와 푸터 사이의 콘텐츠입니다. 남은 높이를 채우며, 콘텐츠가 길면 시트 안에서 스크롤됩니다.
dialog-footer동작 버튼을 담고 주 동작 버튼을 맨 마지막에 배치합니다. 대화 상자 너비가 22rem 미만이면 각 버튼을 전체 너비로 세로 배치하고 주 동작 버튼을 맨 위에 놓습니다.
dialog-close인라인 방향 끝쪽의 상단 모서리에 눈에 덜 띄는 정사각형 버튼을 배치합니다. 버튼에는 접근 가능한 이름이 필요합니다

#사용자 지정 속성

속성기본값설명
--dialog-width28rem선호 너비
--dialog-padding1.5rem구성 요소 둘레의 패딩
--dialog-radius1.25rem모서리 반경
--dialog-scrimdialog-swipe에서 남아 있는 배경막의 양으로, 1(설정하지 않으면 전체)에서 패널이 사라짐에 따라 0까지 줄어듭니다. drawer 동작이 기록합니다.

#소스

@master/ui/components/dialog.css
/* * Dialog: a native <dialog>, opened as a modal by a button with commandfor and command="show-modal". * The browser supplies the top layer, the focus trap, Escape and, with closedby="any", light dismiss. * The stylesheet supplies the overlay sheet, the scrim, and the motion in and out through @starting-style * and discrete transitions. Geometry: a 20px corner, 24px of padding, 10px controls. * * Swipe: with dialog-swipe a drawer or a sheet follows a finger, a trackpad or a wheel, and is let go of to * close. The dialog becomes the track the panel moves on: as large as the viewport, transparent, scrolled * and snapped, holding the dialog-panel, which wears the material, and an empty stretch past the edge the * panel rests on. Scroll snapping makes the panel rest open, at half height in a sheet with dialog-detents, * or gone past the edge; following the hand, the momentum and the fling are the browser's own. The track is * a reversed flex line where the panel rests at the end, so it starts scrolled to the open rest with no * script. The drawer behavior closes the dialog once the panel has gone, gives closedby="any" back on the * track, lets a mouse drag the panel (a mouse cannot scroll by dragging; the track stops snapping while a * fine pointer holds the panel), writes how much scrim is left to --dialog-scrim and gives the handle its * keys. The scrim is not a scroll-driven animation: in a reversed scroller Chromium and WebKit run scroll * and view timelines in opposite directions. Fallbacks: without scripting the gone rest is left out, so a * panel let go of springs back and Escape and the close buttons close it; without the behavior the scrim * stays whole until the dialog closes; without scroll-initial-target (outside Chromium) a sheet with * detents opens at full height until the behavior puts it at half. */@layer components.ui {  .dialog {    --dialog-width: 28rem;    --dialog-padding: 1.5rem;    --dialog-radius: 1.25rem;    --surface-color: var(--color-surface-floating);    /* The parts respond to the dialog's own width, not the viewport's. */    container: dialog / inline-size;    flex-direction: column;    gap: 1.25rem;    width: min(var(--dialog-width), calc(100% - 2rem));    max-width: none;    max-height: min(calc(100dvh - 2rem), 44rem);    margin: auto;    padding: var(--dialog-padding) 0;    border: 0;    border-radius: calc(var(--dialog-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    overflow: hidden;    background: var(--color-surface-floating);    color: var(--color-text-body);    box-shadow: var(--shadow-overlay);    font-size: .875rem;    line-height: 1.55;    /* Closed is where it leaves to: it fades and settles back half as far as it came, faster than it arrived. */    opacity: 0;    scale: .985;    translate: 0 .25rem;    transition-property: opacity, scale, translate, overlay, 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);      /* Where it arrives from, on the first frame it is rendered. */      @starting-style {        opacity: 0;        scale: .97;        translate: 0 .5rem;      }    }    /* The scrim dims and softens the page; it fades with the dialog. */    &::backdrop {      background: var(--color-surface-scrim);      backdrop-filter: blur(3px);      opacity: 0;      transition-property: opacity, overlay, display;      transition-duration: var(--duration-quick);      transition-timing-function: var(--easing-glide);      transition-behavior: allow-discrete;    }    &[open]::backdrop {      opacity: 1;      transition-duration: var(--duration-base);    }    @starting-style {      &[open]::backdrop {        opacity: 0;      }    }    &:focus-visible {      outline: none;    }    &.dialog-sm {      --dialog-width: 22rem;    }    &.dialog-lg {      --dialog-width: 40rem;    }    /*     * Drawer: a panel on the inline-end edge for work that keeps the page in view. It floats 8px inside the     * viewport, so its corner and its shadow stay whole, and it slides in from the edge it rests on. Like the     * sheet it keeps clear of what the device lays over the page: the status bar and the home indicator above     * and below it, and in landscape the notch at either side, which the device reports on both.     */    &.dialog-drawer {      --dialog-width: 24rem;      --dialog-edge-top: max(.5rem, env(safe-area-inset-top));      --dialog-edge-bottom: max(.5rem, env(safe-area-inset-bottom));      --dialog-edge-inline: max(.5rem, env(safe-area-inset-left), env(safe-area-inset-right));      --dialog-from: calc(100% + var(--dialog-edge-inline));      width: min(var(--dialog-width), calc(100% - 2 * var(--dialog-edge-inline)));      height: calc(100dvh - var(--dialog-edge-top) - var(--dialog-edge-bottom));      max-height: none;      margin: var(--dialog-edge-top) var(--dialog-edge-inline) var(--dialog-edge-bottom);      margin-inline-start: auto;      scale: 1;      translate: var(--dialog-from) 0;      &:dir(rtl) {        --dialog-from: calc(-100% - var(--dialog-edge-inline));      }      &[open] {        translate: 0 0;        @starting-style {          scale: 1;          translate: var(--dialog-from) 0;        }      }    }    /*     * Start: the same panel on the inline-start edge, where navigation lives. A sidebar that has left a narrow     * layout comes back as this drawer. Use it together with dialog-drawer.     */    &.dialog-drawer.dialog-drawer-start {      --dialog-width: 18rem;      --dialog-from: calc(-100% - var(--dialog-edge-inline));      margin-inline: var(--dialog-edge-inline) auto;      &:dir(rtl) {        --dialog-from: calc(100% + var(--dialog-edge-inline));      }    }    /*     * Sheet: a panel that rises from the bottom edge, for a task on a small screen or a short list of     * choices. It spans the width up to --dialog-width, squares its lower corners and clears the home indicator.     */    &.dialog-sheet {      width: min(var(--dialog-width), 100%);      max-height: calc(100dvh - 3rem);      margin: auto auto 0;      padding-bottom: max(var(--dialog-padding), env(safe-area-inset-bottom));      border-end-start-radius: 0;      border-end-end-radius: 0;      scale: 1;      translate: 0 100%;      &[open] {        translate: 0 0;        @starting-style {          scale: 1;          translate: 0 100%;        }      }    }    /*     * Swipe: the dialog is the track, the whole viewport, and the panel inside it is the drawer or the sheet.     * Only the panel takes the pointer, so a press beside it lands on the scrim, and a wheel there moves nothing.     * It enters and leaves as the drawer or the sheet does: the whole track slides.     */    &.dialog-swipe {      inset: 0;      width: auto;      height: auto;      max-width: none;      max-height: none;      margin: 0;      padding: 0;      gap: 0;      border-radius: 0;      overflow: auto;      overscroll-behavior: contain;      scrollbar-width: none;      background: transparent;      box-shadow: none;      pointer-events: none;      &::-webkit-scrollbar {        display: none;      }      /* The stretch past the edge, as large as the track: where the panel goes when it is let go of. */      &::after {        content: '';        flex: none;      }      /* The gone rest exists only where a script can close the dialog that rests there. */      @media (scripting: enabled) {        &::after {          scroll-snap-align: start;        }      }      @media (prefers-reduced-motion: no-preference) {        scroll-behavior: smooth;      }      /* A mouse drags the panel by scrolling the track from the behavior; the track does not snap meanwhile. */      @media (pointer: fine) {        &:has(.dialog-panel:active) {          scroll-snap-type: none;        }      }    }    /* The scrim thins as the panel leaves: the behavior writes how much of it is left to --dialog-scrim. */    &.dialog-swipe::backdrop {      background: color-mix(in oklab, var(--color-surface-scrim) calc(var(--dialog-scrim, 1) * 100%), transparent);      backdrop-filter: blur(calc(var(--dialog-scrim, 1) * 3px));      pointer-events: auto;    }    /* A reader who asks for less transparency gets the scrim without the blur behind it, swiped or not. */    @media (prefers-reduced-transparency: reduce) {      &::backdrop, &.dialog-swipe::backdrop {        backdrop-filter: none;      }    }    /* A swiped drawer moves across: the panel rests at the inline end, the stretch lies before it. */    &.dialog-drawer.dialog-swipe {      width: auto;      height: auto;      margin: 0;      flex-direction: row-reverse;      scroll-snap-type: x mandatory;      &::after {        inline-size: 100%;      }    }    &.dialog-drawer.dialog-drawer-start.dialog-swipe {      margin: 0;      flex-direction: row;    }    /* A swiped sheet moves down: the panel rests on the bottom edge, the stretch lies above it. */    &.dialog-sheet.dialog-swipe {      width: auto;      max-height: none;      margin: 0;      padding: 0;      flex-direction: column-reverse;      scroll-snap-type: y mandatory;      &::after {        block-size: 100%;      }    }    @media (prefers-reduced-motion: reduce) {      scale: none;      translate: none;      &[open], &.dialog-drawer, &.dialog-drawer[open], &.dialog-sheet, &.dialog-sheet[open] {        scale: none;        translate: none;        @starting-style {          scale: none;          translate: none;        }      }    }    /*     * The edge in forced colors, also while the dialog itself has focus, which takes away its outline above.     * A swiped dialog is only the track: its panel draws the edge.     */    @media (forced-colors: active) {      &, &:focus-visible {        outline: 1px solid CanvasText;        outline-offset: -1px;      }      &.dialog-swipe, &.dialog-swipe:focus-visible {        outline: none;      }    }  }  /* The title and what it means, at the top of the sheet. */  .dialog-header {    display: grid;    flex: none;    gap: .375rem;    padding: 0 var(--dialog-padding);  }  /* Leave the title clear of the close button. */  .dialog:has(.dialog-close) .dialog-header {    padding-inline-end: calc(var(--dialog-padding) + 2rem);  }  .dialog-title {    margin: 0;    color: var(--color-text-strong);    font: var(--font-weight-control) 1.0625rem/1.35 var(--font-family-sans);    font-feature-settings: inherit;    letter-spacing: -.01em;    text-wrap: balance;    overflow-wrap: anywhere;  }  .dialog-description {    margin: 0;    color: var(--color-text-muted);    text-wrap: pretty;    overflow-wrap: anywhere;  }  /* The body takes the remaining height and scrolls inside the sheet; a little block padding keeps focus rings whole. */  .dialog-body {    flex: 1 1 auto;    min-height: 0;    margin-block: -.25rem;    padding: .25rem var(--dialog-padding);    overflow-y: auto;    overscroll-behavior: contain;    scrollbar-width: thin;    scrollbar-color: var(--color-line-strong) transparent;  }  /* Actions end the sheet, the main one last. In a narrow dialog they stack at full width, the main one first. */  .dialog-footer {    display: flex;    flex: none;    flex-wrap: wrap;    justify-content: flex-end;    gap: .5rem;    padding: .25rem var(--dialog-padding) 0;    @container dialog (inline-size < 22rem) {      flex-direction: column-reverse;      align-items: stretch;    }  }  /* A quiet square button in the corner; give it an accessible name. */  .dialog .dialog-close {    position: absolute;    inset-block-start: calc(var(--dialog-padding) - .4375rem);    inset-inline-end: calc(var(--dialog-padding) - .4375rem);  }  /*   * The panel: in a dialog-swipe, the drawer or the sheet itself. It wears the dialog's material and lays out   * its parts as the dialog does, and it is the container their queries measure. It clips its corners   * without becoming a scroller, so what it holds snaps on the track.   */  .dialog-swipe .dialog-panel {    --surface-color: var(--color-surface-floating);    position: relative;    container: dialog / inline-size;    display: flex;    flex: none;    flex-direction: column;    gap: 1.25rem;    box-sizing: border-box;    padding: var(--dialog-padding) 0;    border-radius: calc(var(--dialog-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    overflow: clip;    background: var(--color-surface-floating);    box-shadow: var(--shadow-overlay);    pointer-events: auto;    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }  /*   * In a drawer it floats 8px inside the viewport, at the inline end or, with dialog-drawer-start, the start,   * and clear of the safe areas as the drawer itself is.   */  .dialog-drawer .dialog-panel {    width: min(var(--dialog-width), calc(100% - 2 * var(--dialog-edge-inline)));    margin: var(--dialog-edge-top) var(--dialog-edge-inline) var(--dialog-edge-bottom);    scroll-margin: var(--dialog-edge-top) var(--dialog-edge-inline) var(--dialog-edge-bottom);    scroll-snap-align: end;  }  .dialog-drawer-start .dialog-panel {    scroll-snap-align: start;  }  /* In a sheet it stands on the bottom edge with square lower corners, clear of the home indicator. */  .dialog-sheet .dialog-panel {    width: min(var(--dialog-width), 100%);    max-height: calc(100% - 3rem);    margin-inline: auto;    padding-bottom: max(var(--dialog-padding), env(safe-area-inset-bottom));    border-end-start-radius: 0;    border-end-end-radius: 0;    scroll-snap-align: end;  }  /*   * Detents: the sheet is as tall as it may be and also rests showing half the track, where it opens. The   * half rest is an empty box from the panel's top edge down half the track, snapped to the track's bottom.   */  .dialog-detents .dialog-panel {    height: calc(100% - 3rem);    &::before {      content: '';      position: absolute;      inset-block-start: 0;      inset-inline: 0;      block-size: calc((100% + 3rem) / 2);      pointer-events: none;      scroll-snap-align: end;      /* A fling from full height stops here; only one from half height lets the sheet go. */      scroll-snap-stop: always;      scroll-initial-target: nearest;    }  }  /* On a touch screen a drag that reaches the top of a scrolled body goes on to move the sheet. */  @media (pointer: coarse) {    .dialog-sheet.dialog-swipe .dialog-body {      overscroll-behavior-y: auto;    }  }  /*   * The grab handle: a short groove in the sheet's top edge, centered over the title. Its target is 64 by   * 24px, 88 by 44px on a touch screen; the groove keeps its size. It takes ink while it is held. In a sheet   * with dialog-detents it is a button the behavior gives keys: it moves the sheet between half and full height   * and says which with aria-expanded. Elsewhere it only shows where to take hold, and is hidden from assistive technology.   */  .dialog-handle {    position: absolute;    inset-block-start: 0;    inset-inline: 0;    z-index: 1;    width: 4rem;    height: var(--dialog-padding);    margin: 0 auto;    padding: 0;    border: 0;    outline: none;    background: none;    color: inherit;    cursor: grab;    appearance: none;    /* A pan still moves the track; a double tap does not zoom the page. */    touch-action: manipulation;    -webkit-tap-highlight-color: transparent;    &::before {      content: '';      position: absolute;      inset-block-start: .5rem;      inset-inline: 0;      width: 2.25rem;      height: .3125rem;      margin-inline: auto;      border-radius: 999px;      corner-shape: round;      background: var(--color-line-strong);      transition: background-color var(--duration-quick) var(--easing-glide);    }    @media (hover: hover) {      &:hover::before {        background: var(--color-line-mark);      }    }    &:active {      cursor: grabbing;    }    &:active::before {      background: var(--color-text-muted);    }    &:focus-visible::before {      @apply --focus-ring;    }    @media (pointer: coarse) {      width: 5.5rem;      height: 2.75rem;    }    @media (forced-colors: active) {      &::before {        background: CanvasText;      }      &:focus-visible::before {        outline-color: Highlight;      }    }  }  /* While a modal dialog is open the page behind it does not scroll. */  :root:has(.dialog:modal) {    overflow: hidden;  }}