ナビゲーション

v2.1.0
オーバーレイ

フローティングパネル

移動やサイズ変更ができ、ヘッダーだけに折りたたんだり、閉じたりできるフローティングサーフェス。

このページの内容

フローティングパネルは、作業中の内容の横に開いたまま置いておける浮動サーフェスで、その下のページも引き続き操作できます。キャンバスのレイヤー、カラーピッカー、インスペクター、チャットなどに使います。読者はヘッダーをドラッグして移動し、隅からサイズを変え、ヘッダーだけに折りたたみ、閉じることができます。role="dialog" を指定した popover="manual" なので、ブラウザーがボタンからパネルを開き、トップレイヤーに持ち上げてページ上のすべての要素より手前に表示します。z-index の順序を管理する必要はありません。移動、サイズ変更、折りたたみ、Escape キー、フォーカス、どのパネルを手前に表示するかといった残りの処理は、panel のビヘイビアが行います。

フローティングパネル

<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 です。
  • ヘッダーは、同じシートの上に細い区切り線を伴って置かれるバーで、先頭にタイトル、末尾にアクションが並びます。その両方の下に、バーと同じ大きさのボタンであるハンドルがあります。そのため、ヘッダー上のコントロール以外の場所を押すとパネルをつかめ、カーソルは開いた手から握った手に変わります。タイトルはポインター操作を受け取らないため、タイトルを押してもハンドルに届きます。
  • ハンドルにフォーカスすると、パネル全体にリングが表示されます。キー操作で動くのはパネル全体だからです。
  • 折りたたみ 最小化ボタンを押すと、パネルはヘッダーだけになります。本文と隅は非表示になり、ボタンはくぼんだ表示になります。
  • 本文は、使える領域より長い場合、下のページを動かさずにパネルの中でスクロールします。
  • 隅は末尾側の下にある 2 本の短い斜線で、ターゲットの大きさは 16px です。タッチスクリーンでは 44px になります。タッチスクリーンでもヘッダーのボタン自体のサイズは変わらず、操作領域がヘッダーの端まで広がります。

#配置

位置とサイズはカスタムプロパティで表します。--panel-x と --panel-y は左上隅の位置で、ビューポートの左上隅からのピクセル数です。--panel-width と --panel-height は幅と高さです。これらの値はイベントからしかわからないため、ビヘイビアがポインターとキー操作に応じて書き込みます。プレビューで各パネルの初期位置を指定しているように、ページ側で書き込むこともできます。

配置と制限はスタイルシートが clamp() で行います。基準は、固定配置の要素がパーセンテージを読み取るビューポートで、スクロールバーは含みません。

  • パネルはビューポートより広くならず、--panel-min-width(12rem)より狭くならず、幅全体がビューポート内に収まります。
  • ヘッダーがビューポートの外に出ることはないため、パネルは常に見つけてドラッグで戻せます。パネルはビューポートより高くならず、収まらない本文はスクロールします。
  • ウィンドウが狭くなると、パネルは内側に押し込まれます。広くなると、指定された位置に戻ります。clamp() によって、保持している位置自体は変わらないためです。
  • 位置を指定しない場合、パネルは末尾側の上隅に、そこから 8px(--panel-gutter)内側の位置で開きます。

移動とサイズ変更が終わるたびに、ビヘイビアはスタイルシートがパネルを描画した位置を読み取って保持します。そのため、アプリケーションが保存する値は、読者が見ていた位置になります。

#複数のパネル

パネルは、表示された順にトップレイヤーに並びます。最後に表示したパネルが最も手前です。別のパネルの後ろにあるパネルの中を押すかフォーカスすると、そのパネルが手前に来ます。ビヘイビアがそのパネルを表示し直し、トップレイヤーの最後に置くためです。非表示と表示は、ブラウザーが描画する前に 1 つのタスク内で行われるため、パネルが消えたようには見えず、表示時のアニメーションも再生されません。ブラウザーは、開いた状態から開いた状態への toggle を 1 回だけ通知します。フォーカスは読者が置いた場所に留まります。

#ビヘイビア

panel は、panel クラスを持つ要素であるルートを受け取り、ビヘイビアを解除する関数を返します。value は、パネルの位置、大きさ、折りたたまれているかどうかを表す { x, y, width, height, minimized } です。4 つの数値はピクセル単位で、スタイルシートの既定値が適用されている場合は 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 キーを押しながらだとその 4 倍移動します。
  • サイズ変更 隅をドラッグすると --panel-width と --panel-height を書き込みます。ハンドル上で Alt キーを押しながら矢印キーを押しても、1 ステップずつ同じ操作ができます。右から左に書く言語では隅が左下にあるため、パネルは左に広がり、Alt+ArrowLeft で幅が広くなります。
  • 折りたたみ 最小化ボタンをクリックすると、その aria-pressed が切り替わります。
  • 閉じる パネル内にフォーカスがあるときに Escape を押すと、パネルが閉じます。ただし、先に閉じるメニューのように、内部のコントロールがそのキーを処理した場合は閉じません。閉じるボタンにスクリプトは不要で、command="hide-popover" を指定するだけです。
  • フォーカス コントロールから開いたパネルは、フォーカスをハンドルに移します。パネル内にフォーカスがある状態で閉じると、フォーカスをそのコントロールに戻します。ページの読み込み時に開くパネルは、フォーカスを移動しません。
  • イベント ルートは、パネルの移動中やサイズ変更中に input を、ドラッグが終わったとき、キー操作で動いたとき、折りたたまれたときに change を発行します。どちらもバブリングするため、本文内のフィールドのイベントもルートに届きます。event.target とルートを比較して区別します。
オプション設定する内容
step矢印キーでパネルを移動またはサイズ変更する量。ピクセル単位です。既定値は 16 です

ビヘイビアを適用しない場合でも、パネルはボタンからページの上のトップレイヤーに開き、閉じるボタンで閉じます。位置は、カスタムプロパティが指定した場所に留まります。

#ボタンから開く

commandfor と command="toggle-popover" を指定したボタンで、パネルを開閉します。popovertarget でも同じことができます。パネルはタブ移動の順序でボタンの次に位置し、開くとフォーカスがハンドルに移るため、すぐに矢印キーで移動できます。開閉ボタン、閉じるボタン、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, Spacecommandfor と command="toggle-popover" を指定したボタン上で、パネルを開いてハンドルにフォーカスを移動します。もう一度押すと閉じます。
ArrowLeft, ArrowRight, ArrowUp, ArrowDownハンドル上で、パネルをその方向に 1 ステップ(16px)移動します。ビューポートの端で止まります。
Shift+Arrow keysハンドル上で、パネルを 4 ステップ移動します。
Alt+ArrowRight, Alt+ArrowLeftハンドル上で、パネルの幅を 1 ステップ広げる、または狭めます。Shift では 4 ステップです。右から左では、サイズ変更の起点となる隅が左側にあるため逆になります。
Alt+ArrowDown, Alt+ArrowUpハンドル上で、パネルの高さを 1 ステップ高く、または低くします。Shift では 4 ステップです。折りたたんだパネルは高さを保ちます。
Enter, Space最小化ボタン上で、パネルをヘッダーに折りたたむ、または展開します。
Escapeパネル内にフォーカスがある場合は、パネルを閉じて開いたコントロールにフォーカスを戻します。開いているメニューなど、内部で Escape を処理するコントロールがある場合は、そちらが優先されます。
Tab, Shift+Tabハンドル、アクション、本文の間を移動し、さらにページへ移動します。パネルはモーダルではありません。

#アクセシビリティ

  • パネルは role="dialog" で、aria-labelledby でタイトルを名前にします。モーダルではありません。aria-modal は指定せず、ページは操作可能なままで、Tab キーでパネルの外に移動できます。先にタスクを完了させる必要がある場合は、ダイアログを使います。
  • ハンドルは実際のボタンなので、ボタンとして読み上げられ、同じ方法で到達できます。「矢印キーでレイヤーパネルを移動」のように、何をどのように動かすかを名前にします。隅は支援技術から隠します。キー操作ではハンドルからサイズを変えられるためです。
  • すべてのドラッグ操作にキー操作があります。矢印キーで移動し、Alt キーを押しながら矢印キーでサイズを変えます。ポインターを使う読者がドラッグできない場合に備えて、1 回押すだけの操作も用意します。ヘッダーに「左端に固定」のように値を設定する項目を持つメニューを置くだけで十分です。
  • 最小化ボタンは名前を変えず、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-title1 行のタイトルです。パネルの 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;    }  }}