網站導覽

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-item-back 往開頭滑、sortable-item-forward 往結尾滑,距離為 --sortable-size,也就是搬移中項目的尺寸加上其後的間距,在拿起項目時測量。空出來的位置就是落點。項目的原位會保持空白,讓使用者看得出它從哪裡來。
  • 放下。 讓出空間的項目已經站在最終位置上,因此只要一次變更,就能收回空間並將節點放進空位。在 view transition(檢視轉場)中,每個項目都透過 view-transition-name: match-element 成為獨立的畫面,只有搬移中的項目會從放開的位置移到它的新位置。過程中根元素會設為 aria-busy="true",其他項目都不會滑動。

瀏覽器若不支援 view transition,搬移中的項目會直接出現在新位置,其他項目則已經就位。啟用減少動態效果時,不會有放大、滑動或轉場效果。

#卡片

任何容納項目的元素都可以排序。這裡的每個項目都是一張卡片,排成帶有間距的一疊,卡片讓出的空間也會包含這段間距;搬移中卡片所浮起的表面,會透過 --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 會拿起項目。沿清單方向的方向鍵每次將項目移動一格;在拿起項目之前,方向鍵不會有任何作用,因此螢幕閱讀器自己的方向鍵操作仍可正常使用。按 Enter 或 Space 會放下項目,按 Escape 會將項目放回拿起時的位置,焦點離開把手時也會放下項目。
  • 朗讀內容。 每次拿起、移動、放下和取消,都會在 sortable-status 區域中朗讀項目名稱和位置,例如「帳務,4 個項目中的第 3 個。」這個區域帶有 role="status",放在根元素內或緊接在根元素之後。傳入 messages 即可改用頁面的語言朗讀。
  • 移動的是項目節點本身;瀏覽器支援時會使用 moveBefore(),因此項目內的狀態會保留下來,例如欄位中的文字、正在播放的影片和焦點。在其他瀏覽器中,項目會重新插入,並重新讓把手取得焦點。
  • 事件。 放下後若順序有變,根元素會派送 input 和 change。傳回的函式帶有 value,也就是項目的順序,每個項目以其 data-value 或文字表示。設定 value 會將項目排成該順序,但不會派送任何事件。

sortable-row 讓清單改為橫向排列:位移改為水平方向,落點線改為直立,並改用 ArrowLeft 和 ArrowRight 移動,由右至左排列時方向相反。

未掛上行為時,清單會維持原本的順序,內容仍可閱讀。

可排序清單只處理單一清單。如果項目還會在清單之間移動,例如看板的各個階段,請使用看板。

#鍵盤操作

按鍵動作
Enter, Space在把手上時,拿起項目;再按一次則將項目放在目前位置
ArrowUp, ArrowDown將拿起的項目移動一格。在 sortable-row 中改用 ArrowLeft 和 ArrowRight,由右至左排列時方向相反
Home, End將拿起的項目移到第一個或最後一個位置
Escape將項目放回拿起時的位置,或拖曳開始時的位置
Tab離開把手,並放下項目

#無障礙

  • 以把手所移動的內容為每個把手命名,例如「移動帳務」。把手是項目上唯一用來調整順序的控制項,而且拖曳絕不是唯一的方式:按一下會拿起項目,再按另一個把手就會把它放到那裡;指標能做到的每一次移動,按鍵也都能做到。
  • 從一開始就在頁面中放好空白的狀態區域:在要朗讀時才加入的區域,常常不會被讀出。
  • 若順序會影響頁面的功能,例如優先順序或工作流程的步驟,請在清單附近說明,並以頁面儲存其他資料的方式儲存新的順序。

#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;  }}