ナビゲーション

v2.1.0
構造

並べ替えリスト

ハンドルのドラッグまたはキー操作で項目の順序を変えられるリスト。

このページの内容

並べ替えリストは、ハンドルのドラッグまたはキー操作で項目の順序を変えられるリストです。並べ替えリスト自体は項目の行を生成しません。リスト、カードを積み重ねた列など、項目を収める任意の要素に適用し、各項目にハンドルを付けます。ハンドルは、移動する対象を名前に含めたボタンです。sortable のビヘイビアは、ほかの項目が場所を空けるなかで項目を運び、ドロップしたときに一度だけそのノードを移動します。

並べ替えリスト

<div class="max-w(420) mx-auto">  <ol class="list sortable" aria-label="Priorities this quarter">    <li class="list-row sortable-item" data-value="onboarding">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Onboarding</span><span class="list-description">First run, invitations and the empty states</span>      </span>      <span class="list-end">Mar 2</span>    </li>    <li class="list-row sortable-item" data-value="billing">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Billing">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Billing</span><span class="list-description">Invoices in every currency</span>      </span>      <span class="list-end">Mar 16</span>    </li>    <li class="list-row sortable-item" data-value="search">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Search">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Search</span><span class="list-description">Filters that can be saved and shared</span>      </span>      <span class="list-end">Apr 6</span>    </li>    <li class="list-row sortable-item" data-value="exports">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Exports">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="list-body">        <span class="list-title">Exports</span><span class="list-description">CSV and PDF for every report</span>      </span>      <span class="list-end">Apr 27</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-react/native/16/soft/grip-vertical'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="max-w(420) mx-auto">      <ol className="list sortable" aria-label="Priorities this quarter">        <li className="list-row sortable-item" data-value="onboarding">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Onboarding</span><span className="list-description">First run, invitations and the empty states</span>          </span>          <span className="list-end">Mar 2</span>        </li>        <li className="list-row sortable-item" data-value="billing">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Billing">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Billing</span><span className="list-description">Invoices in every currency</span>          </span>          <span className="list-end">Mar 16</span>        </li>        <li className="list-row sortable-item" data-value="search">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Search">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Search</span><span className="list-description">Filters that can be saved and shared</span>          </span>          <span className="list-end">Apr 6</span>        </li>        <li className="list-row sortable-item" data-value="exports">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Exports">            <GripVerticalIcon className="icon" />          </button>          <span className="list-body">            <span className="list-title">Exports</span><span className="list-description">CSV and PDF for every report</span>          </span>          <span className="list-end">Apr 27</span>        </li>      </ol>      <p className="sortable-status" role="status"></p>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import GripVerticalIcon from '@master/icons-svelte/native/16/soft/grip-vertical'</script><div class="max-w(420) mx-auto" {@attach attach}>  <ol class="list sortable" aria-label="Priorities this quarter">    <li class="list-row sortable-item" data-value="onboarding">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Onboarding</span><span class="list-description">First run, invitations and the empty states</span>      </span>      <span class="list-end">Mar 2</span>    </li>    <li class="list-row sortable-item" data-value="billing">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Billing">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Billing</span><span class="list-description">Invoices in every currency</span>      </span>      <span class="list-end">Mar 16</span>    </li>    <li class="list-row sortable-item" data-value="search">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Search">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Search</span><span class="list-description">Filters that can be saved and shared</span>      </span>      <span class="list-end">Apr 6</span>    </li>    <li class="list-row sortable-item" data-value="exports">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Exports">        <GripVerticalIcon class="icon" />      </button>      <span class="list-body">        <span class="list-title">Exports</span><span class="list-description">CSV and PDF for every report</span>      </span>      <span class="list-end">Apr 27</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-vue/native/16/soft/grip-vertical'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="max-w(420) mx-auto">    <ol class="list sortable" aria-label="Priorities this quarter">      <li class="list-row sortable-item" data-value="onboarding">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Onboarding">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Onboarding</span><span class="list-description">First run, invitations and the empty states</span>        </span>        <span class="list-end">Mar 2</span>      </li>      <li class="list-row sortable-item" data-value="billing">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Billing">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Billing</span><span class="list-description">Invoices in every currency</span>        </span>        <span class="list-end">Mar 16</span>      </li>      <li class="list-row sortable-item" data-value="search">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Search">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Search</span><span class="list-description">Filters that can be saved and shared</span>        </span>        <span class="list-end">Apr 6</span>      </li>      <li class="list-row sortable-item" data-value="exports">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Exports">          <GripVerticalIcon class="icon" />        </button>        <span class="list-body">          <span class="list-title">Exports</span><span class="list-description">CSV and PDF for every report</span>        </span>        <span class="list-end">Apr 27</span>      </li>    </ol>    <p class="sortable-status" role="status"></p>  </div></template>
グリップをドラッグします。または、グリップを押してから移動先のグリップを押します。キー操作では、グリップにフォーカスして Space キーを押し、矢印キーで移動してから、もう一度 Space キーを押します。

#スタイルシートの描画内容

  • ハンドル グリップアイコンを入れたボタンです。ポインターやキー操作が届くまでは控えめに表示され、カーソルは握った手の形になります。ハンドルの大きさは 24×28px です。タッチ画面では、グリップの位置を変えずに操作領域が 44px まで広がります。touch-action: none が指定されているため、ハンドルから始めたドラッグでページがスクロールすることはありません。項目のほかの部分では、通常どおりスクロールできます。
  • 運ばれている項目 項目が持ち上がります。浮き上がったシートが項目の端から少しはみ出す大きさで周囲に広がるため、中身は動きません。浮き上がりを示す影が付き、1.5% だけ膨らみます。項目は、ビヘイビアが書き込む --sortable-offset によってポインターに追従し、ポインターと項目の間にイージングはかかりません。リストの細い罫線のように行の下に描かれる線は、項目が離れた元の行に残ります。
  • 場所を空ける動き 運ばれている項目の元の位置と移動先の間にある項目が、--sortable-size の分だけ滑るように位置をずらします。先頭方向へは sortable-item-back、末尾方向へは sortable-item-forward です。--sortable-size は、持ち上げた時点で計測した、運ばれている項目の大きさとその後ろの間隔を合わせた値です。空いた隙間が移動先になります。元の位置は空いたままなので、どこから運んできたかがわかります。
  • ドロップ 場所を空けた項目はすでに移動先に並んでいるため、空けた場所の解消と隙間へのノードの配置が 1 回の変更で行われます。各項目を view-transition-name: match-element によって個別の画像として扱うビュートランジションの中で、運ばれていた項目だけが、離した位置から移動先へ移動します。その間、ルート要素は aria-busy="true" を示し、ほかの項目は動きません。

ビュートランジションに対応していないブラウザーでは、運ばれていた項目はすぐに移動先に収まります。ほかの項目はすでに移動先にあります。動きを抑える設定では、膨らみ、滑るような移動、トランジションのいずれも行いません。

#カード

項目を収める要素であれば、何でも並べ替えられます。この例では、各項目が間隔をあけて積み重ねたカードです。カードが空ける場所には、この間隔も含まれます。運ばれているカードが乗るシートは、--sortable-radius によってカードと同じ角丸になります。

カード

<div class="max-w(360) mx-auto">  <ol class="list sortable gap-xs" aria-label="Release checklist" style="--sortable-radius: var(--radius-surface)">    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Freeze the branch</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="notes">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Write the release notes</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="staging">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Deploy to staging</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="announce">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" />        </svg>      </button>      <span class="text-sm fg-text-strong">Announce the release</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-react/native/16/soft/grip-vertical'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="max-w(360) mx-auto">      <ol className="list sortable gap-xs" aria-label="Release checklist" style={{ '--sortable-radius': 'var(--radius-surface)' } as React.CSSProperties}>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Freeze the branch</span>        </li>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="notes">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Write the release notes</span>        </li>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="staging">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Deploy to staging</span>        </li>        <li className="card sortable-item flex items-center gap-sm p-sm" data-value="announce">          <button type="button" className="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">            <GripVerticalIcon className="icon" />          </button>          <span className="text-sm fg-text-strong">Announce the release</span>        </li>      </ol>      <p className="sortable-status" role="status"></p>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import GripVerticalIcon from '@master/icons-svelte/native/16/soft/grip-vertical'</script><div class="max-w(360) mx-auto" {@attach attach}>  <ol class="list sortable gap-xs" aria-label="Release checklist" style="--sortable-radius: var(--radius-surface)">    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Freeze the branch</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="notes">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Write the release notes</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="staging">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Deploy to staging</span>    </li>    <li class="card sortable-item flex items-center gap-sm p-sm" data-value="announce">      <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">        <GripVerticalIcon class="icon" />      </button>      <span class="text-sm fg-text-strong">Announce the release</span>    </li>  </ol>  <p class="sortable-status" role="status"></p></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import GripVerticalIcon from '@master/icons-vue/native/16/soft/grip-vertical'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="max-w(360) mx-auto">    <ol class="list sortable gap-xs" aria-label="Release checklist" style="--sortable-radius: var(--radius-surface)">      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="freeze">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Freeze the branch">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Freeze the branch</span>      </li>      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="notes">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Write the release notes">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Write the release notes</span>      </li>      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="staging">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Deploy to staging">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Deploy to staging</span>      </li>      <li class="card sortable-item flex items-center gap-sm p-sm" data-value="announce">        <button type="button" class="sortable-handle" aria-pressed="false" aria-label="Move Announce the release">          <GripVerticalIcon class="icon" />        </button>        <span class="text-sm fg-text-strong">Announce the release</span>      </li>    </ol>    <p class="sortable-status" role="status"></p>  </div></template>

#ビヘイビア

sortable は、sortable クラスを持つルート要素を受け取り、ビヘイビアを解除する関数を返します。

app.js
import { sortable } from '@master/ui/behaviors/sortable.js'const priorities = sortable(document.querySelector('.sortable'))priorities.value // ['onboarding', 'billing', 'search', 'exports']
  • ポインター ハンドルを押したまま 4px を超えて動かすと、項目が持ち上がります。それ未満なら通常の押下として扱います。運んでいる間、ハンドルは aria-pressed="true" を示し、項目はポインターに追従し、通過した項目が場所を空けます。移動先は、場所を空ける途中の位置ではなく、レイアウト上の項目の位置から判定するため、移動先が自身を追いかけるように揺れ動くことはありません。ポインターを離すと項目が移動し、Escape を押すと、ほかの項目が元の位置へ滑って戻るなかで項目も元の位置に戻ります。スクロールするリストでは、ポインターがリストのどちらかの端に近づくとリストがスクロールし、端に寄るほど速くなります。項目を動かせるのは、ドラッグを始めたポインターだけです。
  • ドラッグしない操作 ハンドルを動かさずに押す、つまりクリックやタップをすると、Enter と同じように項目が持ち上がり、そのハンドルにフォーカスが移ります。続けてほかの項目のハンドルを押すと、その位置へ移動してドロップします。自分のハンドルをもう一度押すと、その場でドロップします。ドラッグできないポインターや、スクリーンリーダーのダブルタップでも、この方法でリストを並べ替えられます。
  • キー操作 ハンドルで Enter または Space を押すと、項目が持ち上がります。リストの並びに沿った矢印キーで、項目を 1 つずつ移動します。矢印キーは項目を持ち上げるまで何もしないため、スクリーンリーダー独自の矢印キー操作はそのまま使えます。Enter または Space でドロップし、Escape で持ち上げた位置に戻します。ハンドルからフォーカスが外れた場合もドロップします。
  • 読み上げ 持ち上げ、移動、ドロップ、取り消しのたびに、sortable-status 領域で項目の名前と位置を伝えます(例:「Billing, position 3 of 4.」)。この領域は、ルート要素の中、またはその直後に置く role="status" の要素です。ページの言語で伝えるには messages を渡します。
  • 移動 移動するのは項目のノードそのものです。ブラウザーが moveBefore() に対応していればそれを使うため、項目内の状態(フィールドのテキスト、再生中の動画、フォーカス)が保たれます。対応していない場合は項目を挿入し直し、ハンドルにフォーカスを戻します。
  • イベント ドロップによって順序が変わると、ルート要素が input と change を発行します。返される関数の value は項目の順序で、各項目の data-value、なければテキストを並べたものです。value に代入するとその順序に並べ替えますが、イベントは発行されません。

sortable-row を指定するとリストが横並びになります。ずらす方向が水平になり、移動先を示す線は縦になります。移動には ArrowLeft と ArrowRight を使い、右から左に並ぶ場合は方向が逆になります。

ビヘイビアを適用しない場合も、リストは元の順序のまま読めます。

並べ替えリストは 1 つのリストです。ボードの段階のように、項目がリストの間も移動する場合は、カンバンを使います。

#キーボード操作

キー操作
Enter, Spaceハンドルの上で項目を持ち上げます。もう一度押すと、その位置にドロップします。
ArrowUp, ArrowDown持ち上げた項目を 1 つ移動します。sortable-row では ArrowLeft と ArrowRight を使い、右から左に並ぶ場合は方向が逆になります。
Home, End持ち上げた項目を先頭または末尾に移動します。
Escape項目を、持ち上げた位置またはドラッグを始めた位置に戻します。
Tabハンドルから移動します。項目はその位置にドロップされます。

#アクセシビリティ

  • 各ハンドルには、移動する対象を含む名前を付けます(例:「Move Billing」)。ハンドルは項目の順序を変える唯一のコントロールですが、ドラッグだけが手段になることはありません。押すと項目が持ち上がり、ほかのハンドルを押すとそこへ移動します。ポインターでできる移動は、すべてキー操作でもできます。
  • ステータス領域は、最初から空の状態でページに置いておきます。読み上げる瞬間に追加した領域は、読み上げられないことがよくあります。
  • 優先度やワークフローの手順など、順序がページの動作に関わる場合は、リストの近くでそのことを説明し、新しい順序はページのほかのデータと同じ方法で保存します。

#React、Svelte、Vue

sortable コンポーネントは、保持している順序で項目を描画してビヘイビアを適用し、ビヘイビアから求められると自身のリスト内で項目を移動します。そのため、フレームワークが管理する行とページの表示が一致します。npx master-ui add sortable でプロジェクトにコピーできます。コンポーネントの構成と使い方は React、Svelte、Vue を参照してください。

ui/sortable.tsx
'use client'import { useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react'import { sortable, type SortableMessages } from '@master/ui/behaviors/sortable.js'import { useBehavior } from './use-behavior'export interface SortableItem {  /** What the item stands for in the order. */  value: string  /** What the item is called: its handle is named "Move <label>", and the status says it. */  label: string}export interface SortableProps<T extends SortableItem> extends Omit<ComponentProps<'ol'>, 'children' | 'defaultValue' | 'ref'> {  items: T[]  /** The order, as the items' values. The order of `items` by default. */  value?: string[]  defaultValue?: string[]  onValueChange?: (value: string[]) => void  /** What an item shows beside its handle. */  children: (item: T) => ReactNode  /** Classes of each item, such as `list-row` in a `list`. */  itemClassName?: string  /** The accessible name of a handle. `Move <label>` by default. */  handleLabel?: (item: T) => string  /** What the status region says, in the page's language. */  messages?: SortableMessages}/** * A list the reader puts in order. React writes the items in the order it holds; the behavior carries them * with the pointer and the keys, and asks React to move one when it is dropped. */export function Sortable<T extends SortableItem>({ items, value, defaultValue, onValueChange, children, itemClassName, handleLabel = item => `Move ${item.label}`, messages, className, ...root }: SortableProps<T>) {  const [kept, setKept] = useState(() => value ?? defaultValue ?? items.map(item => item.value))  const order = value ?? kept  const shown = [...items].sort((a, b) => rank(order, a.value) - rank(order, b.value))  const latest = useRef(shown)  latest.current = shown  // A move waits for the render that puts the item in its place, so a view transition pictures it there.  const waiting = useRef<(() => void)[]>([])  useLayoutEffect(() => {    waiting.current.splice(0).forEach(done => done())  })  const move = (from: number, to: number) => new Promise<void>((done) => {    const next = latest.current.map(item => item.value)    const [moved] = next.splice(from, 1)    next.splice(to, 0, moved!)    waiting.current.push(done)    setKept(next)    onValueChange?.(next)  })  const ref = useBehavior(sortable, { messages, move })  return (    <>      <ol className={className ? `sortable ${className}` : 'sortable'} ref={ref} {...root}>        {shown.map(item => (          <li className={itemClassName ? `sortable-item ${itemClassName}` : 'sortable-item'} data-value={item.value} key={item.value}>            <button type="button" className="sortable-handle" aria-pressed="false" aria-label={handleLabel(item)}><svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" /></svg></button>            {children(item)}          </li>        ))}      </ol>      <p className="sortable-status" role="status" />    </>  )}/** Where a value stands in an order; one the order leaves out goes after it. */function rank(order: string[], value: string) {  const index = order.indexOf(value)  return index < 0 ? order.length : index}
ui/Sortable.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLOlAttributes } from 'svelte/elements'  import type { SortableMessages } from '@master/ui/behaviors/sortable.js'  export interface SortableItem {    /** What the item stands for in the order. */    value: string    /** What the item is called: its handle is named "Move <label>", and the status says it. */    label: string  }  export interface SortableProps<T extends SortableItem> extends Omit<HTMLOlAttributes, 'children'> {    items: T[]    /** The order, as the items' values. Bind it, or leave it out: the order of `items`. */    value?: string[]    onValueChange?: (value: string[]) => void    /** What an item shows beside its handle. */    children: Snippet<[T]>    /** Classes of each item, such as `list-row` in a `list`. */    itemClass?: string    /** The accessible name of a handle. `Move <label>` by default. */    handleLabel?: (item: T) => string    /** What the status region says, in the page's language. */    messages?: SortableMessages  }</script><script lang="ts" generics="T extends SortableItem">  import { tick, untrack } from 'svelte'  import { sortable } from '@master/ui/behaviors/sortable.js'  import { behavior } from './behavior.svelte.js'  let { items, value = $bindable(), onValueChange, children, itemClass, handleLabel = (item: T) => `Move ${item.label}`, messages, class: className, ...root }: SortableProps<T> = $props()  let kept = $state(untrack(() => value) ?? untrack(() => items.map(item => item.value)))  const order = $derived(value ?? kept)  const rank = (value: string) => {    const index = order.indexOf(value)    return index < 0 ? order.length : index  }  const shown = $derived([...items].sort((a, b) => rank(a.value) - rank(b.value)))  // A move waits for the render that puts the item in its place, so a view transition pictures it there.  const move = async (from: number, to: number) => {    const next = shown.map(item => item.value)    const [moved] = next.splice(from, 1)    next.splice(to, 0, moved!)    kept = next    value = next    onValueChange?.(next)    await tick()  }  const attach = behavior(sortable, () => ({ messages, move }))</script><!--  @component  A list the reader puts in order. Svelte writes the items in the order it holds; the behavior carries them  with the pointer and the keys, and asks Svelte to move one when it is dropped.--><ol class={['sortable', className]} {@attach attach} {...root}>  {#each shown as item (item.value)}    <li class={['sortable-item', itemClass]} data-value={item.value}>      <button type="button" class="sortable-handle" aria-pressed="false" aria-label={handleLabel(item)}><svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" /></svg></button>      {@render children(item)}    </li>  {/each}</ol><p class="sortable-status" role="status"></p>
ui/Sortable.vue
<script setup lang="ts" generic="T extends { value: string, label: string }">import { computed, nextTick, ref, useTemplateRef } from 'vue'import { sortable, type SortableMessages } from '@master/ui/behaviors/sortable.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { items, itemClass, handleLabel = (item: T) => `Move ${item.label}`, messages } = defineProps<{  /** Each with the value it stands for in the order and the label its handle and the status say. */  items: T[]  /** Classes of each item, such as `list-row` in a `list`. */  itemClass?: string  /** The accessible name of a handle. `Move <label>` by default. */  handleLabel?: (item: T) => string  /** What the status region says, in the page's language. */  messages?: SortableMessages}>()/** The order, as the items' values: `v-model`. The order of `items` by default. */const model = defineModel<string[]>()defineSlots<{  /** What an item shows beside its handle. */  default?: (props: { item: T }) => unknown}>()/* * A list the reader puts in order. Vue writes the items in the order it holds; the behavior carries them * with the pointer and the keys, and asks Vue to move one when it is dropped. */const kept = ref<string[]>(model.value ?? items.map(item => item.value))const order = computed(() => model.value ?? kept.value)const rank = (value: string) => {  const index = order.value.indexOf(value)  return index < 0 ? order.value.length : index}const shown = computed(() => [...items].sort((a, b) => rank(a.value) - rank(b.value)))// A move waits for the render that puts the item in its place, so a view transition pictures it there.const move = async (from: number, to: number) => {  const next = shown.value.map(item => item.value)  const [moved] = next.splice(from, 1)  next.splice(to, 0, moved!)  kept.value = next  model.value = next  await nextTick()}const root = useTemplateRef<HTMLOListElement>('root')useBehavior(root, sortable, () => ({ messages, move }))</script><template>  <ol class="sortable" ref="root" v-bind="$attrs">    <li v-for="item in shown" :key="item.value" class="sortable-item" :class="itemClass" :data-value="item.value">      <button type="button" class="sortable-handle" aria-pressed="false" :aria-label="handleLabel(item)"><svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="4" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="8" r="1" fill="currentColor" stroke="none" /><circle cx="6" cy="12" r="1" fill="currentColor" stroke="none" /><circle cx="10" cy="12" r="1" fill="currentColor" stroke="none" /></svg></button>      <slot :item="item" />    </li>  </ol>  <p class="sortable-status" role="status" /></template>

#クラス

クラス説明
sortable項目を収めるリストや積み重ねた列です。項目を運んでいる間、カーソルは握った手の形になります。
sortable-row項目を横に並べます。項目のずれと、ほかの項目が空ける場所は水平方向になります。sortable と併用します
sortable-item項目です。data-value、なければテキストを値とします。運んでいる間は、端から少しはみ出す浮き上がったシートの上に持ち上がり、ポインターに追従します。
sortable-item-back運んでいる項目を末尾方向へ動かしたとき、ドラッグ中にビヘイビアが、その項目の元の位置と移動先の間にある項目に設定します。各項目は --sortable-size の分だけ先頭方向へ滑るように移動します。sortable-item と併用します
sortable-item-forward運んでいる項目を先頭方向へ動かしたとき、ドラッグ中にビヘイビアが設定します。通過された各項目は --sortable-size の分だけ末尾方向へ滑るように移動します。sortable-item と併用します
sortable-handle項目を運ぶためのボタンで、グリップアイコンを入れます。移動する対象を名前に含めます。操作領域は 24×28px で、タッチ画面では 44px です。
sortable-status持ち上げ、移動、ドロップのたびに内容を伝える領域です。ルート要素の中、またはその直後に置きます。スペースは占有しません。

#カスタムプロパティ

プロパティ既定値説明
--sortable-offset運んでいる項目の、リストに沿った元の位置からの距離。スクリプトが書き込みます。
--sortable-sizeドラッグ中にルート要素に設定されます。運んでいる項目の大きさにその後ろの間隔を加えた値で、ほかの項目が場所を空ける距離です。スクリプトが書き込みます。
--sortable-radiusvar(--radius-control)運んでいる項目が乗るシートの角の丸み

#ソース

@master/ui/components/sortable.css
/* * Sortable: a list whose items are put in order by dragging a handle or with the keys. * It has no row of its own: it is put on a list, a stack of cards or anything that holds items, and adds * three things. The handle, a quiet grip that says the item can be carried. The carried item, which lifts: * a raised sheet grows around it a little past its edges, so its content does not move, with the lifted * shadow and a slight swell, and it follows the pointer through --sortable-offset. And the room it would land * in: the items between its place and that one glide aside by --sortable-size, so the gap is where it goes, * and nothing under the pointer answers it while they do. * The behavior moves the node once, on the drop, inside a view transition where there is one; the items that * made room are already where they land, so only the carried one travels. */@layer components.ui {  .sortable {    --sortable-radius: var(--radius-control);    /*     * While an item is carried, the cursor is a closed hand wherever the pointer goes, and the items it passes     * are not under the pointer: a row's hover or a handle's open hand would flicker on each item as it glides     * aside beneath it. The pointer stays with the carried handle, which holds it.     */    &:has(.sortable-handle[aria-pressed="true"]) {      cursor: grabbing;      user-select: none;      -webkit-user-select: none;      .sortable-item {        pointer-events: none;        /* Each item glides on a layer of its own, so its words are not drawn again at every step. */        will-change: translate;        /* Each item is its own picture in the view transition of a move, so each slides to its place. */        view-transition-name: match-element;      }    }    /*     * Picked up by the keys or by a press without a drag, the carried handle has focus and nothing follows the     * pointer: every handle takes a press again, another item's to move it to that place, its own to drop it.     */    &:has(.sortable-handle[aria-pressed="true"]:focus) .sortable-handle:not(:disabled) {      pointer-events: auto;    }    /* While the items change places, nothing glides but the transition, or an item would travel twice. */    &[aria-busy="true"] .sortable-item {      transition: none;    }  }  .sortable-item {    position: relative;    scroll-margin: .5rem;    transition-property: translate, scale;    transition-duration: var(--duration-base);    transition-timing-function: var(--easing-glide);    /* Making room for the carried item: toward the start of the list, or toward its end. */    &.sortable-item-back {      translate: 0 calc(-1 * var(--sortable-size, 0px));    }    &.sortable-item-forward {      translate: 0 var(--sortable-size, 0px);    }    /* Carried: above the others, a little larger, on a raised sheet, and under the pointer. */    &:has(.sortable-handle[aria-pressed="true"]) {      z-index: 2;      scale: 1.015;      translate: 0 var(--sortable-offset, 0px);      pointer-events: none;      /* The pointer moves it: no easing between the pointer and the item. */      transition-property: scale;      &::before {        content: '';        position: absolute;        inset: -.25rem -.5rem;        z-index: -1;        border-radius: calc(var(--sortable-radius) * var(--corner-scale));        corner-shape: var(--corner-shape);        @apply --surface-sheet;        box-shadow: var(--shadow-lifted);      }      /* A rule the row draws under itself, such as a list's hairline, stays with the row it parted. */      &::after {        opacity: 0;      }    }    @media (prefers-reduced-motion: reduce) {      transition-property: none;      &:has(.sortable-handle[aria-pressed="true"]) {        scale: 1;      }    }    @media (forced-colors: active) {      &:has(.sortable-handle[aria-pressed="true"])::before {        outline: 2px solid Highlight;      }    }  }  /* Across: the items run along the line, and both the offset and the room are horizontal. */  .sortable-row .sortable-item {    &.sortable-item-back {      translate: calc(-1 * var(--sortable-size, 0px)) 0;    }    &.sortable-item-forward {      translate: var(--sortable-size, 0px) 0;    }    &:dir(rtl) {      &.sortable-item-back {        translate: var(--sortable-size, 0px) 0;      }      &.sortable-item-forward {        translate: calc(-1 * var(--sortable-size, 0px)) 0;      }    }    &:has(.sortable-handle[aria-pressed="true"]) {      translate: var(--sortable-offset, 0px) 0;    }  }  /* The handle: a grip of six points, quiet until the pointer or the keys reach it. */  .sortable-handle {    position: relative;    display: inline-grid;    flex: none;    place-items: center;    width: 1.5rem;    height: 1.75rem;    margin: 0;    padding: 0;    border: 0;    border-radius: calc(var(--radius-chip) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: transparent;    color: var(--color-text-muted);    appearance: none;    cursor: grab;    touch-action: none;    user-select: none;    -webkit-user-select: none;    -webkit-tap-highlight-color: transparent;    transition-property: background-color, color;    transition-duration: var(--duration-quick);    transition-timing-function: var(--easing-glide);    /* The glyph is the button's icon. It takes no pointer of its own, so a press is the button's. */    .icon {      pointer-events: none;      width: .875rem;      height: .875rem;    }    /* The target reaches 44px on touch without moving the grip. */    &::after {      content: '';      position: absolute;      inset: -.25rem;      @media (pointer: coarse) {        inset: min(-.25rem, calc((100% - 2.75rem) / 2));      }    }    @media (hover: hover) {      &:hover:not(:disabled) {        background: var(--color-surface-chip);        color: var(--color-text-strong);      }    }    &:focus-visible {      @apply --focus-ring;      outline-offset: 0;      color: var(--color-text-strong);    }    /* Carried: the grip sits in a well, as a pressed button does. */    &[aria-pressed="true"] {      background: var(--color-surface-inset);      color: var(--color-text-strong);      box-shadow: var(--shadow-pressed);      cursor: grabbing;    }    &:disabled {      color: var(--color-text-disabled);      cursor: not-allowed;    }    @media (forced-colors: active) {      .icon {        color: ButtonText;      }      /* The grip is a fill, so the system's disabled ink is given to it here, as the color is given above. */      &:disabled .icon {        color: GrayText;      }    }  }  /* What the status region says is for assistive technology: it takes no room. */  .sortable-status {    position: absolute;    width: 1px;    height: 1px;    margin: -1px;    padding: 0;    overflow: hidden;    clip-path: inset(50%);    white-space: nowrap;  }}