导航

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>
将面板拖向边缘,或点击旁边的遮罩。

滑动关闭的实现方式:

  • 由浏览器移动面板。 轨道是一个带有吸附点的滚动容器:一个是打开时的停靠位置,另一个是越过边缘、与视口一样长的区域,面板松手后会滑到那里。手指、触控板和滚轮都能滚动它,因此跟手移动、轻扫的惯性以及最终停在哪里,都由浏览器自行处理。轨道采用反向排列的 Flex 布局,面板位于其末端,因此无需脚本即可从打开时的停靠位置开始。
  • 行为脚本处理滚动做不到的事。 无论面板以何种方式离开轨道,脚本都会在其离开后关闭对话框。它恢复 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 加到应首先获得焦点的字段上。确认破坏性操作时,将它加到安全的操作上。
  • 当前版本的 Chrome、Edge、Firefox 和 Safari 均支持 command 和 commandfor。在旧版浏览器中,从点击事件处理函数调用 dialog.showModal(),继续使用同一份样式表。
  • 滑动绝不能是唯一的关闭方式:保留关闭按钮或能关闭对话框的操作,Esc 仍然有效。在带停靠高度的底部面板中,手柄是带有无障碍名称(例如“底部面板高度”)的按钮,按键和点击都能像拖动一样改变高度;没有停靠高度时,手柄是对辅助技术隐藏的凹槽。手柄的命中区域宽 64px、高 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-start与 dialog-drawer 搭配使用,将宽度为 18rem 的面板放在行内起始边缘,用于容纳导航。与 dialog 一同使用
dialog-sheet从底边升起的面板,下方两角为直角,并避开主屏幕指示条。与 dialog 一同使用
dialog-swipe搭配 dialog-drawer 或 dialog-sheet:对话框变为与视口同大的透明轨道,其中的 dialog-panel 跟随手指、触控板、滚轮或鼠标移动,松手即关闭。需挂载 drawer 行为脚本与 dialog 一同使用
dialog-detents搭配 dialog-sheet 和 dialog-swipe:底部面板达到允许的最大高度,打开时显示半个视口,可停在半高或全高处与 dialog 一同使用
dialog-panel在 dialog-swipe 中,即抽屉或底部面板本身:带有材质,容纳标题栏、主体、页脚和关闭按钮
dialog-handle拖动手柄:底部面板顶边上的一道短凹槽,位于其 dialog-panel 的开头。在带 dialog-detents 的底部面板中,使用以其作用命名的按钮,行为脚本借此移动面板并设置 aria-expanded;其他情况下使用带 aria-hidden="true" 的 div
dialog-header在面板顶部放置标题和说明
dialog-title标题。将 dialog 的 aria-labelledby 指向该标题。
dialog-description标题下方解释标题含义的低强调说明
dialog-body头部和底部之间的内容。占据剩余高度,内容过长时在面板内滚动
dialog-footer操作区,主操作排在最后。对话框宽度小于 22rem 时,各操作占满宽度并纵向排列,主操作排在最前
dialog-close在面板顶部的行内末端放置一个视觉权重较低的方形按钮,并为按钮提供无障碍名称。

#自定义属性

属性默认值说明
--dialog-width28rem首选宽度
--dialog-padding1.5rem各组成部分外围的内边距
--dialog-radius1.25rem圆角半径
--dialog-scrim在 dialog-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;  }}