打开一张从屏幕边缘滑出、可拖动、可调整大小的面板。

抽屉让一项任务拥有自己的面板(sheet),而不必离开页面。它共享 Dialog 的焦点与关闭行为,并在此基础上加入拖动、吸附点,以及一个可以用键盘操作的手柄。

import "@ui-sdk/web/drawer"
import { createElement, Minus, Plus } from "lucide"
const goal = { initial: 350, min: 200, max: 400, step: 10 }

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-drawer>
      <ui-drawer-trigger><button>Open Drawer</button></ui-drawer-trigger>
      <ui-drawer-backdrop hidden></ui-drawer-backdrop>
      <ui-drawer-content hidden>
        <div data-slot="grip" aria-hidden="true"></div>

        <div data-slot="stack">
          <ui-drawer-title>Move goal</ui-drawer-title>
          <ui-drawer-description>Set your daily activity goal.</ui-drawer-description>
        </div>

        <div data-slot="row">
          <button type="button" aria-label="Decrease">${createElement(Minus, { "aria-hidden": "true" }).outerHTML}</button>
          <div data-slot="stack">
            <div aria-live="polite"></div>
            <div data-slot="hint">Calories/day</div>
          </div>
          <button type="button" aria-label="Increase">${createElement(Plus, { "aria-hidden": "true" }).outerHTML}</button>
        </div>

        <div data-slot="stack">
          <ui-drawer-close value="submit"><button data-variant="solid">Submit</button></ui-drawer-close>
          <ui-drawer-close><button>Cancel</button></ui-drawer-close>
        </div>
      </ui-drawer-content>
    </ui-drawer>
  `
  const value = root.querySelector("[aria-live]")!
  const decrease = root.querySelector<HTMLButtonElement>(
    '[aria-label="Decrease"]'
  )!
  const increase = root.querySelector<HTMLButtonElement>(
    '[aria-label="Increase"]'
  )!
  let calories = goal.initial
  const show = () => {
    value.textContent = String(calories)
    decrease.disabled = calories <= goal.min
    increase.disabled = calories >= goal.max
  }
  decrease.addEventListener("click", () => {
    calories -= goal.step
    show()
  })
  increase.addEventListener("click", () => {
    calories += goal.step
    show()
  })
  show()
}

export { mount }
打开抽屉,调整每日目标,然后按 Submit 或 Cancel。你也可以按 Escape、在外部按压,或者把面板拖向它所在的边缘来关闭它。

安装

npm install @ui-sdk/web @ui-sdk/core

导入组件来注册它的元素。这个导入在服务端是安全的。

import "@ui-sdk/web/drawer"

组合

用下面的组合构建一个 ui-drawer:

ui-drawer
├── ui-drawer-trigger
│   └── button
├── ui-drawer-backdrop
└── ui-drawer-content
    ├── ui-drawer-title
    ├── ui-drawer-description
    └── ui-drawer-close
        └── button

内容就是面板。抽屉把它放进一个全屏视口,并用 translate 移动它。给它大小、表面和圆角;定位和位移交给抽屉。给遮罩一个颜色,比如 bg-black/30;不透明度由抽屉管理。给内容和遮罩加上 hidden,让它们在元素升级之前保持隐藏。

用法

导入各个部件并把它们组合起来:

<script type="module">
  import "@ui-sdk/web/drawer"
</script>

<ui-drawer>
  <ui-drawer-trigger><button>Filters</button></ui-drawer-trigger>
  <ui-drawer-backdrop hidden></ui-drawer-backdrop>
  <ui-drawer-content hidden>
    <ui-drawer-title>Filters</ui-drawer-title>
    <ui-drawer-description>Narrow down the results.</ui-drawer-description>
    <ui-drawer-close><button>Done</button></ui-drawer-close>
  </ui-drawer-content>
</ui-drawer>

可滚动内容

把长内容放进内部的 min-h-0 flex-1 overflow-y-auto 区域。向下拖动会先滚动这个区域;到达顶部后,同一个手势就能移动抽屉。initial-focus="content" 让焦点从面板本身开始。

import "@ui-sdk/web/drawer"

const paragraphs = [
  "The drawer rises from any edge, rests on snap points and follows your finger with the same spring as a system sheet.",
  "Snap points take fractions of the screen, pixels, rem, percentages or the content's own size. Points that land within a pixel of each other merge into one.",
  "Dragging a list scrolls it until it reaches the top, and then the same gesture moves the drawer, so closing a long sheet never needs two tries.",
  "The handle steps through the snap points with a press, the arrow keys, Home and End. Screen readers on phones adjust it like a slider.",
  "Below a snap point you choose, the page behind stays usable and undimmed, like a map with a sheet of results.",
  "Drawers opened from inside each other stack, and the one beneath steps back while the new one rises.",
  "The on-screen keyboard pushes the drawer up, and the focused field scrolls into view inside it, never the page.",
  "With reduced motion, drawers fade in and out instead of sliding.",
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-drawer>
      <ui-drawer-trigger><button>Scrollable Content</button></ui-drawer-trigger>
      <ui-drawer-backdrop hidden></ui-drawer-backdrop>
      <ui-drawer-content initial-focus="content" hidden>
        <div data-slot="grip" aria-hidden="true"></div>
        <div data-slot="stack">
          <ui-drawer-title>Release notes</ui-drawer-title>
          <ui-drawer-description>Everything new in the drawer.</ui-drawer-description>
        </div>
        <div data-slot="scroll">
          ${[...paragraphs, ...paragraphs].map((paragraph) => `<p data-slot="hint">${paragraph}</p>`).join("")}
        </div>
        <div data-slot="stack">
          <ui-drawer-close><button data-variant="solid">Got It</button></ui-drawer-close>
        </div>
      </ui-drawer-content>
    </ui-drawer>
  `
}

export { mount }
打开长面板并滚动它的文字。在顶部向下拖动可以移动面板;使用键盘时,Tab 会到达控件,Escape 会关闭它。

面板里的字段、滑块和颜色区域保留各自的拖动。对于你自己的拖动面,比如画布或地图,给它加上 data-drawer-no-drag,从这里开始的拖动就不会移动抽屉。

方向

side 选择 bottom、top、left 或 right。逻辑方向 start 和 end 跟随文字方向。内容的 data-side 告诉你该给哪条物理边缘设置样式。

侧边抽屉可以启用 prevent-edge-swipe,避免边缘手势触发 iOS Safari 的后退或前进导航。它也会阻止贴在这些边缘上的点击,所以只在你需要这个取舍时使用。

import "@ui-sdk/web/drawer"

const sides = [
  {
    side: "top",
    label: "Top",
    title: "Notifications",
    description: "You're all caught up.",
  },
  {
    side: "right",
    label: "Right",
    title: "Cart",
    description: "2 items, $84.00.",
  },
  {
    side: "bottom",
    label: "Bottom",
    title: "Share",
    description: "Send this page to your team.",
  },
  {
    side: "left",
    label: "Left",
    title: "Menu",
    description: "Jump to a section of the docs.",
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="row">
      ${sides
        .map(
          ({
            side,
            label,
            title,
            description,
          }) => `<ui-drawer side="${side}" ${side === "left" || side === "right" ? "prevent-edge-swipe" : ""}>
            <ui-drawer-trigger><button>${label}</button></ui-drawer-trigger>
            <ui-drawer-backdrop hidden></ui-drawer-backdrop>
            <ui-drawer-content hidden>
              <div data-slot="stack">
                <ui-drawer-title>${title}</ui-drawer-title>
                <ui-drawer-description>${description}</ui-drawer-description>
              </div>
              <ui-drawer-close><button data-variant="solid">Close</button></ui-drawer-close>
            </ui-drawer-content>
          </ui-drawer>`
        )
        .join("")}
    </div>
  `
}

export { mount }
从每条边缘打开一张面板。把它拖回那条边缘、在外部按压,或按 Escape 来关闭它。

吸附点

snap-points 是抽屉可以停靠的位置,以逗号分隔的列表表示。它在第一个位置打开,或者在 default-snap-point 处打开;拖动后会停在另一个位置。快速甩动可以跳过中间的位置。

值大小
0.5沿抽屉轴线的视口一半。
320 或 "320px"像素;大于 1 的数字是像素值。
"20rem"根字号的倍数。
"50%"视口的百分比。
"content"面板自身的大小,默认值。

面板的 CSS 尺寸就是上限:1 不能把一张矮面板撑满屏幕。如果最大的吸附点应该几乎填满屏幕,就用 h-[calc(100dvh-3rem)] 这样的高度。内容或可用空间变化时,抽屉会重新测量;停靠点因此移动时会报告 content-resize。

Handle 部件包装一个带无障碍名称的按钮。按压它会移到下一个更大的吸附点,到达最大后回绕到最小的吸附点。沿抽屉轴线的方向键每次移动一个吸附点,不会回绕;Home 和 End 移到两端。canExpand 和 canCollapse 让示例显示还剩哪些移动。

如果面板只有一个吸附点,就用装饰性的横条代替不可用的按钮。

import "@ui-sdk/web/drawer"

const places = [
  { name: "Blue Bottle Coffee", detail: "Coffee · 0.2 mi" },
  { name: "Tartine Bakery", detail: "Bakery · 0.4 mi" },
  { name: "Dolores Park", detail: "Park · 0.5 mi" },
  { name: "Mission Dolores", detail: "Landmark · 0.6 mi" },
  { name: "Ritual Coffee Roasters", detail: "Coffee · 0.7 mi" },
  { name: "Bi-Rite Creamery", detail: "Ice cream · 0.7 mi" },
  { name: "Alamo Square", detail: "Park · 1.1 mi" },
  { name: "The Castro Theatre", detail: "Cinema · 1.2 mi" },
  { name: "Ferry Building", detail: "Market · 2.3 mi" },
  { name: "Coit Tower", detail: "Landmark · 2.9 mi" },
  { name: "Golden Gate Park", detail: "Park · 3.0 mi" },
  { name: "Lands End", detail: "Trail · 5.4 mi" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-drawer snap-points="0.25,0.5,1" default-snap-point="0.5" expand-on-scroll>
      <ui-drawer-trigger><button>Find a Place</button></ui-drawer-trigger>
      <ui-drawer-backdrop hidden></ui-drawer-backdrop>
      <ui-drawer-content hidden>
        <ui-drawer-handle><button aria-label="Resize"></button></ui-drawer-handle>
        <div data-slot="stack">
          <ui-drawer-title>Places nearby</ui-drawer-title>
          <ui-drawer-description>Drag the drawer, or press the handle, to see more.</ui-drawer-description>
        </div>
        <div data-slot="scroll">
          <ul data-slot="list">
            ${places
              .map(
                (place) => `<li>
                  <div>${place.name}</div>
                  <div data-slot="hint">${place.detail}</div>
                </li>`
              )
              .join("")}
          </ul>
        </div>
      </ui-drawer-content>
    </ui-drawer>
  `
}

export { mount }
在中间吸附点打开面板。拖动它、按压手柄,或者 Tab 到手柄并用 Up、Down、Home 和 End 试试其他停靠位置。

受控

设置元素的 open 和 snapPoint property,并监听 openchange 和 snappointchange;attribute 设置它们的起始值。你可以分别控制打开状态和吸附点。用 event.preventDefault() 取消一次提议的变更;被取消的滑动会弹回。openchangecomplete 在面板停稳后触发。

<ui-drawer snap-points="0.25,0.5,1" snap-point="0.5"></ui-drawer>

<script type="module">
  const drawer = document.querySelector("ui-drawer")
  drawer.addEventListener(
    "openchange",
    (event) => (open.checked = event.detail.value)
  )
  drawer.addEventListener(
    "snappointchange",
    (event) => (size.value = String(event.detail.value))
  )
  drawer.open = true
  drawer.snapPoint = 1
</script>

不可关闭

当 dismissible="false" 时,Escape、外部按压、返回手势和滑动都会让抽屉保持打开。dismissattempt 告诉你尝试了什么,这样你可以提供一条丢弃未保存工作的途径。Close 部件、触发器和控制器仍然可以主动关闭它。

<ui-drawer dismissible="false">
  <ui-drawer-trigger><button>Write a Post</button></ui-drawer-trigger>
  <ui-drawer-backdrop hidden></ui-drawer-backdrop>
  <ui-drawer-content hidden>
    <ui-drawer-close id="discard" hidden
      ><button>Discard</button></ui-drawer-close
    >
    <ui-drawer-close value="post"><button>Post</button></ui-drawer-close>
  </ui-drawer-content>
</ui-drawer>

<script type="module">
  const drawer = document.querySelector("ui-drawer")
  drawer.addEventListener("dismissattempt", () => (discard.hidden = false))
</script>

当页面应该在一张小面板旁边保持可用时,设置 modal-above。在这个位置或以下,页面不变暗、不进入不可交互(inert)状态,也没有滚动锁定和 aria-modal。超过这个位置时,modal 生效。切换发生在抽屉停稳时,并且不移动焦点;data-interactive 暴露页面可用的状态。

modal 的选项与 Dialog 相同:true 阻止页面交互,"trap-focus" 把 Tab 保持在内部,同时页面仍然可用,false 允许焦点离开。点击页面也会关闭 "trap-focus" 抽屉,而非模态抽屉只有在启用 close-on-outside-press 时才会在外部按压时关闭。

import "@ui-sdk/web/drawer"

const places = [
  { name: "Blue Bottle Coffee", detail: "Coffee · 0.2 mi" },
  { name: "Tartine Bakery", detail: "Bakery · 0.4 mi" },
  { name: "Dolores Park", detail: "Park · 0.5 mi" },
  { name: "Mission Dolores", detail: "Landmark · 0.6 mi" },
  { name: "Ritual Coffee Roasters", detail: "Coffee · 0.7 mi" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ul data-slot="list" aria-label="Places">
        ${places
          .map(
            (place) => `<li>
              <button type="button" data-place="${place.name}">${place.name}<span data-slot="hint">${place.detail}</span></button>
            </li>`
          )
          .join("")}
      </ul>
      <ui-drawer snap-points="0.2,0.6" modal-above="0.2">
        <ui-drawer-trigger><button>Get Directions</button></ui-drawer-trigger>
        <ui-drawer-backdrop hidden></ui-drawer-backdrop>
        <ui-drawer-content hidden>
          <ui-drawer-handle><button aria-label="Resize"></button></ui-drawer-handle>
          <div data-slot="row">
            <div data-slot="stack">
              <ui-drawer-title></ui-drawer-title>
              <ui-drawer-description></ui-drawer-description>
            </div>
            <ui-drawer-close><button>Done</button></ui-drawer-close>
          </div>
          <ol data-slot="stack">
            <li>Head north on Valencia St.</li>
            <li>Turn left onto 18th St.</li>
            <li></li>
          </ol>
        </ui-drawer-content>
      </ui-drawer>
    </div>
  `
  const content = root.querySelector("ui-drawer-content")!
  const title = root.querySelector("ui-drawer-title")!
  const description = root.querySelector("ui-drawer-description")!
  const arrival = root.querySelector("ol li:last-child")!
  const buttons = [...root.querySelectorAll<HTMLButtonElement>("[data-place]")]
  const select = (destination: string) => {
    for (const button of buttons) {
      button.setAttribute(
        "aria-pressed",
        String(button.dataset.place === destination)
      )
    }
    title.textContent = `To ${destination}`
    arrival.textContent = `Arrive at ${destination}.`
  }
  const describe = () => {
    description.textContent = content.hasAttribute("data-interactive")
      ? "12 min walk. Pick another place behind the sheet."
      : "12 min walk. Drag the sheet down to see the places."
  }
  for (const button of buttons) {
    button.addEventListener("click", () => select(button.dataset.place!))
  }
  new MutationObserver(describe).observe(content, {
    attributes: true,
    attributeFilter: ["data-interactive"],
  })
  select(places[0].name)
  describe()
}

export { mount }
在小吸附点打开 Get Directions,选择面板后面的另一个地点。展开它让面板变为模态,再收起它重新使用页面。

嵌套抽屉

在另一个抽屉里打开的抽屉会加入它的栈。Escape 和外部按压只影响最上层的抽屉;关闭父级也会关闭它的子级。--drawer-stack 跟随其上方面板的打开和拖动而变化,所以父级可以用 [scale:calc(1-var(--drawer-stack)*0.04)] 缩小并后退。

import "@ui-sdk/web/drawer"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-drawer>
      <ui-drawer-trigger><button>Account</button></ui-drawer-trigger>
      <ui-drawer-backdrop hidden></ui-drawer-backdrop>
      <ui-drawer-content hidden>
        <div data-slot="grip" aria-hidden="true"></div>
        <div data-slot="stack">
          <ui-drawer-title>Account</ui-drawer-title>
          <ui-drawer-description>Manage how you sign in.</ui-drawer-description>
        </div>
        <dl>
          <div data-slot="row">
            <dt>Email</dt>
            <dd>hollis@example.com</dd>
          </div>
          <div data-slot="row">
            <dt>Password</dt>
            <dd>Changed 3 months ago</dd>
          </div>
          <div data-slot="row">
            <dt>Two-factor</dt>
            <dd>On</dd>
          </div>
        </dl>
        <div data-slot="stack">
          <ui-drawer>
            <ui-drawer-trigger><button>Change Password</button></ui-drawer-trigger>
            <ui-drawer-backdrop hidden></ui-drawer-backdrop>
            <ui-drawer-content hidden>
              <div data-slot="grip" aria-hidden="true"></div>
              <div data-slot="stack">
                <ui-drawer-title>Change password</ui-drawer-title>
                <ui-drawer-description>Use at least 12 characters.</ui-drawer-description>
              </div>
              <ui-field>
                <ui-field-label>New password</ui-field-label>
                <ui-input>
                  <input type="password" />
                </ui-input>
              </ui-field>
              <div data-slot="stack">
                <ui-drawer-close><button data-variant="solid">Update</button></ui-drawer-close>
              </div>
            </ui-drawer-content>
          </ui-drawer>
          <ui-drawer-close><button data-variant="solid">Done</button></ui-drawer-close>
        </div>
      </ui-drawer-content>
    </ui-drawer>
  `
}

export { mount }
打开 Account,然后打开 Change Password。父级会随着子级打开而后退;Escape 一次关闭一张面板。

表单

带 action attribute 的 Close 部件会触发 action 事件;把 Promise 传给 event.detail.waitUntil()。它运行期间面板保持打开,包括经过 Escape 或滑动。被拒绝时,动作的错误状态会保留下来,供重试。共用的待处理与错误约定见 Alert Dialog 的异步动作。

keep-mounted 保留尚未完成的字段,final-focus 把焦点还给更新后的个人资料。

<ui-drawer-content keep-mounted final-focus="#profile-summary" hidden>
  <form><!-- fields --></form>
  <ui-drawer-close action><button>Save Changes</button></ui-drawer-close>
</ui-drawer-content>

<script type="module">
  const close = document.querySelector("ui-drawer-close[action]")
  const button = close.querySelector("button")
  close.addEventListener("action", (event) => {
    button.textContent = "Saving…"
    const saving = save()
    event.detail.waitUntil(saving)
    saving.then(
      () => (button.textContent = "Save Changes"),
      () => (button.textContent = "Try Again")
    )
  })
</script>

Outlet

Outlet 让另一个元素跟随面板的进度。它的 keyframes property 从收起运行到完全展开;这个示例让 Compose 面板后面的收件箱缩放并变圆。抽屉之外的 Outlet 用 for="drawer-id" 连接。

import "@ui-sdk/web/drawer"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import "@ui-sdk/web/textarea"

const messages = [
  { from: "Inès", text: "The proofs are back from the printer." },
  { from: "Kofi", text: "Lunch on Thursday?" },
  { from: "Wren", text: "Pushed the fix for the release build." },
  { from: "Tomasz", text: "Can you review the launch checklist?" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-drawer>
      <div>
        <ui-drawer-outlet>
          <div data-slot="row">
            <span>Inbox</span>
            <ui-drawer-trigger><button data-variant="solid">Compose</button></ui-drawer-trigger>
          </div>
          <ul data-slot="list">
            ${messages
              .map(
                (message) => `<li>
                  <div>${message.from}</div>
                  <div data-slot="hint">${message.text}</div>
                </li>`
              )
              .join("")}
          </ul>
        </ui-drawer-outlet>
      </div>
      <ui-drawer-backdrop hidden></ui-drawer-backdrop>
      <ui-drawer-content hidden>
        <div data-slot="grip" aria-hidden="true"></div>
        <div data-slot="stack">
          <ui-drawer-title>New message</ui-drawer-title>
          <ui-drawer-description>Write a quick note to the team.</ui-drawer-description>
        </div>
        <ui-field>
          <ui-field-label>To</ui-field-label>
          <ui-input>
            <input value="Design team" />
          </ui-input>
        </ui-field>
        <ui-field>
          <ui-field-label>Message</ui-field-label>
          <ui-textarea>
            <textarea placeholder="What's new?"></textarea>
          </ui-textarea>
        </ui-field>
        <div data-slot="stack">
          <ui-drawer-close value="send"><button data-variant="solid">Send</button></ui-drawer-close>
        </div>
      </ui-drawer-content>
    </ui-drawer>
  `
  root.querySelector("ui-drawer-outlet")!.keyframes = {
    scale: [1, 0.94],
    borderRadius: ["0px", "24px"],
  }
}

export { mount }
打开 Compose,然后慢慢拖动面板。后面的收件箱会随着面板的进度缩放并变圆。

从任意位置打开

给抽屉一个 id,用 for 连接外部触发器,并给每个触发器的 payload property 赋值。抽屉的 payloadchange 事件把它放在 event.detail.value 里。这让同一张面板可以服务每一行,包括为不可用操作准备的禁用触发器。

在抽屉的 api 上调用 open({ payload }) 会返回一个 Promise,带着关闭的 reason 和 returnValue。getSnapPoint() 和 setSnapPoint() 也让代码可以读取或移动面板。控制器指南涵盖共用的结果与 payload 流程。

<ui-drawer-trigger for="share" disabled
  ><button>Share</button></ui-drawer-trigger
>

<ui-drawer id="share">
  <ui-drawer-backdrop hidden></ui-drawer-backdrop>
  <ui-drawer-content hidden>
    <ui-drawer-title></ui-drawer-title>
  </ui-drawer-content>
</ui-drawer>

<script type="module">
  const drawer = document.querySelector("#share")
  document.querySelector("ui-drawer-trigger").payload = file
  drawer.addEventListener("payloadchange", (event) => {
    drawer.querySelector("ui-drawer-title").textContent =
      `Share ${event.detail.value?.name}`
  })

  const { reason, returnValue } = await drawer.api.open({ payload: roadmap })
</script>

操作表

面板可以提供选项而不是表单。给每个 Close 部件一个 value;打开的 Promise 返回选中的动作。Escape、外部按压或滑动不返回值,这个示例把它当作 Cancel。

把风险最低的动作放在最前面,因为键盘或代码打开时会从那里开始。需要确认的选择,改用 Alert Dialog。

控制台
import "@ui-sdk/web/drawer"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="row">
      <button type="button">Photo Options</button>
      <ui-drawer>
        <ui-drawer-backdrop hidden></ui-drawer-backdrop>
        <ui-drawer-content hidden>
          <div data-slot="stack">
            <ui-drawer-title>Beach.jpg</ui-drawer-title>
            <ui-drawer-description>Taken today at 9:41.</ui-drawer-description>
          </div>
          <div data-slot="stack">
            <ui-drawer-close value="share"><button>Share</button></ui-drawer-close>
            <ui-drawer-close value="duplicate"><button>Duplicate</button></ui-drawer-close>
            <ui-drawer-close value="delete"><button>Delete</button></ui-drawer-close>
            <ui-drawer-close value="cancel"><button>Cancel</button></ui-drawer-close>
          </div>
        </ui-drawer-content>
      </ui-drawer>
    </div>
  `
  const drawer = root.querySelector("ui-drawer")!
  root.querySelector("button")!.addEventListener("click", async () => {
    const { returnValue = "cancel" } = await drawer.api.open()
    log(root, returnValue === "cancel" ? "Canceled" : `Chose ${returnValue}`)
  })
}

export { mount }
打开 Photo Options 并选择一个动作。控制台会记录返回的值;关闭面板算作 Cancel。

响应式

这个做法用媒体查询在窄屏上选择 drawer,在宽屏上选择 dialog。它会在断点处替换标记,所以打开的面板会关闭,字段编辑也会重置。如果打开状态和字段值必须在切换后保留,就把它们放在那段标记之外。

<div id="profile"></div>

<script type="module">
  import "@ui-sdk/web/dialog"
  import "@ui-sdk/web/drawer"

  const isDesktop = matchMedia("(min-width: 768px)")
  const render = () => {
    const name = isDesktop.matches ? "dialog" : "drawer"
    document.querySelector("#profile").innerHTML = `
      <ui-${name}>
        <ui-${name}-trigger><button>Edit Profile</button></ui-${name}-trigger>
        <ui-${name}-backdrop hidden></ui-${name}-backdrop>
        <ui-${name}-content hidden>${profileForm}</ui-${name}-content>
      </ui-${name}>
    `
  }
  isDesktop.addEventListener("change", render)
  render()
</script>

驱动方式与物理参数

driver 决定面板如何移动。"scroll-snap" 为底部面板使用原生滚动和 CSS 吸附点;"pointer" 在每条边上使用指针拖动和弹簧运动。默认的 "auto" 在触摸屏上为底部面板选择原生滚动,而鼠标和触控笔、其他边缘、modal-above 或 expand-on-scroll="false" 时选择指针拖动。data-driver 报告当前的选择。

用 physics property 覆盖 sheetPhysics.ios 的一部分,来调整指针驱动:response 改变弹簧的时间,dampingRatio 改变停稳过程,momentumDampingRatio 影响甩动,rubberBand 改变越过最大吸附点时的阻力。

<ui-drawer driver="pointer"></ui-drawer>

<script type="module">
  document.querySelector("ui-drawer").physics = {
    response: 0.3,
    dampingRatio: 0.9,
  }
</script>

页面集成

theme-color 会随着遮罩把已有的 <meta name="theme-color"> 调暗,让浏览器的工具栏可以跟着变化;没有这个标签的页面不受影响。persistent-elements 在抽屉处于模态时让选中的元素保持可用:一个逗号分隔的选择器列表,或者给 persistentElements property 赋一个元素数组或返回元素的函数。必须留在遮罩之上的内容,也需要自己的顶层表面。

抽屉就地渲染,并使用顶层(top layer)。container 接收一个选择器,把遮罩和视口移到那里,比如移进影子根(shadow root),或者移出外围的表单。见共享的浮层指南。

<ui-drawer
  theme-color
  persistent-elements="#chat-launcher"
  container="#drawer-host"
></ui-drawer>

自定义渲染

元素没有 render 函数。Trigger、Close 和 Handle 部件包装你的原生 button 或链接,标题上的 as-child 绑定你自己的标题。当标记里没有全屏视口时,内容会在自身周围添加一个 ui-drawer-viewport。监听抽屉的 openchange 事件和内容的数据属性,比如 data-expanded,来改变里面的内容。

<ui-drawer>
  <ui-drawer-trigger shortcut="mod+j"
    ><button>View Details</button></ui-drawer-trigger
  >
  <ui-drawer-content hidden>
    <ui-drawer-title as-child><h3>Quarterly report</h3></ui-drawer-title>
    <ui-drawer-description>Drag up to see more.</ui-drawer-description>
    <ui-drawer-close
      ><a href="/reports/q3">Open the Full Page</a></ui-drawer-close
    >
  </ui-drawer-content>
</ui-drawer>

<script type="module">
  const drawer = document.querySelector("ui-drawer")
  const content = drawer.querySelector("ui-drawer-content")
  drawer.addEventListener("openchange", (event) => {
    drawer.querySelector("ui-drawer-trigger button").textContent = event.detail
      .value
      ? "Viewing"
      : "View Details"
  })
  new MutationObserver(() => {
    content.querySelector("ui-drawer-description").textContent =
      content.hasAttribute("data-expanded")
        ? "Showing all of it."
        : "Drag up to see more."
  }).observe(content, { attributeFilter: ["data-expanded"] })
</script>

样式

每个元素都有一个 data-slot,比如 drawer-content,并通过数据属性下列出的属性展示状态。

把内容的 translate 和遮罩的不透明度留给抽屉。你可以设置缩放、圆角、颜色和内部滚动区域的样式。底部面板可以在边缘下方用一个 after 元素,在过度滚动时盖住空隙,示例就是这样做的。抽屉尊重减少动态效果设置,改为淡入淡出而不是滑动。

<ui-drawer-content>

变量内容
--drawer-progressHow far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
--drawer-dimHow dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
--drawer-expand0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.
--drawer-stackHow many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it.

<ui-drawer-viewport>

变量内容
--keyboard-insetHow many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthThe width of the part of the page you can see.
--visual-viewport-heightThe height of the part of the page you can see, above the keyboard.
--visual-viewport-topHow far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

<ui-drawer-outlet>

变量内容
--drawer-progressHow far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
--drawer-dimHow dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
--drawer-expand0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.

数据属性

<ui-drawer-trigger>

[data-slot="drawer-trigger"]

属性含义
data-closedPresent while the drawer is closed, including while it animates out.
data-disabledPresent when the trigger is disabled.
data-openPresent while the drawer is open. On a trigger, while it's open from that trigger.

<ui-drawer-backdrop>

[data-slot="drawer-backdrop"]

属性含义
data-closedPresent while the drawer is closed, including while it animates out.
data-openPresent while the drawer is open. On a trigger, while it's open from that trigger.
data-interactivePresent while it rests at or below modalAbove, so the page behind is usable. The backdrop lets presses through.
data-starting-stylePresent for the first frame. The drawer slides itself, so leave the content's translate and the backdrop's opacity alone.
data-ending-stylePresent while the drawer animates out.
data-draggingPresent while a finger, mouse or pen drags it.

<ui-drawer-viewport>

[data-slot="drawer-viewport"]

属性含义
data-sidetoprightbottomleftThe edge it comes from, with start and end resolved for the writing direction.
data-closedPresent while the drawer is closed, including while it animates out.
data-openPresent while the drawer is open. On a trigger, while it's open from that trigger.
data-keyboardPresent on the viewport while the on-screen keyboard covers part of the page.

<ui-drawer-content>

[data-slot="drawer-content"]

属性含义
data-closedPresent while the drawer is closed, including while it animates out.
data-sidetoprightbottomleftThe edge it comes from, with start and end resolved for the writing direction.
data-openPresent while the drawer is open. On a trigger, while it's open from that trigger.
data-snap-pointcontent0.2The snap point it rests on or is moving to, as written, like 0.5 or content.
data-interactivePresent while it rests at or below modalAbove, so the page behind is usable. The backdrop lets presses through.
data-starting-stylePresent for the first frame. The drawer slides itself, so leave the content's translate and the backdrop's opacity alone.
data-ending-stylePresent while the drawer animates out.
data-driverpointerscroll-snapWhat moves it.
data-expandedPresent while it rests at its largest snap point.
data-draggingPresent while a finger, mouse or pen drags it.

<ui-drawer-handle>

[data-slot="drawer-handle"]

属性含义
data-snap-pointcontent0.2The snap point it rests on or is moving to, as written, like 0.5 or content.
data-expandedPresent while it rests at its largest snap point.

<ui-drawer-close>

[data-slot="drawer-close"]

属性含义
data-disabled
data-pendingPresent on a Close part while its action runs.

<ui-drawer-outlet>

[data-slot="drawer-outlet"]

属性含义
data-closedPresent while the drawer is closed, including while it animates out.
data-openPresent while the drawer is open. On a trigger, while it's open from that trigger.

API 参考

Props 是写成 kebab-case 的属性,比如 modal-above:"false" 表示 false。snap-points 接收逗号分隔的列表,比如 "0.5,1" 或 "240px,content"。container 接收一个 CSS 选择器,persistent-elements 接收逗号分隔的选择器列表。physics 和 controller 是 property。回调是 DOM 事件。

Drawer

debug?boolean
Logs every state change with its reason to the console, in development builds.
container?DocumentFragment | Element | null
Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
open?boolean
Whether the dialog is open. Pass it to control the dialog.
defaultOpen?boolean
Whether the dialog starts open, when uncontrolled. Focus moves into it once it's on the page.
openchangecomplete event
Runs once the dialog has finished opening or closing, after any animation.
dismissible?boolean
Whether Escape, an outside press and Android's back gesture can close the dialog. Close parts, triggers and the controller always can. Pass false while a form has unsaved changes, and ask in dismissattempt.
persistentElements?(string | Element)[] | (() => Element[])
Elements that stay usable while the dialog makes the page inert, like a chat launcher or a password manager's button. Elements, CSS selectors, or a function that returns elements, read when the dialog opens. Presses on them never close it.
pendingAnnouncement?string
What screen readers hear once a Close part's action has been running for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
openchange event
Runs when the drawer wants to open or close. details.reason says why, "swipe" included, details.cancel() stops it, and details.returnValue carries what closed it.
payloadchange event
Runs when the payload the content shows changes: a trigger with another payload opens the drawer, or takes a non-modal drawer over while it's open, which fires no openchange, and so does a controller's open({ payload }) on the open drawer. details.cancel() keeps the previous payload.
dismissattempt event
Runs when a dismissal was refused because dismissible is false, including a swipe. The drawer resists and springs back. Ask "Discard changes?" here.
modal?"trap-focus" | boolean
true: the rest of the page is inert and doesn't scroll, focus is trapped, and an outside press only closes the drawer. "trap-focus": traps focus and leaves the page usable. false: a drawer beside the page. See modalAbove to make it modal only above a snap point.
closeOnOutsidePress?boolean
Whether pressing outside the drawer, like on its backdrop, closes it.
controller?DrawerController<any, any>
Opens, closes and moves the drawer from anywhere, and connects triggers and outlets outside it. Create one with createDrawerController().
snapPoints?SnapPoint[]
Where the drawer can rest, from the edge it comes from: a fraction of the screen up to 1, pixels above 1, "…px", "…rem", "…%", or "content" for its own size. None can be larger than the drawer, which you size with CSS.
snapPoint?SnapPoint | null
The snap point it rests on. Pass it to control it.
defaultSnapPoint?SnapPoint
The snap point it opens at, when uncontrolled. It opens there again each time.
snappointchange event
Runs when the drawer moves to another snap point. details.reason says why: a swipe, the handle, the keyboard, a resize or the controller.
side?Side
The edge it comes from. "start" and "end" follow the writing direction.
modalAbove?SnapPoint
At or below this snap point the page stays usable and undimmed, like Maps: no inert page, no scroll lock, no aria-modal, and presses beside the drawer reach the page. Above it, modal applies. Changes once the drawer comes to rest.
driver?SheetDriverName
How it moves. "pointer" follows touch, mouse and pen with a spring fitted to iOS. "scroll-snap" uses the browser's own scrolling for bottom drawers. "auto" picks scroll snap for a bottom drawer on a touch screen, unless modalAbove is set or expandOnScroll is false, and the pointer driver otherwise.
expandOnScroll?boolean
Whether dragging toward a larger snap point on scrollable content moves the drawer first, until it's at its largest.
physics?Partial<SheetPhysics>
Overrides the motion: spring, projection, rubber band and dim. Starts from sheetPhysics.ios.
themeColor?boolean
Whether <meta name="theme-color"> dims with the backdrop, so Safari's toolbars darken too. Written where motion starts and ends, never per frame.
preventEdgeSwipe?boolean
Whether presses on the drawer near the screen's left and right edges are kept from starting iOS Safari's back and forward swipe. Taps right at those edges then don't click. Read when the content mounts.

DrawerTrigger

抽屉之外的触发器用 for="drawer-id" 指向它,并接收 payload property,或者把字符串作为 payload attribute。property 优先。

disabled?boolean
Stops the trigger from opening the dialog. A native button can't be focused or pressed, unless focusableWhenDisabled is set.
focusableWhenDisabled?boolean
Keeps a disabled trigger in the tab order with aria-disabled instead of the native attribute, so it can host a tooltip that says why. Presses still do nothing.
payload?unknown
Data for the content to render when this trigger opens the dialog, like the row it belongs to.
shortcut?string
A keyboard shortcut that presses the trigger, like "mod+k". mod is Command on Apple platforms and Control elsewhere. Sets aria-keyshortcuts, and a Shortcut part inside shows it. A modal dialog pauses the page's shortcuts while it's open.
controller?PopupController<any, DialogOpenChangeReason, {}, any, DialogPayloadChangeReason>
Connects a trigger outside the dialog, like one per table row, to the dialog with this controller.

DrawerBackdrop

让模态抽屉后面的页面变暗,不透明度由抽屉管理。<ui-drawer-backdrop> 没有自己的属性。

DrawerContent

container?DocumentFragment | Element | null
Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
initialFocus?DialogInitialFocus
Where focus goes when the dialog opens. Opening with touch focuses the dialog itself, so no on-screen keyboard appears, unless this is set to something other than "auto".
finalFocus?PopupFocusTarget
Where focus goes when the dialog closes while focus is inside it.
keepMounted?boolean
Whether the dialog stays in the page, hidden, while closed. Its content keeps its state between opens.

DrawerHandle

调整面板大小:按压会移到下一个吸附点,方向键、Home 和 End 选择一个吸附点。<ui-drawer-handle> 包装你的原生 button。

DrawerTitle

为抽屉命名。<ui-drawer-title> 渲染一个二级标题。

DrawerDescription

在渲染期间描述抽屉。<ui-drawer-description> 是一个段落。

DrawerClose

value?string
Reported as returnValue in openchange and by the controller's open(). createConfirm() resolves true for "confirm".
action?((event: Event | undefined, details: ActionDetails) => unknown)
Runs when the part is pressed, before the dialog closes. A returned Promise keeps the dialog open while it runs: the part gets data-pending, aria-busy and aria-disabled, screen readers hear the dialog's pendingAnnouncement after a second, and nothing but the controller closes the dialog. It closes with reason "action" once the Promise resolves. A rejection keeps it open and puts the reason in the part's error state until the next press, or until the dialog opens again. details.source says how the part was pressed, for changes made after an await.

DrawerShortcut

shortcut?string
The keys to show. Inside a trigger, its shortcut.

DrawerOutlet

抽屉之外的 Outlet 用 for="drawer-id" 指向它。

keyframes?SheetKeyframes
Keyframes it plays as the drawer expands, like { scale: [1, 0.94] }: the first while collapsed, the last at the largest snap point. They run on the compositor when they're transforms or opacity.
controller?DrawerController<any, any>
Connects an outlet outside the drawer, like the app's shell, to the drawer with this controller.

状态

同样的状态以数据属性出现在每个元素上。

DrawerTrigger:

openboolean
Whether the dialog is open from this trigger.
disabledboolean
Set by the trigger's disabled prop, which stops it opening the dialog.

DrawerBackdrop:

openboolean
Whether the dialog is open. False while it animates out.
nestedboolean
Whether the dialog was opened from inside another dialog.
nestedOpenboolean
Whether a dialog opened from inside this one is open.
interactiveboolean
Whether the page behind is usable, so the backdrop lets presses through.

DrawerContent:

openboolean
Whether the dialog is open. False while it animates out.
modalboolean | "trap-focus"
The modal setting. Always true for an alert dialog.
nestedboolean
Whether the dialog was opened from inside another dialog.
nestedOpenboolean
Whether a dialog opened from inside this one is open.
stacknumber
How many dialogs are open above this one, nested inside it.
payloadPayload | undefined
The payload of the last open, from the trigger that opened it or a controller, typed as the controller's Payload.
pendingboolean
Whether a Close part's action is running.
snapPointSnapPoint | null
The snap point it rests on or is moving to.
expandedboolean
Whether it's at its largest snap point.
draggingboolean
Whether a finger, mouse or pen is dragging it.
sidePhysicalSide
The edge it comes from, with start and end resolved.
interactiveboolean
Whether the page behind is usable, because it rests at or below modalAbove.

DrawerHandle:

snapPointSnapPoint | null
The snap point it rests on.
canExpandboolean
Whether there's a larger snap point to move to.
canCollapseboolean
Whether there's a smaller snap point to move to.

DrawerClose:

pendingboolean
Whether this part's action is running.
errorunknown
Why this part's last action failed, until it's pressed again or the dialog opens again.

DrawerOutlet:

openboolean
Whether the drawer is open. False as soon as it starts closing, while it still animates out.

原因

event.detail.reason 说明抽屉为什么打开或关闭。

trigger-pressMouseEvent | KeyboardEvent | TouchEvent
Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its touchend.
close-pressMouseEvent | KeyboardEvent | SubmitEvent
A Close part was pressed, or a form with method="dialog" was submitted.
outside-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
parent-closenone
The parent layer closed.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
actionMouseEvent | KeyboardEvent
A Close part's action finished.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.
imperativenone
A controller or api call.

对于 payload 变更,它说明是什么打开了抽屉或接管了它。

trigger-pressMouseEvent | KeyboardEvent | TouchEvent
Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its touchend.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
imperativenone
A controller or api call.

它为什么移动到另一个吸附点:

backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.
imperativenone
A controller or api call.
handle-pressMouseEvent | KeyboardEvent
A drawer's handle was pressed, which moved it to its next snap point.
handle-keyKeyboardEvent
Arrow keys, Home or End on a drawer's handle moved it between snap points.
content-resizenone
The content or the screen changed size, and the drawer's snap point or the carousel's page went away, so it moved to the nearest one.

dismissible 可以拒绝的关闭操作:

outside-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.

控制器

用 @ui-sdk/web/drawer 里的 createDrawerController<Payload, Result>() 创建一个,并赋给根元素的 controller property。根元素的 api property 有相同的方法,它的 open 和 snapPoint property 读写是否打开以及停在哪里。

每个写方法都接受可选的 { reason, event },事件会带上它。用控制器关闭总是有效,即使抽屉不可关闭,或者有动作正在运行。

isOpen()() => boolean
Whether it's open. False as soon as it starts closing, while it still animates out.
setOpen(open, options?)(open: boolean, options?: PopupChangeOptions<DrawerOpenChangeReason> | undefined) => boolean
Opens or closes it. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (PopupChangeOptions<DialogPayloadChangeReason> & { payload?: Payload | undefined; anchor?: Anchor | undefined; signal?: AbortSignal | undefined; }) | undefined) => Promise<...>
Opens it, and resolves once it closes, with why, how and any return value. Resolves exactly once and never rejects: on the next close from any source, when signal aborts, or with reason "unmount" when the component leaves the page.
close(options?)(options?: (PopupChangeOptions<DrawerOpenChangeReason> & { returnValue?: Result | undefined; }) | undefined) => boolean
Closes it. returnValue is passed to the promise open() returned. Returns false when the close was canceled or it was already closed.
toggle(options?)(options?: PopupChangeOptions<DrawerOpenChangeReason> | undefined) => boolean
Opens it when it's closed, and closes it when it's open. Returns false when the change was canceled.
getPayload()() => Payload | undefined
The payload of the last open, from a controller or the trigger that opened it.
focus()() => void
Moves focus to the trigger that opened it last, or the first trigger.
getSnapPoint()() => SnapPoint | null
The snap point it rests on, or null before it first opens.
setSnapPoint(snapPoint, options?)(snapPoint: SnapPoint, options?: ChangeOptions<DrawerSnapPointChangeReason> | undefined) => boolean
Moves it to a snap point. While closed, it opens there next. Returns false when the change was canceled or it was already there.

事件

事件在各自的元素上触发,不冒泡。在 openchange 或 snappointchange 上调用 preventDefault() 会取消这次变更。

成员所属说明
open property, attributeui-drawer抽屉是否打开。attribute 设置起始值,并且是实时的
snapPoint property, attributeui-drawer它停靠的吸附点。snap-point attribute 设置起始值
api propertyui-drawer这个控制器
controller propertyui-drawer来自 createDrawerController() 的控制器,用来从代码驱动它
physics propertyui-drawersheetPhysics.ios 的覆盖值
openchange eventui-drawerdetail: { value: open, reason, event, returnValue }
openchangecomplete eventui-drawerdetail: { value: open },在停稳之后
payloadchange eventui-drawerdetail: { value: payload, reason, event, source },当内容的 payload 变化时
snappointchange eventui-drawerdetail: { value: snapPoint, reason, event }
dismissattempt eventui-drawerdetail: { reason, event },当一次关闭被拒绝时
payload propertyui-drawer-trigger内容的数据,在触发器连接时读取
for attributeui-drawer-trigger触发器从抽屉之外打开的那个抽屉的 id
for attributeui-drawer-outletOutlet 从抽屉之外跟随的那个抽屉的 id
keyframes propertyui-drawer-outlet抽屉展开时播放的关键帧

无障碍

触发器是一个打开对话框的按钮,抽屉在模态时遵循 WAI-ARIA 模态对话框模式:带有 aria-modal,焦点困在内部,页面不可交互,由标题提供名称,由描述说明。Escape 会关闭它。手柄是一个控制抽屉的按钮:按压会移到下一个吸附点,沿抽屉轴线的方向键逐步移动,Home 和 End 移到两端。下面每一行都是一个自动化测试。

键盘

按键作用
Enter, Space在触发器上打开抽屉;在手柄上移到下一个吸附点
Arrow keys along the axis在手柄上移动一个吸附点,不回绕
Home, End在手柄上移到最小或最大的吸附点
Tab, Shift+Tab在面板的控件之间移动,模态时保持在内部
Escape在可关闭时关闭最上层的抽屉

它共享 Dialog 的焦点行为:打开时焦点移入,关闭时返回。触摸打开会把焦点放在内容上,这样字段不会立刻唤出键盘,除非你设置了 initial-focus。屏幕键盘打开时,视口会缩小,聚焦的字段可以在面板内部滚动到可见区域。

经过测试的行为

Dialog
  • The trigger advertises a dialog.
  • The trigger opens a modal dialog named by its title and described by its description.
  • Opening moves focus into the drawer and closing returns it to the trigger.
  • Tab stays inside the drawer.
  • Escape closes it with the escape-key reason.
  • Pressing the backdrop closes it.
  • A Close part closes it.
  • Buttons inside it work without closing it.
  • The page behind is hidden from assistive technology while it's open.
  • Opening and closing never scroll or restyle the page.
  • A controller opens it from outside.
Sheet
  • It rises from the bottom and rests against it at its own size.
  • It opens at the first snap point, a fraction of the screen.
  • A slow drag settles on the nearest snap point and reports the swipe.
  • A drag down past the smallest snap point closes it with the swipe reason.
  • A short fast flick down closes it, though it moved less than half its height.
  • The same distance, slowly, settles back.
  • A fling up from the smallest snap point can pass the middle one.
  • A press while it rises catches it and holds it under the finger.
  • A short drag back up keeps it open.
  • A click on a button inside it isn't a drag.
  • With side="…" it rests against the … edge.
  • With side="left" a drag toward the left closes it.
Touch
  • A touch drag down closes it.
Handle
  • Pressing it moves to the next snap point and wraps.
  • Arrow keys step without wrapping, and Home and End go to the ends.
  • Moving it moves the drawer to the snap point's extent.
  • A snap point a controller sets while it animates closed is where it opens next.
  • A controller moves it with the imperative reason.
Not dismissible
  • Escape reports an attempt and keeps it open.
  • A press on the backdrop reports an attempt and keeps it open.
  • A swipe down resists, springs back and reports an attempt.
Modal above a snap point
  • At that snap point the page stays usable and the drawer isn't modal.
  • Above it the drawer becomes modal, and back down the page is usable again.
  • The switch doesn't move focus.
Nested
  • Escape closes only the drawer on top.

运行于 React、Vue 和 web components。

抽屉在这些屏幕阅读器和布局上经过测试:

  • No axe violations while closed.
  • No axe violations while open.
  • No axe violations while a nested drawer is open.
  • No axe violations while it rests where the page stays usable.
  • The drawer's accessibility tree is a dialog with its handle, title and actions.
  • The handle is a button that controls the drawer.

运行于 React、Vue 和 web components。

  • Side="start" comes from the right in a right-to-left layout.
  • Side="end" comes from the left in a right-to-left layout.
  • Side="…" stays on the … in a right-to-left layout.
  • A drag toward the start edge closes it in a right-to-left layout.
  • Side="top" stays at the top in a right-to-left layout.

运行于 React、Vue 和 web components。

还测试了:

  • Without a touch screen `auto` picks the pointer driver.
Dialog
  • An open modal drawer is marked aria-modal.
  • A keyboard open focuses its first control, and Tab cycles through the controls in order.
  • A controller's open() resolves with how it closed.
  • Focus inside a popup open in its content leaves that popup's scrolling alone.
Shortcuts
  • A trigger connected through a controller shows its shortcut in a Shortcut part, and binds it.
State attributes
  • The content names its side, its snap point and whether it's at the largest.
  • A drawer resting at its own size reports the content snap point and is expanded.
  • Data-dragging is set while a drag moves it.
  • A drawer opened from inside another marks both, and the one beneath reads its depth from --drawer-stack.
Physics
  • Past the largest snap point it stretches less than 24px and springs back.
Touch
  • Pulling down on scrolled content scrolls it to the top, then moves the drawer in the same gesture.
  • Pushing up on content below the largest snap point grows the drawer before the content scrolls.
Compositor
  • A settle runs as a spring sampled into linear(), on translate and the backdrop's opacity.
  • While a finger drives it, the drawer writes no attributes, only styles.
  • Its variables are registered and don't inherit, so moving it restyles only the drawer.
  • With reduced motion it fades in and out instead of sliding.
Page
  • An outlet outside the drawer follows it, and goes back when it closes.
  • The theme color dims while it's open and comes back when it closes.
  • Content that grows moves its content snap point, and the drawer follows.
  • Escape on a drawer that can't be dismissed nudges it toward closing.
Scroll-snap driver
  • On a touch screen it's the driver `auto` picks.
  • On a touch screen `auto` keeps the pointer driver with …=….
  • It opens at its first snap point with the browser's scrolling.
  • A swipe up snaps to the next snap point and reports the swipe.
  • A swipe up from the handle snaps to the next snap point.
  • It comes to rest when the scroll ends before the page hears the finger lift.
  • A swipe down closes it once it leaves the screen.
  • The handle moves it with a spring, like the pointer driver.

运行于 React、Vue 和 web components。