網站導覽

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浮動面板本體:設有 role="dialog" 的 popover="manual",以 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;    }  }}