탐색

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는 항목을 집어 들 때 측정한, 옮기는 항목의 크기와 그 뒤 간격을 더한 값입니다. 이렇게 생긴 빈자리가 항목이 놓일 곳입니다. 항목의 원래 자리는 비어 있으므로 사용자는 항목이 어디서 왔는지 알 수 있습니다.
  • 놓기. 자리를 비켜 준 항목들은 이미 최종 위치에 있으므로, 이동은 비켜 준 공간을 없애고 노드를 빈자리에 넣는 작업을 한 번의 변경으로 처리합니다. 뷰 트랜지션(view transition) 안에서는 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 키를 누르면 항목을 집어 듭니다. 목록 방향의 방향키를 누르면 한 칸씩 이동합니다. 항목을 집어 들기 전에는 방향키가 아무 동작도 하지 않으므로, 스크린 리더 자체의 방향키 조작은 그대로 작동합니다. Enter 또는 Space 키를 누르면 항목을 놓고, Escape 키를 누르면 집어 든 자리로 되돌립니다. 핸들에서 포커스가 벗어나도 항목을 놓습니다.
  • 안내 메시지. 집어 들기, 이동, 놓기, 취소는 각각 sortable-status 영역에서 항목의 이름과 위치와 함께 안내합니다(예: "청구, 4개 중 3번째."). 이 영역은 루트 요소 안이나 바로 뒤에 두는 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핸들을 벗어나며 항목을 놓습니다.

#접근성

  • 각 핸들의 이름에는 무엇을 옮기는지 밝히세요(예: "청구 항목 이동"). 핸들은 항목의 순서를 바꾸는 유일한 컨트롤이지만, 드래그만 사용해야 하는 일은 없습니다. 누르면 항목을 집어 들고 다른 핸들을 누르면 그 자리에 놓으며, 포인터로 할 수 있는 모든 이동은 키보드로도 할 수 있습니다.
  • 상태 영역은 처음부터 비어 있는 상태로 페이지에 두세요. 안내하는 순간에 추가한 영역은 스크린 리더가 읽지 못하는 경우가 많습니다.
  • 우선순위나 작업 흐름의 단계처럼 순서가 페이지의 기능에 중요하다면 목록 근처에 그 사실을 알리고, 페이지에서 다른 데이터를 저장하는 방식과 같은 방식으로 새 순서를 저장하세요.

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