导航

v2.1.0
浮层

浮动面板

读者可以移动、调整大小、折叠到标题栏并关闭的浮动表面。

本页内容

浮动面板是一块浮动的表面,在工作区旁保持打开,同时其下方的页面仍可使用:画布的图层、颜色选择器、检查器、聊天。读者可以拖动其标题栏来移动它,从角落调整大小,把它折叠到只剩标题栏,或者关闭它。它是带有 role="dialog" 的 popover="manual",因此浏览器会从按钮打开它,并把它提升到顶层,位于页面上所有内容之上,无需维护 z-index 的顺序。其余工作由 panel 行为脚本完成:移动、调整大小、折叠、Escape、焦点,以及哪个面板位于最前面。

浮动面板

<button type="button" class="btn btn-sm" commandfor="layers" command="toggle-popover">  Layers</button><button type="button" class="btn btn-sm" commandfor="comments" command="toggle-popover">  Comments</button><div id="layers" popover="manual" role="dialog" class="panel" aria-labelledby="layers-title" style="--panel-x: 24px; --panel-y: 24px; --panel-width: 232px">  <div class="panel-header">    <button type="button" class="panel-handle" aria-label="Move the Layers panel with the arrow keys"></button>    <h2 class="panel-title" id="layers-title">Layers</h2>    <div class="panel-actions">      <button type="button" class="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed="false" aria-label="Minimize">        <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="M3 8L13 8" />        </svg>      </button>      <button type="button" class="btn btn-quiet btn-sm btn-square" commandfor="layers" command="hide-popover" 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>  </div>  <div class="panel-body">    <ol class="list">      <li class="list-row">        <span class="list-body"><span class="list-title">Header</span></span>      </li>      <li class="list-row">        <span class="list-body"><span class="list-title">Hero image</span></span>      </li>      <li class="list-row">        <span class="list-body"><span class="list-title">Pricing table</span></span>      </li>      <li class="list-row">        <span class="list-body"><span class="list-title">Footer</span></span>      </li>    </ol>  </div>  <span class="panel-resize" aria-hidden="true"></span></div><div id="comments" popover="manual" role="dialog" class="panel" aria-labelledby="comments-title" style="--panel-x: 296px; --panel-y: 64px; --panel-width: 272px">  <div class="panel-header">    <button type="button" class="panel-handle" aria-label="Move the Comments panel with the arrow keys"></button>    <h2 class="panel-title" id="comments-title">Comments</h2>    <div class="panel-actions">      <button type="button" class="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed="false" aria-label="Minimize">        <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="M3 8L13 8" />        </svg>      </button>      <button type="button" class="btn btn-quiet btn-sm btn-square" commandfor="comments" command="hide-popover" 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>  </div>  <div class="panel-body">    <div class="flex flex-col gap-sm">      <p class="m(0)">        <span class="fg-text-strong">Mira</span> The hero image crops the product on narrow screens.      </p>      <p class="m(0)">        <span class="fg-text-strong">Jun</span> Fixed in the next build: it keeps the middle third.      </p>      <input class="input input-sm" type="text" placeholder="Reply" aria-label="Reply">    </div>  </div>  <span class="panel-resize" aria-hidden="true"></span></div><script>document.getElementById('layers').showPopover()document.getElementById('comments').showPopover()</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
拖动标题栏,或拖动其底部末端的角落。在后方面板内按下可将其移到最前。用 Tab 移到标题栏后使用方向键,按住 Shift 移动更长距离,按住 Alt 调整大小;按 Escape 关闭面板。

#样式表绘制的内容

  • 面板表面。 与弹出层相同的浮起表面,带有浮起阴影。按住标题栏或角落时,它会升高到浮层阴影,拖动时不会选中文本。它的圆角是小按钮的圆角加上标题栏在按钮周围保留的 6px,即 14px。
  • 标题栏是同一表面上的一条横栏,下方有一条细线,标题位于起始端,操作按钮位于末端。两者之下是拖动手柄,一个与横栏同样大小的按钮,因此在标题栏上任何不是控件的位置按下都会拿起面板,光标先是张开的手,然后是握紧的手。标题不接收指针事件,因此在标题上按下会传到手柄。
  • 手柄获得焦点时,焦点环围绕整个面板,因为按键移动的是整个面板。
  • 折叠后,即按下最小化按钮时,面板只剩标题栏:主体和角落被隐藏,按钮呈凹陷状态。
  • 主体比可用空间长时会在面板内滚动,不会带动下方的页面。
  • 底部末端的角落由两条短斜线组成,其可操作区域为 16px,在触摸屏上扩大到 44px。触摸屏上的标题栏按钮外观尺寸保持不变,触控区域延伸到标题栏边缘。

#放置位置

位置和尺寸都是自定义属性:--panel-x 和 --panel-y 表示左上角的位置,以距视口左上角的像素计;另有 --panel-width 和 --panel-height。行为脚本根据指针和按键写入它们,因为只有事件才知道这些值;页面也可以写入它们,就像预览为每个面板设置初始位置那样。

样式表用 clamp() 完成定位和限制,参照的是固定定位元素计算百分比时所依据的视口,其中不包括滚动条:

  • 面板的宽度绝不会超过视口,也绝不会小于 --panel-min-width(12rem),并且整个宽度都保持在视口之内。
  • 它的标题栏绝不会离开视口,因此面板总能被找到并拖回来;它的高度绝不会超过视口,放不下的主体会滚动。
  • 窗口变窄时,面板会被推进视口。窗口变宽时,面板可以回到原先设定的位置,因为它保存的位置不会被 clamp 改变。
  • 未指定位置时,面板在末端顶部的角落打开,向内缩进 8px(--panel-gutter)。

每次移动和调整大小结束时,行为脚本都会读取样式表实际绘制面板的位置并保存下来,因此应用保存的值就是读者看到的位置。

#多个面板

面板按显示的先后顺序位于顶层:最后显示的位于最前面。在被其他面板遮住的面板内按下或聚焦时,会把它移到最前:行为脚本会再次显示它,使其排在顶层的最后。隐藏和显示在同一个任务中、在浏览器绘制之前完成,因此看不到面板离开,不会播放入场动画,浏览器也只报告一次从打开到打开的 toggle。焦点保持在读者放置的位置。

#行为脚本

panel 接收根元素,即带有 panel 类的元素,并返回用于解除绑定的函数。它的 value 表示面板的位置、大小以及是否折叠:{ x, y, width, height, minimized },四个数值以像素计,使用样式表默认值的项为 null。请保存这个值,并在页面加载时设置回去。

app.js
import { panel } from '@master/ui/behaviors/panel.js'const root = document.querySelector('#layers')const layers = panel(root)const saved = localStorage.getItem('layers-panel')if (saved) layers.value = JSON.parse(saved)root.addEventListener('change', (event) => {  if (event.target === root) localStorage.setItem('layers-panel', JSON.stringify(layers.value))})
  • 移动。 拖动手柄会写入 --panel-x 和 --panel-y;拿起面板时按住的那一点会保持在指针下方。在手柄上按方向键会移动 16px,按住 Shift 时移动四倍距离。
  • 调整大小。 拖动角落会写入 --panel-width 和 --panel-height;在手柄上按住 Alt 再按方向键也能做到,每次一个步长。在从右到左的书写方向中,角落位于左下方,因此面板向左变宽,Alt+ArrowLeft 会让它变宽。
  • 折叠。 点击最小化按钮会切换其 aria-pressed。
  • 关闭。 焦点在面板内时按 Escape 会关闭面板,除非该按键已被内部的控件处理,例如先关闭的菜单。关闭按钮无需脚本:它是 command="hide-popover"。
  • 焦点。 从控件打开的面板会把焦点移到其手柄上,在焦点位于面板内时关闭面板,焦点会还给该控件。页面加载时打开的面板不会移动焦点。
  • 事件。 面板移动或调整大小时,根元素派发 input;拖动结束、通过按键移动或折叠后派发 change。两者都会冒泡,因此主体中输入框派发的同名事件也会到达根元素:请将 event.target 与根元素进行比较。
选项设置的内容
step按一次方向键移动或调整面板大小的距离,以像素计。默认为 16

未加载行为脚本时,面板仍然可以从按钮在页面上方打开,位于顶层,也可以用关闭按钮关闭;它会停留在自定义属性指定的位置。

#从按钮打开

带有 commandfor 和 command="toggle-popover" 的按钮可以打开和关闭面板;popovertarget 的效果相同。面板在 Tab 键顺序中紧跟在其按钮之后,打开时焦点移到它的手柄上,因此可以立即用方向键移动它。用按钮、关闭按钮或 Escape 关闭面板后,焦点会回到按钮上。

从按钮打开

<button type="button" class="btn" commandfor="inspector" command="toggle-popover">Inspect</button><div id="inspector" popover="manual" role="dialog" class="panel" aria-labelledby="inspector-title" style="--panel-x: 24px; --panel-y: 24px; --panel-width: 264px">  <div class="panel-header">    <button type="button" class="panel-handle" aria-label="Move the Inspector panel with the arrow keys"></button>    <h2 class="panel-title" id="inspector-title">Inspector</h2>    <div class="panel-actions">      <button type="button" class="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed="false" aria-label="Minimize">        <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="M3 8L13 8" />        </svg>      </button>      <button type="button" class="btn btn-quiet btn-sm btn-square" commandfor="inspector" command="hide-popover" 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>  </div>  <div class="panel-body">    <dl class="data-list">      <div class="data-list-item">        <dt class="data-list-term">Element</dt>        <dd class="data-list-value">Hero image</dd>      </div>      <div class="data-list-item">        <dt class="data-list-term">Size</dt>        <dd class="data-list-value">1280 × 720</dd>      </div>      <div class="data-list-item">        <dt class="data-list-term">Format</dt>        <dd class="data-list-value">AVIF</dd>      </div>    </dl>  </div>  <span class="panel-resize" aria-hidden="true"></span></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import MinusIcon from '@master/icons-react/native/16/soft/minus'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: 'inspector', command: 'toggle-popover' }}>        Inspect      </button>      <div id="inspector" popover="manual" role="dialog" className="panel" aria-labelledby="inspector-title" style={{ '--panel-x': '24px', '--panel-y': '24px', '--panel-width': '264px' } as React.CSSProperties}>        <div className="panel-header">          <button type="button" className="panel-handle" aria-label="Move the Inspector panel with the arrow keys"></button>          <h2 className="panel-title" id="inspector-title">Inspector</h2>          <div className="panel-actions">            <button type="button" className="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed="false" aria-label="Minimize">              <MinusIcon className="icon" />            </button>            <button type="button" className="btn btn-quiet btn-sm btn-square" {...{ commandfor: 'inspector', command: 'hide-popover' }} aria-label="Close">              <XIcon className="icon" />            </button>          </div>        </div>        <div className="panel-body">          <dl className="data-list">            <div className="data-list-item">              <dt className="data-list-term">Element</dt>              <dd className="data-list-value">Hero image</dd>            </div>            <div className="data-list-item">              <dt className="data-list-term">Size</dt>              <dd className="data-list-value">1280 × 720</dd>            </div>            <div className="data-list-item">              <dt className="data-list-term">Format</dt>              <dd className="data-list-value">AVIF</dd>            </div>          </dl>        </div>        <span className="panel-resize" aria-hidden="true"></span>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import MinusIcon from '@master/icons-svelte/native/16/soft/minus'  import XIcon from '@master/icons-svelte/native/16/soft/x'</script><div {@attach attach}>  <button type="button" class="btn" commandfor="inspector" command="toggle-popover">Inspect</button>  <div id="inspector" popover="manual" role="dialog" class="panel" aria-labelledby="inspector-title" style="--panel-x: 24px; --panel-y: 24px; --panel-width: 264px">    <div class="panel-header">      <button type="button" class="panel-handle" aria-label="Move the Inspector panel with the arrow keys"></button>      <h2 class="panel-title" id="inspector-title">Inspector</h2>      <div class="panel-actions">        <button type="button" class="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed="false" aria-label="Minimize">          <MinusIcon class="icon" />        </button>        <button type="button" class="btn btn-quiet btn-sm btn-square" commandfor="inspector" command="hide-popover" aria-label="Close">          <XIcon class="icon" />        </button>      </div>    </div>    <div class="panel-body">      <dl class="data-list">        <div class="data-list-item">          <dt class="data-list-term">Element</dt>          <dd class="data-list-value">Hero image</dd>        </div>        <div class="data-list-item">          <dt class="data-list-term">Size</dt>          <dd class="data-list-value">1280 × 720</dd>        </div>        <div class="data-list-item">          <dt class="data-list-term">Format</dt>          <dd class="data-list-value">AVIF</dd>        </div>      </dl>    </div>    <span class="panel-resize" aria-hidden="true"></span>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import MinusIcon from '@master/icons-vue/native/16/soft/minus'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="inspector" command="toggle-popover">      Inspect    </button>    <div id="inspector" popover="manual" role="dialog" class="panel" aria-labelledby="inspector-title" style="--panel-x: 24px; --panel-y: 24px; --panel-width: 264px">      <div class="panel-header">        <button type="button" class="panel-handle" aria-label="Move the Inspector panel with the arrow keys"></button>        <h2 class="panel-title" id="inspector-title">Inspector</h2>        <div class="panel-actions">          <button type="button" class="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed="false" aria-label="Minimize">            <MinusIcon class="icon" />          </button>          <button type="button" class="btn btn-quiet btn-sm btn-square" commandfor="inspector" command="hide-popover" aria-label="Close">            <XIcon class="icon" />          </button>        </div>      </div>      <div class="panel-body">        <dl class="data-list">          <div class="data-list-item">            <dt class="data-list-term">Element</dt>            <dd class="data-list-value">Hero image</dd>          </div>          <div class="data-list-item">            <dt class="data-list-term">Size</dt>            <dd class="data-list-value">1280 × 720</dd>          </div>          <div class="data-list-item">            <dt class="data-list-term">Format</dt>            <dd class="data-list-value">AVIF</dd>          </div>        </dl>      </div>      <span class="panel-resize" aria-hidden="true"></span>    </div>  </div></template>
打开面板:焦点会移到它的标题栏。按 Escape 关闭后,焦点回到按钮。

#键盘操作

按键操作
Enter, Space在带有 commandfor 和 command="toggle-popover" 的按钮上:打开面板并将焦点移到其手柄;再按一次则关闭
ArrowLeft, ArrowRight, ArrowUp, ArrowDown在手柄上:将面板朝该方向移动一个步长(16px);到达视口边缘即停止
Shift+Arrow keys在手柄上:将面板移动四个步长
Alt+ArrowRight, Alt+ArrowLeft在手柄上:将面板加宽或变窄一个步长,按住 Shift 时为四个步长;从右到左时方向相反,此时调整大小的角落在左侧
Alt+ArrowDown, Alt+ArrowUp在手柄上:将面板加高或变矮一个步长,按住 Shift 时为四个步长;折叠的面板保持其高度
Enter, Space在最小化按钮上:将面板折叠至标题栏,或将其展开
Escape焦点在面板内时:关闭面板,并将焦点移回打开它的控件。面板内自行处理 Escape 的控件(例如打开的菜单)会保留该按键
Tab, Shift+Tab在手柄、操作按钮和主体之间移动焦点,并可继续移到页面:面板不是模态的

#无障碍

  • 面板是 role="dialog",通过 aria-labelledby 以其标题命名。它不是模态的:没有 aria-modal,页面仍可使用,按 Tab 可以离开面板。如果必须先完成任务,请使用对话框。
  • 手柄是原生按钮,会被辅助技术识别为按钮,也可通过键盘聚焦。名称应说明移动的对象和操作方式,例如“用方向键移动图层面板”。角落对辅助技术隐藏,因为可以在手柄上用按键调整大小。
  • 每一种拖动都有对应的按键:方向键移动,按住 Alt 再按方向键调整大小。对于使用指针但无法拖动的读者,也请提供单击即可完成的方式:在标题栏中放一个菜单,用其中的项(例如“停靠到左侧”)设置值即可。
  • 最小化按钮保持名称不变,用 aria-pressed 表明状态。
  • 在触摸屏上,标题栏保持原有高度。按钮的触控区域达到 44px,并延伸到标题栏边缘。用于调整大小的角落也有 44px 的触控区域。
  • 在强制颜色模式下,面板使用系统文字颜色绘制轮廓,手柄的焦点使用系统高亮色。

#React、Svelte 和 Vue

panel 组件渲染标题栏及其手柄和按钮,根据 open 打开和关闭面板,并接收和传出值:移动过程中调用 onValueChange,移动结束时调用 onValueCommit,这正是保存值的时机。触发按钮和主体仍是页面自己的标记。使用 npx master-ui add panel 将组件复制到项目中。有关这些组件的实现和用法,请参阅 React、Svelte 和 Vue。

ui/panel.tsx
'use client'import { useCallback, useEffect, useId, useReducer, useRef, useState, type ComponentProps, type CSSProperties, type ReactNode } from 'react'import { panel, type PanelValue } from '@master/ui/behaviors/panel.js'import { useBehavior } from './use-behavior'export type { PanelValue }export interface PanelProps extends Omit<ComponentProps<'div'>, 'title' | 'defaultValue' | 'popover' | 'role' | 'ref'> {  /** The title in the header, which names the panel. */  title: ReactNode  /** The name of the handle: what it moves and how, such as "Move the Layers panel with the arrow keys". */  handleLabel: string  /** Whether the panel is open, when this component is told. Leave it out and the trigger opens it. */  open?: boolean  onOpenChange?: (open: boolean) => void  /** Where the panel is, how large and whether it is folded. Keep it to put the panel back where it was. */  value?: PanelValue  defaultValue?: PanelValue  /** Called as the panel moves, resizes or folds. */  onValueChange?: (value: PanelValue) => void  /** Called once a drag ends, a key moved it or it was folded: the moment to keep the value. */  onValueCommit?: (value: PanelValue) => void  /** The button that opens the panel: spread what it is given on a button of your own. */  trigger?: (attributes: { commandfor: string, command: 'toggle-popover' }) => ReactNode  /** More controls in the header, before the minimize and close buttons. */  actions?: ReactNode  minimizeLabel?: string  closeLabel?: string  /** Leave out the corner that resizes it. */  resizable?: boolean  /** How far an arrow key moves or resizes the panel, in pixels. */  step?: number}const measures = ['x', 'y', 'width', 'height'] as const/** * A floating panel. The browser opens it from the trigger and puts it in the top layer; the behavior moves, * resizes, folds and stacks it. This component opens and closes it from `open`, and passes its place in and out. */export function Panel({ title, handleLabel, open, onOpenChange, value, defaultValue, onValueChange, onValueCommit, trigger, actions, minimizeLabel = 'Minimize', closeLabel = 'Close', resizable = true, step = 16, className, id, style, children, ...root }: PanelProps) {  const generated = useId()  const name = id ?? generated  const [first] = useState(value ?? defaultValue)  const latest = useRef(first)  const ref = useBehavior(panel, { step }, {    value,    defaultValue,    onValueChange: (next: PanelValue) => { latest.current = next; onValueChange?.(next) },    // The panel says change once a move ends. A field in its body says change too.    on: { change: (event) => { if (event.target === event.currentTarget) onValueCommit?.(latest.current!) } },  })  const element = useRef<HTMLDivElement | null>(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 popover = element.current    if (!popover || open === undefined) return    const shown = popover.matches(':popover-open')    known.current = open    if (open && !shown) popover.showPopover()    else if (!open && shown) popover.hidePopover()  }, [open, tick])  useEffect(() => {    const popover = element.current    if (!popover) return    const report = () => {      const shown = popover.matches(':popover-open')      if (shown !== known.current) heard.current?.(known.current = shown)      // An `open` this component is told wins: if its owner did not take the change, the panel goes back.      again()    }    popover.addEventListener('toggle', report)    return () => popover.removeEventListener('toggle', report)  }, [])  // The first place and size are drawn into the first render; after that the behavior writes them.  const place = Object.fromEntries(measures.filter(measure => typeof first?.[measure] === 'number').map(measure => [`--panel-${measure}`, `${first![measure]}px`]))  const attach = useCallback((node: HTMLDivElement | null) => {    element.current = node    return ref(node)  }, [ref])  return (    <>      {trigger?.({ commandfor: name, command: 'toggle-popover' })}      <div id={name} popover="manual" role="dialog" aria-labelledby={`${name}-title`} className={className ? `panel ${className}` : 'panel'} style={{ ...place, ...style } as CSSProperties} ref={attach} {...root}>        <div className="panel-header">          <button type="button" className="panel-handle" aria-label={handleLabel} />          <h2 className="panel-title" id={`${name}-title`}>{title}</h2>          <div className="panel-actions">            {actions}            <button type="button" className="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed={first?.minimized ?? false} aria-label={minimizeLabel}>              <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 8L13 8" /></svg>            </button>            <button type="button" className="btn btn-quiet btn-sm btn-square" {...{ commandfor: name, command: 'hide-popover' }} aria-label={closeLabel}>              <svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M4 4L12 12" /><path d="M4 12L12 4" /></svg>            </button>          </div>        </div>        <div className="panel-body">{children}</div>        {resizable && <span className="panel-resize" aria-hidden="true" />}      </div>    </>  )}
ui/Panel.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  import type { PanelValue } from '@master/ui/behaviors/panel.js'  export type { PanelValue }  export interface PanelProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title' | 'popover' | 'role'> {    /** The title in the header, which names the panel. */    title: string    /** The name of the handle: what it moves and how, such as "Move the Layers panel with the arrow keys". */    handleLabel: string    /** Whether the panel is open. Bind it, or leave it out and the trigger opens it. */    open?: boolean    onOpenChange?: (open: boolean) => void    /** Where the panel is, how large and whether it is folded. Bind it to put the panel back where it was. */    value?: PanelValue    /** Called as the panel moves, resizes or folds. */    onValueChange?: (value: PanelValue) => void    /** Called once a drag ends, a key moved it or it was folded: the moment to keep the value. */    onValueCommit?: (value: PanelValue) => void    /** The button that opens the panel: spread what it is given on a button of your own. */    trigger?: Snippet<[{ commandfor: string, command: 'toggle-popover' }]>    /** More controls in the header, before the minimize and close buttons. */    actions?: Snippet    minimizeLabel?: string    closeLabel?: string    /** Leave out the corner that resizes it. */    resizable?: boolean    /** How far an arrow key moves or resizes the panel, in pixels. */    step?: number  }</script><script lang="ts">  import { untrack } from 'svelte'  import type { Attachment } from 'svelte/attachments'  import { panel } from '@master/ui/behaviors/panel.js'  import { behavior } from './behavior.svelte.js'  let { title, handleLabel, open = $bindable(), onOpenChange, value = $bindable(), onValueChange, onValueCommit, trigger, actions, minimizeLabel = 'Minimize', closeLabel = 'Close', resizable = true, step = 16, class: className, id, children, ...root }: PanelProps = $props()  const generated = $props.id()  const name = $derived(id ?? generated)  const first = untrack(() => value)  // Svelte writes a style again whenever its owner changes it, so it writes the place the behavior holds.  let held = $state(first)  const px = (measure: number | null | undefined) => typeof measure === 'number' ? `${measure}px` : undefined  const attach = behavior(panel, () => ({ step }), {    value: () => value,    change: (next) => { value = held = next; onValueChange?.(next) },    settled: (kept) => { held = kept },    // The panel says change once a move ends. A field in its body says change too.    on: { change: (event) => { if (event.target === event.currentTarget && held) onValueCommit?.(held) } },  })  /** What the owner knows: the last state it set or was told. */  let known = false  const presence: Attachment<HTMLDivElement> = (popover) => {    const report = () => {      const shown = popover.matches(':popover-open')      if (shown === known) return      open = known = shown      onOpenChange?.(known)    }    popover.addEventListener('toggle', report)    $effect(() => {      if (open === undefined) return      const shown = popover.matches(':popover-open')      known = open      if (open && !shown) popover.showPopover()      else if (!open && shown) popover.hidePopover()    })    return () => popover.removeEventListener('toggle', report)  }</script><!--  @component  A floating panel. The browser opens it from the trigger and puts it in the top layer; the behavior moves,  resizes, folds and stacks it. This component opens and closes it from `open`, and passes its place in and out.-->{@render trigger?.({ commandfor: name, command: 'toggle-popover' })}<div id={name} popover="manual" role="dialog" aria-labelledby="{name}-title" class={['panel', className]} style:--panel-x={px(held?.x)} style:--panel-y={px(held?.y)} style:--panel-width={px(held?.width)} style:--panel-height={px(held?.height)} {@attach attach} {@attach presence} {...root}>  <div class="panel-header">    <button type="button" class="panel-handle" aria-label={handleLabel}></button>    <h2 class="panel-title" id="{name}-title">{title}</h2>    <div class="panel-actions">      {@render actions?.()}      <button type="button" class="btn btn-quiet btn-sm btn-square panel-minimize" aria-pressed={first?.minimized ?? false} aria-label={minimizeLabel}>        <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="M3 8L13 8" /></svg>      </button>      <button type="button" class="btn btn-quiet btn-sm btn-square" commandfor={name} command="hide-popover" aria-label={closeLabel}>        <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>  </div>  <div class="panel-body">{@render children?.()}</div>  {#if resizable}    <span class="panel-resize" aria-hidden="true"></span>  {/if}</div>
ui/Panel.vue
<script setup lang="ts">import { computed, nextTick, onMounted, useId, useTemplateRef, watch } from 'vue'import { panel, type PanelValue } from '@master/ui/behaviors/panel.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { id, title, handleLabel, minimizeLabel = 'Minimize', closeLabel = 'Close', resizable = true, step = 16 } = defineProps<{  id?: string  /** The title in the header, which names the panel. */  title: string  /** The name of the handle: what it moves and how, such as "Move the Layers panel with the arrow keys". */  handleLabel: string  minimizeLabel?: string  closeLabel?: string  /** Leave out the corner that resizes it. */  resizable?: boolean  /** How far an arrow key moves or resizes the panel, in pixels. */  step?: number}>()/** Where the panel is, how large and whether it is folded: `v-model`. Keep it to put the panel back where it was. */const model = defineModel<PanelValue>()/** Whether the panel is open: `v-model:open`. Leave it out and the trigger opens it. */const open = defineModel<boolean>('open')const emit = defineEmits<{  /** The value, once a drag ends, a key moved it or it was folded: the moment to keep it. */  valueCommit: [value: PanelValue]}>()defineSlots<{  /** The button that opens the panel: bind what it is given on a button of your own. */  trigger?: (attributes: { commandfor: string, command: 'toggle-popover' }) => unknown  /** More controls in the header, before the minimize and close buttons. */  actions?: () => unknown  default?: () => unknown}>()/* * A floating panel. The browser opens it from the trigger and puts it in the top layer; the behavior moves, * resizes, folds and stacks it. This component opens and closes it from `open`, and passes its place in and out. */const generated = useId()const name = computed(() => id ?? generated)const first = model.valueconst root = useTemplateRef<HTMLDivElement>('root')const current = useBehavior(root, panel, () => ({ step }), model, {  // The panel says change once a move ends. A field in its body says change too.  change: (event) => {    const held = current()    if (event.target === root.value && held) emit('valueCommit', held)  },})// Vue writes a style again each time it renders, so it writes the place the behavior holds, not the first one.const place = () => {  const held = current() ?? first  const px = (measure: number | null | undefined) => typeof measure === 'number' ? `${measure}px` : undefined  return { '--panel-x': px(held?.x), '--panel-y': px(held?.y), '--panel-width': px(held?.width), '--panel-height': px(held?.height) }}/** What the owner knows: the last state it set or was told. */let known = falseconst sync = () => {  const popover = root.value  if (!popover || open.value === undefined) return  const shown = popover.matches(':popover-open')  known = open.value  if (open.value && !shown) popover.showPopover()  else if (!open.value && shown) popover.hidePopover()}const report = () => {  const popover = root.value  if (!popover) return  const shown = popover.matches(':popover-open')  if (shown !== known) open.value = known = shown  // An `open` this component is told wins: if its owner did not take the change, the panel goes back.  void nextTick(sync)}onMounted(sync)watch(open, sync, { flush: 'post' })</script><template>  <slot name="trigger" v-bind="{ commandfor: name, command: 'toggle-popover' as const }" />  <div :id="name" popover="manual" role="dialog" :aria-labelledby="`${name}-title`" class="panel" :style="place()" ref="root" v-bind="$attrs" @toggle="report">    <div class="panel-header">      <button type="button" class="panel-handle" :aria-label="handleLabel" />      <h2 class="panel-title" :id="`${name}-title`">{{ title }}</h2>      <div class="panel-actions">        <slot name="actions" />        <button type="button" class="btn btn-quiet btn-sm btn-square panel-minimize" :aria-pressed="first?.minimized ?? false" :aria-label="minimizeLabel">          <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="M3 8L13 8" /></svg>        </button>        <button type="button" class="btn btn-quiet btn-sm btn-square" :commandfor="name" command="hide-popover" :aria-label="closeLabel">          <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>    </div>    <div class="panel-body"><slot /></div>    <span v-if="resizable" class="panel-resize" aria-hidden="true" />  </div></template>

#类名

类名说明
panel浮动面板本体:设置 popover="manual" 和 role="dialog",用 aria-labelledby 以标题命名。位置由 --panel-x 和 --panel-y 决定并保持在视口内,默认宽 20rem;未指定位置时位于顶部末端的角落
panel-header顶部栏:开头是标题,末尾是操作按钮,两者下方是手柄。这一部分始终不会离开视口
panel-handle与标题栏同大的按钮,位于标题栏最前,用于移动面板:在栏上任何非控件处拖动即可移动面板,按钮获得焦点时可用方向键移动。按其移动的对象和方式命名,例如“使用方向键移动图层面板”。聚焦时整个面板显示焦点环
panel-title标题,单行显示;将面板的 aria-labelledby 指向它。标题不接收指针,按下时会作用到手柄
panel-actions标题栏末端、叠在手柄上的控件:小号低调的方形按钮
panel-minimize将面板折叠至标题栏的按钮。按下时陷入凹槽,主体和角落隐藏
panel-body面板的内容,位于细线下方,四周留有 --panel-padding。主体过长时在面板内滚动。将内容放在主体内的元素中布局:面板折叠时会隐藏主体
panel-resize指针用来调整面板大小的角落,位于底部末端:点击区域为 16px,在触摸屏上为 44px。按键通过手柄调整大小,因此对辅助技术隐藏此元素

#自定义属性

属性默认值说明
--panel-x100%左边缘与视口左边缘的距离;由脚本以像素写入。保持整个宽度都在视口内,默认靠右边缘,从右到左时靠左边缘
--panel-y0px上边缘与视口上边缘的距离;由脚本以像素写入。保持标题栏在视口内
--panel-width20rem宽度;由脚本以像素写入。保持在 --panel-min-width 与视口宽度之间
--panel-heightauto高度,默认与内容等高;由脚本以像素写入。不超过视口高度
--panel-min-width12rem调整大小时的最小宽度
--panel-gutter.5rem面板与视口边缘之间保留的最小间距
--panel-padding1rem主体四周的内边距
--panel-radiuscalc(var(--radius-control-sm) + var(--panel-inset) / var(--corner-scale))圆角:小号按钮的圆角加上标题栏在其周围保留的 6px

#源码

@master/ui/components/panel.css
/* * Panel: a floating surface the reader moves, resizes, folds to its header and closes, while the page under it * stays usable: layers beside a canvas, a color picker, an inspector, a chat. It is a popover="manual" in the * top layer, so it floats over everything without a z-index; panels stack in the order they were shown, and the * behavior brings the one the reader reaches into to the front. * * Material: the floating sheet of a popover, with the floating shadow, and the overlay shadow while it is held, * so a panel being dragged rises a step. The header is a bar of the same sheet over a hairline; its whole face is * one button, the handle, so a press anywhere on the bar that is not a control picks the panel up, and focus on * the handle rings the panel the keys move. * * Geometry: the header holds small (32px) buttons 6px from its edges, so the panel's corner is a small control's * corner plus that inset, 14px. On touch a button's 44px target reaches those 6px, to the header's edge. The panel is 20rem wide unless told otherwise, never narrower than 12rem. * * Placement is the stylesheet's. A script writes what only an event knows, the place and the size asked for * (--panel-x, --panel-y, --panel-width, --panel-height); the stylesheet clamps them to the viewport, the box a * fixed element's percentages are read from, so a panel is never wider or taller than the window, the whole of * its width stays in it and its header can never leave it. The window narrowing pushes a panel in; widening it * again lets the panel go back to the place it was given. Without a place, a panel opens at the top end corner. */@layer components.ui {  .panel {    --panel-x: 100%;    --panel-y: 0px;    --panel-width: 20rem;    --panel-height: auto;    --panel-min-width: 12rem;    --panel-gutter: .5rem;    --panel-inset: .375rem;    /* The inset is added after the corner scale, so it is passed divided by it. */    --panel-radius: calc(var(--radius-control-sm) + var(--panel-inset) / var(--corner-scale));    --panel-padding: 1rem;    /* The header's height: a small button and the inset around it. The part of the panel that never leaves the viewport. */    --panel-bar: calc(2rem + 2 * var(--panel-inset));    /* The width it is drawn at: the width asked for, no less than the least, no more than the viewport gives. */    --panel-drawn-width: min(max(var(--panel-min-width), var(--panel-width)), 100% - 2 * var(--panel-gutter));    --surface-color: var(--color-surface-floating);    position: fixed;    inset: auto;    top: clamp(var(--panel-gutter), var(--panel-y), 100% - var(--panel-bar) - var(--panel-gutter));    left: clamp(var(--panel-gutter), var(--panel-x), 100% - var(--panel-drawn-width) - var(--panel-gutter));    flex-direction: column;    width: var(--panel-drawn-width);    height: var(--panel-height);    min-height: var(--panel-bar);    max-height: calc(100% - 2 * var(--panel-gutter));    margin: 0;    padding: 0;    border: 0;    border-radius: calc(var(--panel-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    /* The header's tone and the body's scroll are finished by the panel's corner. */    overflow: clip;    background: var(--color-surface-floating);    color: var(--color-text-body);    box-shadow: var(--shadow-floating);    font-size: .875rem;    line-height: 1.5;    transform-origin: top;    @apply --pop;    transition-property: opacity, scale, box-shadow, overlay, display;    /* With no place given, a panel from right to left opens at the top left. */    &:dir(rtl) {      --panel-x: 0px;    }    &:popover-open {      display: flex;    }    /* Held by its handle or its corner: it rises to the overlay shadow, and the drag selects nothing. */    &:has(.panel-handle:active:not(:disabled, [aria-disabled="true"]), .panel-resize:active:not([aria-disabled="true"])) {      box-shadow: var(--shadow-overlay);      user-select: none;      -webkit-user-select: none;    }    /* The keys move the whole panel, so focus on its handle rings the whole panel. */    &:has(.panel-handle:focus-visible) {      @apply --focus-ring;    }    /*     * Folded to its header: only as tall as the header, with no body and no corner to resize from. The body is     * hidden from sight, focus and assistive technology even where a utility gives it a display of its own.     */    &:has(.panel-minimize[aria-pressed="true"]) {      height: var(--panel-bar);      .panel-body,      .panel-resize {        display: none;        visibility: hidden;      }    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;      &:has(.panel-handle:focus-visible) {        outline: 2px solid Highlight;        outline-offset: 2px;      }    }  }  /* The header: the title at the start, the actions at the end, and the handle under both. */  .panel-header {    position: relative;    display: flex;    flex: none;    align-items: center;    gap: .25rem;    min-height: var(--panel-bar);    padding: var(--panel-inset);    padding-inline-start: .875rem;  }  /*   * The handle: a button the size of the header, under the title and the actions, so the bar is what the hand   * grabs. It draws nothing of its own; its focus is drawn on the panel.   */  .panel-handle {    position: absolute;    inset: 0;    margin: 0;    padding: 0;    border: 0;    border-radius: 0;    outline: none;    background: transparent;    color: inherit;    appearance: none;    cursor: grab;    touch-action: none;    user-select: none;    -webkit-user-select: none;    -webkit-tap-highlight-color: transparent;    &:active:not(:disabled, [aria-disabled="true"]) {      cursor: grabbing;    }    /* A handle the page turned off carries nothing, so it does not offer the hand. */    &:is(:disabled, [aria-disabled="true"]) {      cursor: default;    }  }  /* The title takes no pointer, so a press on it reaches the handle under it. */  .panel-title {    flex: 1 1 auto;    min-width: 0;    margin: 0;    overflow: hidden;    color: var(--color-text-strong);    font: var(--font-weight-control) .875rem/1.25 var(--font-family-sans);    font-feature-settings: inherit;    text-overflow: ellipsis;    white-space: nowrap;    pointer-events: none;  }  /* The controls at the end of the header, over the handle. */  .panel-actions {    position: relative;    display: inline-flex;    flex: none;    align-items: center;    gap: 2px;    margin-inline-start: auto;  }  /* The two stand 2px apart: on touch each target grows above and below only, so Close does not answer for Minimize. */  @media (pointer: coarse) {    .panel-actions .btn::after {      @apply --touch-target-block;    }  }  /* The minimize button is a quiet toggle: pressed, it sits in a well, and the panel is folded to its header. */  .panel-minimize {    flex: none;  }  /* What the panel holds, under a hairline. A long body scrolls inside the panel. */  .panel-body {    flex: 1 1 auto;    min-height: 0;    padding: var(--panel-padding);    border-block-start: 1px solid var(--color-line-hair);    overflow: auto;    overscroll-behavior: contain;    scrollbar-width: thin;    scrollbar-color: var(--color-line-strong) transparent;  }  /*   * The corner a pointer resizes from, at the bottom end: two short diagonal lines in the ink of a firm line,   * on a 16px target, 44px on touch screens. The keys resize from the handle.   */  .panel-resize {    position: absolute;    inset-block-end: 0;    inset-inline-end: 0;    width: 1rem;    height: 1rem;    color: var(--color-line-mark);    cursor: nwse-resize;    touch-action: none;    user-select: none;    -webkit-user-select: none;    -webkit-tap-highlight-color: transparent;    transition: color var(--duration-quick) var(--easing-glide);    &::before {      content: '';      position: absolute;      inset-block-end: .3125rem;      inset-inline-end: .3125rem;      width: .5rem;      height: .5rem;      background: linear-gradient(135deg, transparent 38%, currentColor 38% 50%, transparent 50% 70%, currentColor 70% 82%, transparent 82%);    }    &:dir(rtl) {      cursor: nesw-resize;      &::before {        scale: -1 1;      }    }    @media (hover: hover) {      &:hover {        color: var(--color-text-muted);      }    }    &:active {      color: var(--color-text-strong);    }    @media (pointer: coarse) {      width: 2.75rem;      height: 2.75rem;      color: var(--color-text-muted);    }    /* A corner the page turned off resizes nothing: it keeps its place in disabled ink and offers no resize. */    &[aria-disabled="true"] {      color: var(--color-text-disabled);      cursor: default;    }    /* The two lines are a gradient, which forced colors would drop: kept out of them, in the system's text color. */    @media (forced-colors: active) {      forced-color-adjust: none;      color: CanvasText;    }  }}