导航

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>
拖动握把;或者先按一下握把,再按目标位置上的握把。使用键盘时,聚焦握把后按空格键,用方向键移动,再按一次空格键放下。

#样式表绘制的内容

  • 手柄。 内含握把图标的按钮,指针或键盘到达前保持低调,光标为握拳的手形。手柄大小为 24 × 28px,在触屏上,手柄的触控区域扩展到 44px,握把位置不变。手柄设置了 touch-action: none,因此从手柄开始的拖动不会滚动页面,而从项目其余部分开始的手势仍可滚动页面。
  • 被拖动的项目会抬起:周围出现一块略超出项目边缘的凸起面板,因此项目内容不会移动,同时带有抬起阴影并放大 1.5%。项目通过行为脚本写入的 --sortable-offset 跟随指针,指针和项目之间没有缓动。行在自身下方绘制的线条(例如列表的分隔细线)会留在被它分开的那一行上。
  • 让出空间。 位于被拖动项目原位置和其落点之间的项目会平滑移开,sortable-item-back 移向开头,sortable-item-forward 移向末尾,移动距离为 --sortable-size,即拿起项目时测得的项目尺寸加上其后的间距。腾出的空隙就是落点。项目原来的位置保持空白,读者可以看出它来自哪里。
  • 放下。 让出空间的项目已经位于各自的落点,因此移动操作只需一次变更:撤销让出的空间,并将节点放入空隙。在视图过渡中,每个项目通过 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 时,会拿起项目;移动不足 4px 则视为一次按下。项目被拖动期间,手柄带有 aria-pressed="true",项目跟随指针,经过的项目会让出空间。落点根据各项目在布局中的实际位置判断,而不是根据它们让出空间后的位置,因此落点不会追着自己跑。松开指针即完成移动,按 Esc 则会放回项目,其他项目也会滑回原位。列表可以滚动时,指针靠近列表任一端会滚动列表,越靠近末端滚动越快。只有开始拖动的那个指针能移动项目。
  • 不拖动。 在手柄上按下但不移动,即单击或轻点,会像按 Enter 一样拿起项目,并让它的手柄获得焦点。随后按另一个项目的手柄,会把项目移到那个位置并放下;再按它自己的手柄,则在原处放下。无法拖动的指针以及屏幕阅读器的双击,都可以用这种方式为列表排序。
  • 键盘。 在手柄上按 Enter 或 空格键 会拿起项目。沿列表方向的方向键每次将项目移动一个位置;拿起项目之前,这些方向键不起作用,因此屏幕阅读器自身的方向键操作仍然可用。按 Enter 或 空格键 放下项目,按 Esc 将其放回拿起时的位置,焦点离开手柄也会放下项目。
  • 播报。 每次拿起、移动、放下和取消都会在 sortable-status 区域中播报,内容包括项目名称和位置,例如“Billing, position 3 of 4.”。该区域是位于根元素内部或紧随其后的 role="status"。传入 messages 可使用页面的语言播报。
  • 移动的是项目节点本身;浏览器支持 moveBefore() 时使用该方法,因此项目内的内容会保留状态,例如输入框中的文字、正在播放的视频和焦点。不支持时,节点会被重新插入,手柄也会重新获得焦点。
  • 事件。 放下项目后,如果顺序发生了变化,根元素会派发 input 和 change。返回的函数带有 value,即项目的顺序,每项取其 data-value,未设置时取其文本。为它赋值可将项目按该顺序排列,但不会派发任何事件。

sortable-row 让列表横向排列:偏移改为水平方向,落点线改为竖直,由 ArrowLeft 和 ArrowRight 移动项目;在从右到左的布局中,方向相反。

没有行为脚本时,列表保持原有顺序,内容仍然可读。

可排序列表只有一个列表。如果项目还会在多个列表之间移动,例如看板的各个阶段,请使用看板。

#键盘操作

按键操作
Enter, Space位于手柄上时,拿起项目;再按一次,将其放在当前位置
ArrowUp, ArrowDown将已拿起的项目移动一个位置;在 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;  }}