Skip to content

SortableList (drag & drop) ​

A data-bound port of SortableJS. SortableJS reorders DOM nodes directly on drop — which is precisely what every framework's reconciler then fights, producing snap-back, lost focus, and broken animations. Every framework has a wrapper that solves this independently (react-sortablejs, vuedraggable, ngx-sortablejs, svelte-sortablejs); SortableList.rozie solves it once and compiles to all six.

What the wrapper demonstrates:

  • model: true two-way bind on an array — consumers pass an array and get the reordered array back via r-model:items="…", with no onChange → setState wiring. (Contrast Flatpickr's scalar r-model:date.)
  • The DOM-reconciler workaround — on onUpdate, the wrapper restores the pre-drag DOM order before writing the model. The framework then sees a model change against an unchanged DOM and reconciles cleanly, moving keyed nodes with proper transitions. This is the bug every per-framework wrapper has to fix; here it is fixed once.
  • A default scoped slot (:item / :index) so consumers render whatever they like per row, $watch reconciling disabled / group / handle into the live instance via instance.option(), and $emit for start / end / reorder.

This page shows the live demo plus the per-target compiled output. For the full API reference, recipes, and the published @rozie-ui/sortable-list-* packages (one pre-compiled, per-framework install — no Rozie toolchain required), see the SortableList showcase + package docs.

Live demo ​

SortableListDemo.rozie is the companion consumer. Grab a row by its handle (⋮⋮) and drop it elsewhere — the bound array on the right updates in real time. Add and remove rows; the list and its bound state stay in sync.

Source — SortableList.rozie ​

rozie
<!--
  SortableList.rozie — data-bound port of SortableJS.

  The "killer demo" companion to the simpler Sortable.rozie (which just
  hosts a SortableJS instance over consumer-supplied DOM). This version
  owns the list rendering and gives consumers the experience they actually
  want: pass an array, hand back a re-ordered array, render whatever you
  like per row via the default slot.

  Why this is a worthwhile demo:
    - Replaces four hand-maintained wrapper libraries (react-sortablejs,
      vuedraggable, ngx-sortablejs, svelte-sortablejs) with a single source.
    - The SortableJS-vs-framework-reconciler dance — and the hardening
      against SortableJS's fragile fallback-mode event shapes — is
      encapsulated in `useSortableJS()` (`./internal/useSortableJS`).
      Producer code below stays purely declarative.
    - Two-way binds the underlying array so consumers don't manually wire
      `onChange → setState → re-render`. Use `r-model:items="$data.list"`.

  Consumer example:

    <SortableList r-model:items="$data.todos" itemKey="id" :handle="$classSelector('grip')">
      <template #default="{ item }">
        <span class="grip">⋮⋮</span>
        <span>{{ item.text }}</span>
      </template>
    </SortableList>
-->

<rozie name="SortableList">

<types>
/** The kind of message the list speaks during keyboard reordering (a key of the `announcements` prop). */
export type AnnouncementKind =
  | 'lifted'
  | 'moved'
  | 'movedToList'
  | 'dropped'
  | 'droppedInList'
  | 'atStart'
  | 'atEnd'
  | 'notSortable'
  | 'noListBefore'
  | 'noListAfter'
  | 'cancelledReturnedToList'
  | 'cancelledReturned'
  | 'cancelledStays'
  | 'cancelledRemoved'
  | 'liftEnded'
/** What an `announcements` function receives. */
export interface AnnouncementContext {
  /** The row's screen-reader label (`labelFor`, else `item.label`, else the row's text). */
  label: string
  /** The item value. */
  item: unknown
  /** The name of the list the message is about (`listLabel`, or `list 2 of 3`). */
  list: string
  /** 1-based position of the row in `list` (kinds that have a position). */
  position?: number
  /** How many rows `list` holds (kinds that have a position). */
  total?: number
  /** The list the row came from (`movedToList` only). */
  fromList?: string
}
/** The `announcements` prop: one optional function per message kind; `null` or `''` says nothing. */
export type Announcements = Partial<Record<AnnouncementKind, (ctx: AnnouncementContext) => string | null | undefined>>
/** The payload every `start` / `end` / `reorder` / `add` / `remove` event carries, for pointer and keyboard alike. */
export interface SortablePayload {
  /** Which input made the change. */
  interaction: 'pointer' | 'keyboard'
  /** The item's data value (never an element). */
  item: unknown
  /** The row element; null when there is none (a lost lift, a removed clone copy). */
  el: HTMLElement | null
  /** The list element the row came from. */
  from: HTMLElement
  /** The list element the row went to. */
  to: HTMLElement
  /** Item-row index in `from`; -1 for `add`. */
  oldIndex: number
  /** Item-row index in `to`; -1 for `remove` and a lost lift. */
  newIndex: number
  /** Pointer only: the raw SortableJS event. */
  originalEvent?: unknown
}
/** Which element drives keyboard reordering (the `keyboardTrigger` prop). */
export type SortableKeyboardTrigger = 'row' | 'handle'
/** Which arrow keys move a lifted row within the list (the `orientation` prop). */
export type SortableOrientation = 'vertical' | 'horizontal'
</types>

<emits>
{
  reorder: { payload: 'SortablePayload' },
  add: { payload: 'SortablePayload' },
  remove: { payload: 'SortablePayload' },
  start: { payload: 'SortablePayload' },
  end: { payload: 'SortablePayload' },
}
</emits>

<props>
{
  items: {
    type: Array,
    default: () => [],
    model: true,
    docs: {
      description:
        'The bound items array. The sole `model: true` prop — two-way bind it (`r-model:items` / `v-model:items` / `bind:items` / `[(items)]`) and SortableList writes the re-ordered array back whenever a drag, cross-list move, or keyboard reorder commits, with no manual `onChange → setState` wiring.',
      example: '<SortableList r-model:items="$data.todos" itemKey="id" />',
    },
  },
  // String property name OR a (item, index) => key function for the per-row key.
  // With neither, id-less object items get a stable synthetic key via an internal
  // WeakMap (survives reorder); primitive items fall back to index.
  itemKey: {
    type: [String, Function],
    default: null,
    docs: {
      description:
        'The per-row key the framework reconciler tracks each item by across a reorder — either a property name (e.g. `itemKey="id"` reads `item.id`) or an `(item, index) => key` function. With neither, id-less object items get a stable synthetic key via an internal `WeakMap` (survives reorder by object identity); primitive items fall back to index — pass a function for reorderable duplicate primitives.',
    },
  },
  handle: {
    type: String,
    default: null,
    docs: {
      description:
        'CSS selector identifying the per-row drag handle, so a drag starts only from that element rather than anywhere in the row. Authored class names render literally on every target (React included), so a plain `.grip` works; `$classSelector(\'grip\')` is an optional, typo-checked way to author it. `options.handle` and `option(\'handle\', v)` win over this prop, for the keyboard (`keyboardTrigger: \'handle\'`) as for the mouse.',
    },
  },
  group: {
    type: String,
    default: null,
    docs: {
      description:
        'SortableJS group name enabling cross-list drag — two lists sharing a `group` accept items between each other (the source fires `remove`, the destination fires `add`). Set `cloneable: true` to flip a string group into clone-mode. Lists that share a `group` also exchange rows by keyboard: Shift+arrow while a row is lifted hops it to the previous or next list of the same group (in source order), subject to the same pull/put rules as a mouse drag. `options.group` takes precedence over this prop, for keyboard hops as for drags. Function-valued `pull`/`put` cannot be evaluated without a drag, so those lists are unreachable by keyboard. Set `itemKey` on grouped lists.',
    },
  },
  animation: {
    type: Number,
    default: 150,
    docs: {
      description:
        'Reorder animation duration in milliseconds. `0` disables the animation. Reapplied live via `instance.option(\'animation\', v)` (no remount). `options.animation`, and a runtime `option(\'animation\', v)`, win over this prop.',
    },
  },
  disabled: {
    type: Boolean,
    default: false,
    docs: {
      description:
        'Temporarily disable dragging without unmounting — reapplied live via `instance.option(\'disabled\', v)` (no remount). Also suppresses keyboard reordering: a disabled list is not sortable by any input, so rows lose their `tabindex` and the keydown handler no-ops. Turning it on while a row is lifted ends the lift where the row is (`Lift ended`, and `end` fires); `options.disabled` and `option(\'disabled\', v)` do the same.',
    },
  },
  // Keyboard reordering (Space lift / Arrow move / Esc cancel / Enter drop) is
  // on by default. Set `disableKeyboard: true` to remove it entirely — rows lose
  // their tabindex (so they drop out of the tab order) and onRowKeyDown no-ops.
  // `disabled` ALSO suppresses keyboard reordering: a disabled list is not
  // sortable by ANY input, so keyboard access is gated on `!disabled && !disableKeyboard`.
  disableKeyboard: {
    type: Boolean,
    default: false,
    docs: {
      description:
        'Opt out of keyboard reordering (Space lift / Arrow move / Shift+Arrow hop between lists / Esc cancel / Enter drop) while leaving pointer drag enabled. Rows drop out of the tab order (no `tabindex`) and the keydown handler no-ops. Keyboard access is gated on `!disabled && !disableKeyboard`. Turning it on while a row is lifted ends the lift where the row is.',
    },
  },
  // Which element drives keyboard reordering. 'row' (default) keeps rows as tab
  // stops with the keys read off the focused row. 'handle' removes the rows from
  // the tab order and reads the keys ONLY from the consumer's handle element
  // (the `handle` selector), so rows holding inputs stay typeable and the page
  // gets one tab stop per row instead of two. 'handle' with no `handle` selector
  // turns keyboard reordering off (and warns) rather than silently falling back.
  keyboardTrigger: {
    type: SortableKeyboardTrigger,
    default: 'row',
    docs: {
      description:
        'Which element drives keyboard reordering. `\'row\'` (default): rows are tab stops and the keys on the focused row drive reordering. `\'handle\'`: rows are NOT tab stops, and only keys pressed inside the element matched by `handle` (inside that row) drive the same Space/Enter lift-drop, Arrow move, Shift+Arrow hop and Escape cancel flow; handled keys call preventDefault so a handle `<button>`\'s click does not fire. The consumer owns the handle markup (recommended: a `<button>` with its own aria-label such as "Reorder Hero banner") and the component adds no tabindex or role to slot content. `\'handle\'` without `handle` turns keyboard reordering off and logs a console warning. `disabled`/`disableKeyboard` still apply. Typed as `SortableKeyboardTrigger` (`\'row\' | \'handle\'`); at runtime any value other than `\'handle\'` behaves as `\'row\'`.',
    },
  },
  options: {
    type: Object,
    default: () => ({}),
    docs: {
      description:
        'Verbatim SortableJS options pass-through for anything not covered by the named props. The named props win on key conflict but `options` lands AFTER them in the merge so consumers can override defaults; handler keys (`onStart`, `onEnd`, `onUpdate`, `onAdd`, `onRemove`, `onClone`) are stripped — the helper owns those paths. Runtime-updatable: when `options` changes, each key whose value changed is reapplied via `instance.option(key, v)` (no remount), so mouse and keyboard obey the same values; a key you drop goes back to its named prop (or, for `sort` and `draggable`, the component default), and any other dropped key keeps its last value until you set it. `forceFallback` is still read only at construction.',
    },
  },
  labelFor: {
    type: Function,
    default: null,
    docs: {
      description:
        'Optional `(item, idx) => string` returning the screen-reader label for the aria-live announcer during keyboard drag. Defaults to `item.label`; without a `label` field, the row\'s text (whitespace collapsed, without nested lists or hidden content), else `String(item)` for a primitive, else `item {position}`.',
    },
  },
  // Runtime-updatable SortableJS pass-through props (forwarded via the
  // inline options literal in $onMount + reapplied through $watch +
  // instance.option(name, v) on change).
  ghostClass: {
    type: String,
    default: null,
    docs: {
      description:
        'Class name applied to the drop-placeholder (ghost) element while dragging. Forwarded live via `instance.option`, so toggling it at runtime takes effect without a remount.',
    },
  },
  chosenClass: {
    type: String,
    default: null,
    docs: {
      description:
        'Class name applied to the currently-chosen item while dragging. Forwarded live via `instance.option` (no remount needed to change it).',
    },
  },
  dragClass: {
    type: String,
    default: null,
    docs: {
      description:
        'Class name applied to the dragging element. Only takes effect in fallback mode (`forceFallback: true`). Forwarded live via `instance.option`.',
    },
  },
  filter: {
    type: String,
    default: null,
    docs: {
      description:
        'CSS selector that prevents drag initiation on matching rows (locked items). SortableJS checks it at `mousedown`/`touchstart` and aborts the drag if it matches. The keyboard honours it too: a row that matches (the row element, or its slot root: the row template\'s single element when nothing else sits beside it) cannot be lifted with Space/Enter; any other matching control (a `.js-remove` button, an `input`) blocks only presses on itself. `options.filter` (which may also be a SortableJS filter function) takes precedence. A `data-*` attribute selector (e.g. `[data-locked]`) is the most robust choice across all targets.',
    },
  },
  easing: {
    type: String,
    default: null,
    docs: {
      description:
        'CSS easing function for the reorder animation (e.g. `\'ease-in\'`, `\'cubic-bezier(0.4, 0, 0.2, 1)\'`). Runtime-updatable.',
    },
  },
  // forceFallback is the ONE remaining construction-time-only SortableJS
  // knob — changing it at runtime requires destroying and recreating the
  // SortableJS instance. The SortableListShowcaseDemo bridges this by
  // re-keying its <SortableList> instance on it; consumers wanting a
  // runtime update must do the same. `swapThreshold`/`cloneable` (declared
  // just below) are NOT construction-time — both are live-reconciled via
  // the $watch → instance.option() reconcile block further down.
  forceFallback: {
    type: Boolean,
    default: false,
    docs: {
      description:
        'Force SortableJS\'s mouse-event drag path over HTML5 DnD — useful for touch devices, consistent cross-browser behavior, and synthetic test drivers (and `dragClass` only applies in this mode). **Construction-time only**: SortableJS reads it once at construction, so re-key the `<SortableList>` to toggle it at runtime.',
    },
  },
  swapThreshold: {
    type: Number,
    default: 1,
    docs: {
      description:
        'SortableJS swap threshold (0..1) — a lower value makes rows swap earlier as the dragged item overlaps a neighbor. Reapplied live via `instance.option(\'swapThreshold\', v)` — SortableJS reads it on every dragover, so no remount is needed.',
    },
  },
  // High-level prop that REPLACES a string `group` with the SortableJS
  // clone-mode object form `{ name, pull: 'clone', put: false }`. When
  // `cloneable: true` AND `$props.group` is null, the group is left
  // untouched (a `cloneable` flag without a `group` name is not
  // meaningful — see docs/guide/sortable-list.md).
  cloneable: {
    type: Boolean,
    default: false,
    docs: {
      description:
        'High-level prop that REPLACES a string `group` with SortableJS\'s `{ name, pull: \'clone\', put: false }` clone-mode object form — the source deposits a COPY onto the destination and keeps its own array unchanged, and takes nothing back: no row can be dropped or keyboard-hopped into it (the palette → canvas pattern). With `group: null` it is a no-op (a clone-mode list with no group name has no peer to clone into). Reapplied live — toggling `cloneable` (or changing `group`) recomputes the clone-mode shape and reapplies it via `instance.option(\'group\', …)`, no remount.',
    },
  },
  // Class hooks — extra class(es) merged onto the list container and every
  // item row. Accept String | Array | Object (the cross-target rozieClass
  // normalizer shipped in 260620-kby); bound DIRECTLY as an array/object
  // :class so the base rozie-sortable-list / rozie-sortable-item classes are
  // preserved and the default '' adds no stray/trailing class on any target.
  // itemClass ALSO accepts a (item, index) => class function for per-row classes.
  listClass: {
    type: [String, Array, Object],
    default: '',
    docs: {
      description:
        'Extra class(es) merged onto the list container (the SortableJS root) alongside the base `rozie-sortable-list` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding), normalized identically across all six targets — the hook for bridging a CSS framework (`.list-group`) or a flex/grid parent onto the component.',
    },
  },
  itemClass: {
    type: [String, Array, Object, Function],
    default: '',
    docs: {
      description:
        'Extra class(es) merged onto every item row alongside the base `rozie-sortable-item` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding) applied uniformly, OR an `(item, index) => class` function for per-row classes evaluated at render time. Normalized identically across all six targets.',
    },
  },
  // Per-row inline style applied to the .rozie-sortable-item wrapper. Accepts a
  // string, a flat style object (Record<string, string | number>), or a
  // (item, index) => string | object function for per-row styling. Bound as a
  // dynamic :style, so each target normalizes it (React/Solid parseInlineStyle,
  // Lit/Svelte rozieStyle [260620-rta], Vue/Angular native). Because it lands on
  // the wrapper — the direct child of the list container — it can drive CSS-grid
  // placement (grid-column / grid-row / align-self) when the consumer sets
  // display:grid via listClass. null / empty → no style attribute on any target.
  // Keyboard-move props (keyboard moves between lists, 2026-11).
  listLabel: {
    type: String,
    default: null,
    docs: {
      description:
        'The list\'s human name, such as `"Top sidebar"`. Sets `aria-label` on the list container (`role="list"`) and names the list in keyboard announcements when a row moves between lists (`Moved Hero banner to Top sidebar, position 1 of 4`, `Dropped Hero banner in Top sidebar at position 3 of 4`, `No list after Top sidebar`). Pass the same words as the zone\'s visible heading. With no label, announcements fall back to a neutral `list 2 of 3`, counting the mounted lists of the same group in hop (source) order.',
    },
  },
  orientation: {
    type: SortableOrientation,
    default: 'vertical',
    docs: {
      description:
        'Which arrow keys move a lifted row within the list: `\'vertical\'` (default) uses ↑/↓, `\'horizontal\'` uses ←/→. A horizontal list\'s default spoken instructions say "Use the left and right arrow keys to move" (`role="list"` has no `aria-orientation`). Typed as `SortableOrientation` (`\'vertical\' | \'horizontal\'`).',
    },
  },
  pageStep: {
    type: Number,
    default: 5,
    docs: {
      description:
        'How many positions Page Up / Page Down move a lifted row. The move stops at the first or last position when fewer rows remain.',
    },
  },
  keyboardInstructions: {
    type: String,
    default: null,
    docs: {
      description:
        'Replaces the spoken keyboard instructions. The text sits in a hidden element referenced by `aria-describedby` from each tabbable row (row mode) or from the consumer\'s handle via the `instructionsId` slot prop (handle mode). Default: "Press Space or Enter to pick up, and again to drop. Use the up and down arrow keys to move, Home and End to jump to the start or end, Page Up and Page Down to move several places, and Escape to cancel." (with `orientation: \'horizontal\'`, "the left and right arrow keys"; a `sort: false` list says only "Press Space or Enter to pick up, and again to drop. Press Escape to cancel."). When another mounted list could take this list\'s rows (by the group rules of `group`, `options.group` or `option(\'group\', v)`), the default adds "Hold Shift with an arrow key to move to another list." (updated as lists mount, unmount or change group).',
    },
  },
  announcements: {
    type: Announcements,
    default: null,
    docs: {
      description:
        'Rewords or translates what the list says during keyboard reordering. An object of optional functions keyed by message kind (`lifted`, `moved`, `movedToList`, `dropped`, `droppedInList`, `atStart`, `atEnd`, `notSortable`, `noListBefore`, `noListAfter`, `cancelledReturnedToList`, `cancelledReturned`, `cancelledStays`, `cancelledRemoved`, `liftEnded`). Each receives a context (`label`, `item`, `list`, and for kinds with a position `position` (1-based) and `total`; `movedToList` also `fromList`) and returns the text to speak; `null` or `\'\'` says nothing. Kinds without a function keep the default English text (see "Announcements"). Define the object in your script and bind it (Angular templates reject inline arrow functions), e.g. `const announcements = { moved: ({ label, position, total }) => label + \' → \' + position + \'/\' + total }`. Typed as `Announcements`, exported with `AnnouncementKind` and `AnnouncementContext`.',
      example: '<SortableList r-model:items="$data.todos" :announcements="announcements" />',
    },
  },
  itemStyle: {
    type: [String, Object, Function],
    default: null,
    docs: {
      description:
        'Per-row inline style applied to the `.rozie-sortable-item` wrapper. Accepts a CSS `String`, a flat style object (`Record<string, string | number>`), or an `(item, index) => string | object` function for per-row styling. Because it lands on the wrapper — the direct child of the list container — it can drive CSS-grid placement (`grid-column` / `grid-row` / `align-self`) when `listClass` sets `display: grid`. Normalized per target; `null` / empty drops the attribute.',
    },
  },
}
</props>

<data>
{
  liftedIndex: null,
  ariaLiveText: '',
  // Id of the hidden spoken-instructions element. Assigned in $onMount, not
  // during render: it comes from a page-global counter, and a server counts
  // differently from the browser, so a render-time id would not match on
  // hydration. Until mount, no `id` / `aria-describedby` is rendered and the
  // `instructionsId` slot prop is null.
  instructionsId: null,
  // SortableJS options set at runtime (the `disabled` / `filter` watchers and
  // the imperative `option(name, value)`), for the ones the keyboard honours.
  // A key present here is what SortableJS runs with now.
  optionOverrides: {},
  // Whether another mounted list could take a row hopped out of this one (by
  // group rules): only then do the default instructions mention Shift.
  hasHopPeer: false,
}
</data>

<script lang="ts">
import { ROW_DRAGGABLE, orderByKeys, reapplyOptions, useSortableJS } from './internal/useSortableJS'
import { afterFlush, canHop, getKeyboardRegistry, isRenderable, nextInstructionsId, rowLiftable } from './internal/keyboardRegistry'
import { announcementText, defaultInstructions, fallbackLabel } from './internal/announcements'

let instance = null
// The `options` object SortableJS was last given (see the `options` watcher).
let appliedOptions = null

// Keyboard lift state lives in the shared registry (one active keyboard lift
// per page, so a later task can hand a lifted row between lists).
// `$data.liftedIndex` is only its mirror, for the lifted-row styling.
const registry = getKeyboardRegistry()
// This list's registry entry (a ListEntry), built and registered in $onMount.
let entry = null
let unregisterEntry = null
// Removes the listeners that keep SortableJS's own DOM events inside the list.
let unhookNativeEvents = null
// Removes the document keydown listener that catches keys lost to <body>.
let unhookStrayKeys = null

// SortableJS also dispatches its events as BUBBLING native DOM events
// (`start`, `end`, `add`, `remove`, `change`, …) on the list element, before
// it calls the option callbacks. An output binding on the component host
// (Angular's `(start)` / `(end)` / `(add)` / `(remove)`, a Lit listener) also
// catches a native DOM event of the same name, so a consumer would get the raw
// SortableJS event as an extra event. The component re-emits the committed
// events itself, so stop the raw ones at the list element (only events
// dispatched ON the list — an `<input>`'s own `change` is untouched).
const SORTABLE_DOM_EVENTS = ['choose', 'unchoose', 'start', 'end', 'add', 'update', 'sort', 'remove', 'filter', 'clone', 'change', 'select', 'deselect']

// role="list" takes no aria-orientation, so a horizontal list says which
// arrow keys move in its instructions instead. A `sort: false` list leaves out
// the move sentence, and a list whose rows another mounted list could take
// (by the group SortableJS runs with, `options.group` included) says how to
// hop.
const instructionsText = () => {
  if ($props.keyboardInstructions != null) return $props.keyboardInstructions
  return defaultInstructions({
    horizontal: $props.orientation === 'horizontal',
    sortable: liveOption('sort', true) !== false,
    grouped: effectiveGroup() != null && $data.hasHopPeer,
  })
}

// Instance-scoped synthetic-id store for id-less object items. Keyed by object
// IDENTITY, so the same object keeps its synthetic id across a reorder (the
// framework reconciler then rebinds the row component instance to its ORIGINAL
// item, not its slot position — the data-corruption fix).
//
// Phase 73 item #11-b removed the former "fold the WeakMap + counter into ONE
// member-mutated object const" workaround: `hoistModuleLet`'s reachability
// walk now also roots at helpers called ONLY from a template expression
// (`keyFor` is called from `:key`/`:data-id`, never from a hook), so the bare
// `let __rowKeySeq = 0` below hoists to a `useRef` on React exactly like the
// hook-reached case — no more per-render reset. Verified in codegen.
const __rowKeyMap = new WeakMap()
let __rowKeySeq = 0

// 4-tier per-row key precedence. Its return feeds BOTH :key and :data-id.
const keyFor = (item, index) => {
  // (a) function itemKey: consumer-supplied (item, index) => key.
  if (typeof $props.itemKey === 'function') {
    return $props.itemKey(item, index)
  }
  // (b) string itemKey: a property name on a non-null object item.
  if (
    typeof $props.itemKey === 'string' &&
    item !== null &&
    typeof item === 'object' &&
    item[$props.itemKey] != null
  ) {
    return item[$props.itemKey]
  }
  // (c) id-less object (or function) item: assign-on-first-sight WeakMap
  //     synthetic id. Survives reorder because it is keyed by object identity.
  if ((item !== null && typeof item === 'object') || typeof item === 'function') {
    if (!__rowKeyMap.has(item)) {
      __rowKeyMap.set(item, '__rk' + __rowKeySeq++)
    }
    return __rowKeyMap.get(item)
  }
  // (d) primitive item: fall back to index. NOTE: duplicate primitives are
  //     unsafe to reorder this way — pass a function itemKey for those.
  return index
}

// Resolve the SortableJS `group` option: `cloneable` is a high-level Rozie
// prop that REPLACES a string `group` with SortableJS's
// `{ name, pull: 'clone', put: false }` clone-mode object form (a palette
// takes nothing back, by mouse or keyboard). When
// `cloneable:false`, pass `$props.group` through verbatim. When
// `cloneable:true` AND `$props.group` is null, leave it null — a clone-mode
// list without a group name is not meaningful (no peer list can join the
// cross-list flow). Shared by $onMount construction AND the group/cloneable
// $watch reconcile below — single source of truth, no duplicated ternary.
const resolveGroup = () => $props.cloneable && typeof $props.group === 'string'
  ? { name: $props.group, pull: 'clone' as const, put: false as const }
  : $props.group ?? undefined

// The group SortableJS actually runs with: a runtime `option('group', v)`,
// else `options.group` (it lands after the named props in the merge), else
// the `group` / `cloneable` props. Keyboard hops follow the same rules as the
// mouse, so they read this one.
const effectiveGroup = () => {
  const ov: any = $data.optionOverrides
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, 'group')) return ov.group
  const o: any = $props.options
  return o != null && o.group != null ? o.group : resolveGroup()
}

// Resolve itemClass for a row: a static value (string | array | object) OR a
// per-row (item, index) => class function. The result is fed into the :class
// array and normalized by each target's class path (rozieClass / clsx / native).
const itemClassFor = (item, index) => {
  const v = $props.itemClass
  return typeof v === 'function' ? v(item, index) : v
}

// Resolve itemStyle for a row: a static value (string | object) OR a per-row
// (item, index) => style function. Returns string | object | null; the dynamic
// :style binding normalizes it per target. null / empty → attribute dropped.
const itemStyleFor = (item, index) => {
  const s = typeof $props.itemStyle === 'function' ? $props.itemStyle(item, index) : $props.itemStyle
  return s == null || s === '' ? null : s
}

// Read the display label for an item — used by the aria-live announcer.
// Phase 16 R7 / D-08: $props.labelFor reads as `null` on all 6 targets when
// the consumer omits it (Plan 16-01 prop-default coercion fix); the check is
// a plain null compare — NO runtime callable-type coercion. Without
// `labelFor` or a `label` field, the row's text (`row`), else `String(item)`
// for a primitive, else `item {position}`.
const labelOf = (item, idx, row: HTMLElement | null = null) => {
  if ($props.labelFor !== null) return $props.labelFor(item, idx)
  if (item !== null && typeof item === 'object' && item.label != null) return item.label
  return fallbackLabel(item, idx, row)
}

// The text this list's live region showed last (see the registry entry's
// `announce`).
let lastSpoken = ''

// Keyboard handler (Phase 16 R7): Space/Enter lift and drop; while lifted,
// ArrowUp/ArrowDown (ArrowLeft/ArrowRight when horizontal), Home/End and
// PageUp/PageDown move the row, and Escape returns it to where it was lifted
// from. The lift itself lives in the shared keyboard registry. After
// any array-reorder write, refocusRow() keeps focus on the moved row (or its
// handle) on all six targets.
//
// Note: `index` is passed directly as a number. Plan 16-02 (Solid call-arg
// accessor unwrap) ensures Solid's <For> alias unwraps to `index()` at the
// call site — no runtime callable-type coercion needed in user source.
// Keyboard reordering is available only when the list is not disabled AND the
// `disableKeyboard` opt-out is off. Drives BOTH the row tabindex (rows are
// focusable only when reorderable) and the onRowKeyDown guard below. Reads
// straight off $props so the tabindex binding re-evaluates reactively when
// `disabled`/`disableKeyboard` toggle at runtime.
//
// The keyboard follows the SortableJS options the mouse obeys: `disabled`
// (the prop, `options.disabled`, or `option('disabled', v)`), `filter` and
// `draggable` (which rows lift, see rowLiftable) and `sort: false` (no moves
// within the list). `liveOption` reads the value SortableJS runs with: one set
// at runtime, else `options`, else the named prop.
const KEYBOARD_OPTIONS = ['disabled', 'filter', 'draggable', 'sort']
const liveOption = (name, fallback) => {
  const ov: any = $data.optionOverrides
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, name)) return ov[name]
  const o: any = $props.options
  if (o != null && o[name] !== undefined) return o[name]
  return fallback
}
const setOverride = (name, value) => {
  $data.optionOverrides = { ...$data.optionOverrides, [name]: value }
}
const clearOverride = (name) => {
  const ov: any = $data.optionOverrides
  if (ov == null || !Object.prototype.hasOwnProperty.call(ov, name)) return
  const next = { ...ov }
  delete next[name]
  $data.optionOverrides = next
}
// Options whose runtime value (`option(name, v)`) is remembered, so a later
// change of the matching prop doesn't overwrite it: the keyboard ones, plus
// `animation`, `handle` and `group` (runtime override → `options` → prop).
const TRACKED_OPTIONS = [...KEYBOARD_OPTIONS, 'animation', 'handle', 'group']
const keyboardEnabled = () => !$props.disableKeyboard && !liveOption('disabled', $props.disabled)
// The handle selector SortableJS runs with (`option('handle', v)`, else
// `options.handle`, else the `handle` prop): the keyboard reads the same one.
const handleSelector = () => liveOption('handle', $props.handle)

// keyboardTrigger='handle' mode: rows are not tab stops and the keys are read
// from the consumer's handle element instead. Any other value is 'row' mode.
const handleMode = () => $props.keyboardTrigger === 'handle'
// Rows are tab stops only in row mode (and only while keyboard is enabled).
const rowTabbable = () => keyboardEnabled() && !handleMode()

// One-time-per-change dev warning: handle mode needs a handle selector. Without
// one the keyboard is OFF (see the onRowKeyDown gate) — never a silent fallback
// to row mode, which would re-introduce the tab stops the consumer opted out of.
const warnIfHandleMissing = () => {
  if (handleMode() && handleSelector() == null) {
    console.warn('[rozie-sortable-list] keyboardTrigger is "handle" but no handle selector is set, so keyboard reordering is off. Pass a handle selector (e.g. handle=".grip") or use keyboardTrigger "row".')
  }
}

// True only when a keydown originated inside a `handle` element that belongs to
// THIS row. Walks the COMPOSED ancestor chain from the event target up to (but
// excluding) the row (currentTarget): assignedSlot -> parentNode -> shadow host.
// Plain closest()/contains() stop at a shadow boundary, and Lit renders a Rozie
// consumer's slot content inside the SortableList shadow root while plain-HTML
// consumers project light-DOM nodes through a <slot>. composedPath() is not
// used because React's synthetic event does not expose it. Another
// .rozie-sortable-item met first means the key came from a NESTED list's row,
// which must not reorder this (outer) list.
const isHandleKeyOrigin = ($event) => {
  const sel = handleSelector()
  if (sel == null) return false
  const row = $event.currentTarget
  let n: any = $event.target
  while (n && n !== row) {
    if (n.nodeType === 1) {
      if (n.matches(sel)) {
        // Matched a handle: it counts only if this row is reachable from here
        // without crossing a different sortable item.
        let m: any = n.assignedSlot ?? n.parentNode ?? n.host
        while (m && m !== row) {
          if (m.nodeType === 1 && m.classList.contains('rozie-sortable-item')) return false
          m = m.assignedSlot ?? m.parentNode ?? m.host
        }
        return m === row
      }
      if (n.classList.contains('rozie-sortable-item')) return false
    }
    n = n.assignedSlot ?? n.parentNode ?? n.host
  }
  return false
}

// Put focus back on the MOVED row (row mode) or its handle (handle mode) after
// a reorder write. Looks the row up by KEY (data-id), not by index, so it finds
// the moved row whether this runs before the framework commit (the row element
// is the same one) or after it (Svelte/Solid/Lit re-create the DOM) — and it is
// correct for index-keyed primitive lists too. Direct children of the list
// container only: that skips nested-list rows and the header/footer slot
// content.
//
// Two passes. (1) A microtask covers targets that commit synchronously or in an
// earlier microtask (Vue's scheduler flush is queued by the model write, before
// this one). (2) A timer + rAF "heal" pass covers targets whose DOM commit is
// scheduled AFTER the key handler returns (Angular): the commit can MOVE the
// focused row, and moving a focused node blurs it, so a Home/End/Escape jump or
// a rapid Space/Arrow/Arrow/Space burst would otherwise end with focus on
// <body>. The heal pass never steals: it acts only when focus has been lost to
// <body>. (`$restoreFocus(selector, index)` is not enough here: it is a no-op on
// Vue/Angular, where a long jump moves the focused row itself, and it looks the
// row up by index, which can land on a neighbour on Lit.) The $refs read
// happens here, synchronously, inside an event handler — which is safe.
const refocusRow = (item, idx) => {
  const listEl = $refs.listEl
  const sel = handleSelector()
  const useHandle = handleMode()
  const key = String(keyFor(item, idx))
  // While this refocus is outstanding, a key that falls to <body> belongs to
  // the lift (see onStrayKey). Cleared once the row has focus again, or by a
  // pointer press anywhere.
  const pending = registry.lift
  if (pending != null) pending.focusPending = true
  const focusIt = (onlyIfLost) => {
    if (!listEl) return
    if (useHandle && sel == null) return
    if (onlyIfLost && document.activeElement && document.activeElement !== document.body) return
    for (const row of Array.from(listEl.children) as any[]) {
      if (row.getAttribute('data-id') === key) {
        const target = useHandle ? row.querySelector(sel) : row
        if (target && typeof target.focus === 'function') {
          target.focus()
          const l = registry.lift
          if (l != null && l === pending && l.key === key) {
            l.focusPending = false
            // This row is the lifted row element now (see the items watcher).
            l.liftedRowEl = row
          }
        }
        return
      }
    }
  }
  queueMicrotask(() => focusIt(false))
  setTimeout(() => focusIt(true), 0)
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => focusIt(true))
}

// `el` in an event payload: the row element while it is in the page, else
// null (a row that left with an unmounted list is no row of any list).
const liveEl = (el) => (el != null && el.isConnected ? el : null)

// The row element carrying `data-id === key` among a list element's direct
// children (skips nested-list rows and header/footer slot content).
const rowByKey = (listEl, key) => {
  if (!listEl || key == null) return null
  for (const row of Array.from(listEl.children) as any[]) {
    if (row.getAttribute('data-id') === key) return row
  }
  return null
}

// After the consumer changed the items of the list holding a lift, put focus
// on the row (or its handle) whose key is `key`, else the row nearest `index`
// (or the list itself when it has no rows left) — but only once focus has fallen to <body> (the focused row's element went
// away: the lift was lost, or a framework that keys rows by object identity
// re-created the lifted row). Never steals focus from anywhere else. Same
// three passes as refocusRow, for targets that commit late.
const focusNearRow = (index: number, key: string | null = null) => {
  const listEl = $refs.listEl
  const sel = handleSelector()
  const useHandle = handleMode()
  const focusIt = () => {
    if (!listEl) return
    if (useHandle && sel == null) return
    if (document.activeElement && document.activeElement !== document.body) return
    const rows = Array.from(listEl.children).filter((r: any) => r.hasAttribute('data-id') && r.classList.contains('rozie-sortable-item')) as any[]
    if (rows.length === 0) {
      // The list is now empty: focus the list itself (out of the tab order)
      // so keyboard and screen-reader users stay where they were.
      if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1')
      listEl.focus()
      return
    }
    const row = rows.find((r) => key != null && r.getAttribute('data-id') === key) ?? rows[Math.max(0, Math.min(rows.length - 1, index))]
    const target = useHandle ? row.querySelector(sel) : row
    if (target && typeof target.focus === 'function') target.focus()
  }
  queueMicrotask(focusIt)
  setTimeout(focusIt, 0)
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(focusIt)
}

// Speak `text` from `target`'s aria-live region. The region that spoke last
// is cleared when it belongs to another list, so a message is heard once, from
// the list the row is in now, and never from a list that just lost it.
const speak = (target, text) => {
  const prev = registry.speaker
  if (prev != null && prev !== target && registry.has(prev)) prev.announce('')
  registry.speaker = target
  target.announce(text)
}

// Say announcement `kind` from `target`, in `target`'s words: its
// `announcements` function for that kind, else the default text (see
// ./internal/announcements). `index` is the row's 0-based position in
// `target`, `row` the row element its label is read from (when there is no
// `labelFor` or `label` field), and `total` how many rows `target` holds after
// the change (null for the kinds without a position). A function returning
// null or '' clears the region, so nothing is said.
const say = (target: any, kind: AnnouncementKind, item: unknown, index: number, row: HTMLElement | null, total: number | null = null, fromList: any = null) => {
  const ctx: any = { item, list: registry.listName(target) }
  // The label is read only when the text needs it (a default with `{label}`,
  // or an override that reads `label`), so `labelFor` is not called for a
  // message that doesn't name the row (`Lift ended`: the item has left).
  let label: string | null = null
  Object.defineProperty(ctx, 'label', {
    enumerable: true,
    get: () => {
      if (label === null) label = target.labelOf(item, index, row)
      return label
    },
  })
  if (total != null) {
    ctx.position = index + 1
    ctx.total = total
  }
  if (fromList != null) ctx.fromList = registry.listName(fromList)
  speak(target, target.message(kind, ctx))
}

// The lifted item is no longer in the list holding it: the consumer changed
// that list's items (or re-keyed the item), or the list is unmounting. End the
// lift without writing anything (the item is wherever the consumer's data put
// it). `end` still fires once, with `item` = the lifted value and `el: null`
// (there is no row), so keyboard `start` / `end` pair (unless the holder and the origin have both unmounted). Lost to a consumer change (not an
// unmount), the holder says `Lift ended` and, if focus fell to <body> with the
// row, focuses its row nearest where the lifted row was.
const loseLift = (unmounting = false) => {
  const lift = registry.lift
  if (!lift) return
  const h = lift.holder
  registry.lift = null
  h.setLifted(null)
  if (!unmounting) {
    say(h, 'liftEnded', lift.item, lift.index ?? lift.origin.index, lift.liftedRowEl)
    h.focusNear(lift.index ?? lift.origin.index)
  }
  const payload = {
    interaction: 'keyboard' as const,
    item: lift.item,
    el: null,
    from: lift.origin.list.el,
    to: h.el,
    oldIndex: lift.origin.index,
    newIndex: -1,
  }
  // Like every `end`, in a task after the writes, from the holder. An
  // unmounted list never emits (Angular rejects an emit from a destroyed
  // component): when the holder is unmounting, the origin list (which emitted
  // `start`) ends the lift if it is still mounted, so `start` and `end` pair;
  // if it is gone too, nothing is emitted.
  registry.deferEnd((host) => host.emit('end', payload), h, lift.origin.list)
}

// Keyboard `start` / `end` (the same payload as every other event): `item` is
// the item value, `el` its row element. `start` fires from the origin list
// (`from`), `end` from the list the row ends up in (`to`). `el` is the row in
// that list when it is rendered, else `fallbackEl` (the row element the move
// started from, before a target re-rendered). `end` is called after
// `registry.lift` is cleared, so a consumer `end` handler that writes the
// items (re-keying a clone copy) is not mistaken for a lost lift, and it is
// emitted in a task (`registry.deferEnd`), after the writes AND the re-render
// they schedule: a consumer `end` handler reads the new state on every target
// (React included, whose handler closure is the one from the latest render).
// If `to` has unmounted by then, `from` (the origin, which emitted `start`)
// emits it instead, `to` unchanged in the payload; an unmounted list never
// emits.
const keyboardStartEnd = (name, lift, from, to, oldIndex, newIndex, fallbackEl: HTMLElement | null = null) => {
  const fire = (host) => host.emit(name, {
    interaction: 'keyboard',
    item: lift ? lift.item : null,
    el: (lift && host === to ? rowByKey(host.el, lift.key) : null) ?? liveEl(fallbackEl),
    from: from.el,
    to: to.el,
    oldIndex,
    newIndex,
  })
  if (name === 'end') registry.deferEnd(fire, to, from)
  else fire(from)
}

// Move the lifted row to `toIndex` (clamped) within the list holding it.
// Works through the registry entry, so it acts on the current holder. `dir`
// is the key's direction (-1 toward the start), for when the row can't move.
const moveLiftTo = (toIndex, dir) => {
  const lift = registry.lift
  if (!lift) return
  const h = lift.holder
  const from = registry.indexOfLift()
  if (from < 0) {
    loseLift()
    return
  }
  const items = h.items()
  const to = Math.max(0, Math.min(items.length - 1, toIndex))
  // The moved row's element, read before the write (an index key changes).
  const el = h.rowEl(from)
  if (to === from) {
    // Nowhere to go: say so (the row is already at that end).
    say(h, dir < 0 ? 'atStart' : 'atEnd', items[from], from, el ?? lift.liftedRowEl, items.length)
    return
  }
  const next = [...items]
  const [moved] = next.splice(from, 1)
  next.splice(to, 0, moved)
  // Index keys (primitive items without itemKey) change with the position.
  // Update the lift BEFORE writing: a target whose watchers run synchronously
  // on the write must already see where the row is going.
  lift.key = h.keyOf(moved, to)
  lift.index = to
  h.write(next)
  h.setLifted(to)
  // Name the row that MOVED from the local `moved` item: on React/Vue/Lit the
  // items prop still holds the pre-write array here. Labels come from the
  // holder's own `labelFor`.
  say(h, 'moved', moved, to, el, items.length)
  h.focusRow(moved, to)
  h.emit('reorder', { interaction: 'keyboard', item: moved, el, from: h.el, to: h.el, oldIndex: from, newIndex: to })
}

// Hop the lifted row to the next (`dir` 1) or previous (-1) list it could
// also reach by mouse, in composed-tree source order. One hand-off: the source
// writes its items without the row, the destination writes them with it, and
// the destination becomes the holder. As with the mouse, the destination
// emits `add` first, then the source emits `remove`. A forward hop lands
// first, a backward hop lands last.
const hop = (dir) => {
  const lift = registry.lift
  if (!lift) return
  const from = lift.holder
  const i = registry.indexOfLift()
  if (i < 0) {
    loseLift()
    return
  }
  const fromItems = from.items()
  const data = fromItems[i]
  const el = from.rowEl(i)
  // Keep the lifted row element current: lists nested inside it (a grid
  // widget's columns) are never hop targets. Before a target re-renders the
  // row may not exist yet, so keep the last known element then.
  lift.liftedRowEl = el ?? lift.liftedRowEl
  const to = registry.findHopTarget(from, dir)
  if (to == null) {
    say(from, dir === 1 ? 'noListAfter' : 'noListBefore', data, i, el ?? lift.liftedRowEl)
    return
  }
  const origin = lift.origin
  const toItems = to.items()
  // A clone copy hopping back into the list it was cloned from merges with
  // its original there (that list never gave it up), rather than adding a
  // second row with the same key.
  if (lift.copy && to === origin.list) {
    let home = toItems.indexOf(data)
    if (home < 0) home = Math.max(0, Math.min(toItems.length - 1, origin.index))
    lift.holder = to
    lift.copy = false
    lift.key = to.keyOf(toItems[home], home)
    lift.item = toItems[home]
    lift.index = home
    const rest = [...fromItems]
    rest.splice(i, 1)
    from.write(rest)
    from.emit('remove', { interaction: 'keyboard', item: data, el, from: from.el, to: to.el, oldIndex: i, newIndex: -1 })
    from.setLifted(null)
    to.setLifted(home)
    say(to, 'movedToList', data, home, el, toItems.length, from)
    to.focusRow(toItems[home], home)
    return
  }
  // The first hop out of a clone source (`pull: 'clone'`) leaves the source
  // untouched and carries a copy (the same item value the mouse path
  // inserts); from then on the copy moves like any row.
  const cloneOut = canHop(from.group(), to.group()).copy && from === origin.list && !lift.copy
  const at = dir === 1 ? 0 : toItems.length
  // Update the lift BEFORE writing, so a target whose watchers run
  // synchronously on a write already sees the new holder.
  lift.holder = to
  lift.key = to.keyOf(data, at)
  lift.index = at
  lift.hopped = true
  if (cloneOut) {
    lift.copy = true
  } else {
    const rest = [...fromItems]
    rest.splice(i, 1)
    from.write(rest)
  }
  const next = [...toItems]
  next.splice(at, 0, data)
  to.write(next)
  // The destination has not rendered its new row yet: `el` is the row the
  // move started from. `add` (destination) before `remove` (source), as by
  // mouse.
  to.emit('add', { interaction: 'keyboard', item: data, el, from: from.el, to: to.el, oldIndex: -1, newIndex: at })
  if (!cloneOut) from.emit('remove', { interaction: 'keyboard', item: data, el, from: from.el, to: to.el, oldIndex: i, newIndex: -1 })
  from.setLifted(null)
  to.setLifted(at)
  say(to, 'movedToList', data, at, el, toItems.length + 1, from)
  to.focusRow(data, at)
}

// End the active keyboard lift. 'drop' leaves the row where it is ('off' too,
// announced as `Lift ended`: the holder's keyboard was turned off); 'cancel'
// returns it to the list and position it was lifted from (after hops, a
// reverse hand-off with its own `remove` / `add`; a clone copy is removed).
// Emits `end` once, from the list the row ends up in.
const endLift = (kind) => {
  const lift = registry.lift
  if (!lift) return
  const h = lift.holder
  const origin = lift.origin
  const at = registry.indexOfLift()
  if (at < 0) {
    loseLift()
    return
  }
  const items = h.items()
  const item = items[at]
  // The lifted row's element, read before any write below. Right after a hop
  // the holder may not have rendered it yet: its label is read from the
  // lifted row element then.
  const el = h.rowEl(at)
  const row = el ?? lift.liftedRowEl
  if (kind === 'drop' || kind === 'off') {
    // A row that hopped always names its list, even back in its origin. The
    // keyboard turned off mid-lift ('off') ends it where it is, too.
    if (kind === 'off') say(h, 'liftEnded', item, at, row)
    else say(h, lift.hopped ? 'droppedInList' : 'dropped', item, at, row, items.length)
    h.setLifted(null)
    registry.lift = null
    keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el)
    return
  }
  if (h !== origin.list && !registry.has(origin.list) && lift.copy) {
    // A clone copy is removed on cancel even when its source list has
    // unmounted (the source never gave its item up). Focus moves to the
    // neighbouring row, if any. The lift ends BEFORE the write: the copy is
    // leaving on purpose, and a target whose items watcher runs synchronously
    // on the write (Solid) must not take it for a lost lift (a second `end`).
    registry.lift = null
    const rest = [...items]
    rest.splice(at, 1)
    h.write(rest)
    h.emit('remove', { interaction: 'keyboard', item, el, from: h.el, to: h.el, oldIndex: at, newIndex: -1 })
    h.setLifted(null)
    say(h, 'cancelledRemoved', item, at, row)
    if (rest.length > 0) {
      const k = Math.min(at, rest.length - 1)
      h.focusRow(rest[k], k)
    }
    // The copy is gone, so there is no row: `el: null`.
    const fromEl = origin.list.el
    registry.deferEnd((host) => host.emit('end', { interaction: 'keyboard', item, el: null, from: fromEl, to: h.el, oldIndex: origin.index, newIndex: -1 }), h, origin.list)
    return
  }
  if (h !== origin.list && (!registry.has(origin.list) || !isRenderable(origin.list.el) || !origin.list.keyboardEnabled())) {
    // The origin list has unmounted, is hidden, or has its keyboard off:
    // there is nowhere to return to (focus would be stranded), so the row
    // stays where it is (the lift ends as a drop at its position).
    say(h, 'cancelledStays', item, at, row, items.length)
    h.setLifted(null)
    registry.lift = null
    keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el)
    return
  }
  if (h === origin.list) {
    const to = Math.max(0, Math.min(items.length - 1, origin.index))
    if (to !== at) {
      const next = [...items]
      next.splice(at, 1)
      next.splice(to, 0, item)
      lift.key = h.keyOf(item, to)
      h.write(next)
      h.focusRow(item, to)
      h.emit('reorder', { interaction: 'keyboard', item, el, from: h.el, to: h.el, oldIndex: at, newIndex: to })
    }
    say(h, lift.hopped ? 'cancelledReturnedToList' : 'cancelledReturned', item, to, row, items.length)
    h.setLifted(null)
    registry.lift = null
    keyboardStartEnd('end', lift, origin.list, h, origin.index, to, el)
    return
  }
  // Reverse hand-off from the current holder back to the origin list.
  const home = origin.list
  const homeItems = home.items()
  let back
  if (lift.copy) {
    // The clone source never gave its item up: drop the copy, focus the
    // original.
    back = homeItems.indexOf(item)
    if (back < 0) back = Math.max(0, Math.min(homeItems.length - 1, origin.index))
  } else {
    back = Math.min(origin.index, homeItems.length)
  }
  lift.holder = home
  lift.key = home.keyOf(item, back)
  const rest = [...items]
  rest.splice(at, 1)
  h.write(rest)
  if (!lift.copy) {
    const next = [...homeItems]
    next.splice(back, 0, item)
    home.write(next)
    // `add` (destination) before `remove` (source), as by mouse.
    home.emit('add', { interaction: 'keyboard', item, el, from: h.el, to: home.el, oldIndex: -1, newIndex: back })
  }
  h.emit('remove', { interaction: 'keyboard', item, el, from: h.el, to: home.el, oldIndex: at, newIndex: -1 })
  h.setLifted(null)
  // `home` holds the lift during its write, so a target whose items watcher
  // runs synchronously on the write (Solid) highlighted the row there: clear it.
  home.setLifted(null)
  say(home, 'cancelledReturnedToList', item, back, row, homeItems.length + (lift.copy ? 0 : 1))
  home.focusRow(lift.copy ? homeItems[back] : item, back)
  registry.lift = null
  keyboardStartEnd('end', lift, home, home, origin.index, back, lift.copy ? home.rowEl(back) : el)
}

// This list's keyboard was turned off (`disabled`, `disableKeyboard`, or
// `option('disabled', true)`): a lift it holds ends where the row is, with
// its `end`.
const endLiftIfHeld = () => {
  const lift = registry.lift
  if (lift != null && lift.holder === entry) endLift('off')
}

// In row mode the rows leave the tab order when the keyboard turns off, and a
// focused element that stops being focusable drops focus to <body>. If one of
// this list's rows still has focus (a target whose watcher runs before its DOM
// update), move it to the list itself (out of the tab order), like an emptied
// list. Once the DOM update has run, the `focusout` listener added in $onMount
// does it instead.
const keepFocusOffBody = () => {
  const listEl = entry ? entry.el : null
  if (!listEl) return
  const root: any = listEl.getRootNode()
  const a: any = root != null ? root.activeElement : null
  if (a == null || a.parentNode !== listEl || !a.classList.contains('rozie-sortable-item')) return
  if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1')
  listEl.focus()
}

const keyboardTurnedOff = () => {
  endLiftIfHeld()
  keepFocusOffBody()
}

// Lift the row at `index` of this list.
const startLift = (index) => {
  if (!entry) return
  // A previous drag's or lift's `end` that is still pending fires first, so
  // every `end` comes before the next `start`.
  registry.flushEnds()
  const item = $props.items[index]
  registry.lift = {
    holder: entry,
    key: entry.keyOf(item, index),
    item,
    copy: false,
    hopped: false,
    origin: { list: entry, index },
    liftedRowEl: entry.rowEl(index),
    index,
  }
  $data.liftedIndex = index
  say(entry, 'lifted', item, index, registry.lift.liftedRowEl, $props.items.length)
  keyboardStartEnd('start', registry.lift, entry, entry, index, index)
}

const onRowKeyDown = ($event, index) => {
  // Origin guard — must run FIRST, before the keyboardEnabled() check.
  //  - handle mode (keyboardTrigger='handle'): reorder keys apply ONLY when the
  //    keydown came from inside this row's `handle` element. A missing `handle`
  //    selector means keyboard is OFF (warned in warnIfHandleMissing).
  //  - row mode (quick 260716-ggq): reorder keys apply ONLY when the row
  //    element ITSELF is focused. A slotted interactive child (an <input>,
  //    <button>, etc. rendered into the row's default slot) bubbles its own
  //    keydown up to this handler — without this guard, Space/Enter typed into
  //    that child would be hijacked for lift/drop instead of reaching the
  //    child.
  if (handleMode()) {
    if (handleSelector() == null || !isHandleKeyOrigin($event)) return
  } else if ($event.target !== $event.currentTarget) {
    return
  }
  // Defense-in-depth: when keyboard reordering is off the rows carry no
  // tabindex and can't receive focus, but a consumer-focused row (or a
  // programmatic .focus()) must still no-op here rather than reorder.
  if (!keyboardEnabled()) return
  // While a lift exists, reorder keys in the list holding it act on it. A key
  // from ANOTHER list of the holder's group is routed to the holder only when
  // it comes from the lifted row element itself (its old row, still there
  // before the frameworks re-render after a hop; compared by element, so a
  // row of another list that shares the lifted row's key is not it) or while a refocus after a move is
  // outstanding (a fast burst). Any other row — and every row of an unrelated
  // list (another group, or none) — keeps single-list behaviour: Space/Enter
  // there drops the foreign lift and lifts its own row, other keys do nothing.
  const lift = registry.lift
  const key = $event.key
  if (lift != null) {
    const mine = groupNameOf(effectiveGroup())
    const sameGroup = mine != null && mine === groupNameOf(lift.holder.group())
    const fromLiftedRow = lift.liftedRowEl != null && $event.currentTarget === lift.liftedRowEl
    if (lift.holder === entry || (sameGroup && (fromLiftedRow || lift.focusPending === true))) {
      if (lift.holder.onKey(key, !!$event.shiftKey)) $event.preventDefault()
      return
    }
  }
  // Space (' ' on browsers; KeyboardEvent.key === ' ') OR Enter — lift. A row
  // the mouse can't drag (it matches `filter`, or not `draggable`) can't be
  // lifted either: the key is left alone (not prevented).
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    const rules = { filter: liveOption('filter', $props.filter), draggable: liveOption('draggable', undefined), sortable: instance }
    if (!rowLiftable($event.currentTarget as any, rules)) return
    $event.preventDefault()
    if (lift != null) endLift('drop')
    startLift(index)
  }
}

// The group NAME of a SortableJS group option (string or object form).
const groupNameOf = (g) => (g == null ? null : typeof g === 'string' ? g : g.name ?? null)

// A reorder key for the lift THIS list holds (routed here from any list via
// the registry entry's onKey). Returns true when the key was handled. Every
// key except Space/Enter acts only while lifted, so it never steals keys from
// fields inside a row.
const holderKey = (key, shift) => {
  const lift = registry.lift
  if (lift == null || lift.holder !== entry) return false
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    endLift('drop')
    return true
  }
  if (key === 'Escape') {
    endLift('cancel')
    return true
  }
  const horizontal = $props.orientation === 'horizontal'
  const prevKey = horizontal ? 'ArrowLeft' : 'ArrowUp'
  const nextKey = horizontal ? 'ArrowRight' : 'ArrowDown'
  if (shift && (key === nextKey || key === prevKey)) {
    // Hopping is on wherever a group is set; an ungrouped list ignores it.
    if (effectiveGroup() == null) return false
    hop(key === nextKey ? 1 : -1)
    return true
  }
  const from = registry.indexOfLift()
  if (from < 0) {
    loseLift()
    return false
  }
  // pageStep below 1 (or not a number) still moves by at least one position.
  const step = Math.max(1, Math.floor(Number($props.pageStep) || 1))
  let to = null
  if (key === nextKey) to = from + 1
  else if (key === prevKey) to = from - 1
  else if (key === 'Home') to = 0
  else if (key === 'End') to = entry.items().length - 1
  else if (key === 'PageDown') to = from + step
  else if (key === 'PageUp') to = from - step
  if (to === null) return false
  // `sort: false`: no moves within the list (as by mouse). The key is still
  // taken, so it does not scroll the page while a row is lifted, and says why
  // nothing moved.
  if (liveOption('sort', true) === false) {
    say(entry, 'notSortable', entry.items()[from], from, entry.rowEl(from) ?? lift.liftedRowEl)
    return true
  }
  moveLiftTo(to, key === prevKey || key === 'Home' || key === 'PageUp' ? -1 : 1)
  return true
}

// A key pressed while focus has fallen to <body> during a lift. A hop removes
// the focused row from one list and the destination may render (and take
// focus) only after the handler returns (Angular), so the next key of a fast
// burst can reach <body>. The list holding the lift handles it as if it had
// landed on the lifted row, then puts focus back on that row.
//
// Only while a refocus of ours is outstanding (`focusPending`): focus that left
// the lifted row for any other reason (the user clicked elsewhere or tabbed
// away) keeps today's behaviour, and those keys are not ours. Modified keys
// and keys someone already handled are never taken.
const onStrayKey = (ev) => {
  const lift = registry.lift
  if (lift == null || lift.holder !== entry || !lift.focusPending) return
  if (ev.defaultPrevented || ev.ctrlKey || ev.metaKey || ev.altKey) return
  const t = ev.target
  if (t !== document.body && t !== document.documentElement) return
  const item = lift.item
  const at = registry.indexOfLift()
  if (!holderKey(ev.key, !!ev.shiftKey)) return
  ev.preventDefault()
  const now = registry.lift
  if (now != null) now.holder.focusRow(now.item, registry.indexOfLift())
  else if (at >= 0) entry.focusRow(item, at)
}

// SortableJS wiring lives in `useSortableJS()` (./internal/useSortableJS).
// The helper owns the SortableJS-vs-reconciler dance — DOM-restore hardening
// against fragile-event paths, identity-based item lookup over fragile
// `e.oldIndex`, and the single-onEnd disambiguation that collapses
// onUpdate / onAdd / onRemove into one handler.
//
// What stays here is purely declarative: which array to read, what to write
// back, what to emit, and how to bridge `afterCommit` to the Lit-only
// `$reconcileAfterDomMutation()` sigil.
$onMount(() => {
  // Kept across a Lit element's disconnect and reconnect (mount runs again).
  if ($data.instructionsId == null) $data.instructionsId = nextInstructionsId()
  warnIfHandleMissing()
  // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
  // when the options object below references it.
  const sortable = useSortableJS($refs.listEl, {
    items: () => $props.items,
    onCommit: (next) => { $model.items = next },
    options: {
      animation:     $props.animation,
      disabled:      $props.disabled,
      group:         resolveGroup(),
      handle:        $props.handle,
      ghostClass:    $props.ghostClass,
      chosenClass:   $props.chosenClass,
      dragClass:     $props.dragClass,
      filter:        $props.filter,
      forceFallback: $props.forceFallback,
      swapThreshold: $props.swapThreshold,
      easing:        $props.easing,
      ...$props.options,
    },
    // Lit lit-html `repeat` directive caches its part array by sentinel-
    // comment node identity; SortableJS's physical DOM mutation desyncs
    // that cache. The sigil lowers to `__rozieReconcileAfterDomMutation(this)`
    // on Lit (real call) and `void 0` on the other 5 targets (no-op).
    afterCommit: () => $reconcileAfterDomMutation(),
    // Every pointer event carries the same payload as the keyboard ones, with
    // item-row indices and the raw SortableJS event as `originalEvent`.
    onChange: (c) => {
      const payload = { interaction: 'pointer' as const, item: c.item, el: c.el, from: c.from, to: c.to, oldIndex: c.oldIndex, newIndex: c.newIndex, originalEvent: c.event }
      if (c.kind === 'reorder') $emit('reorder', payload)
      else if (c.kind === 'add') $emit('add', payload)
      else if (c.kind === 'remove') $emit('remove', payload)
    },
    onStart: (d) => {
      // A pointer drag ends any active keyboard lift first.
      if (registry.lift != null) endLift('drop')
      // That lift's `end` (pending until a task) comes before this `start`.
      registry.flushEnds()
      $emit('start', { interaction: 'pointer', item: d.item, el: d.el, from: d.from, to: d.to, oldIndex: d.oldIndex, newIndex: d.newIndex, originalEvent: d.event })
    },
    // `end` comes from the list the row ended up in: the destination when it
    // is a SortableList, else (dropped outside, or into a SortableJS list
    // that isn't one of ours) this source list. It goes through the
    // registry's `deferEnd`, like a keyboard `end`: it fires in a task after
    // every list involved has written its items and the re-render those
    // writes scheduled, and before the next drag's or lift's `start`. An
    // unmounted list never emits: if the destination has unmounted by then
    // (in its own `add` handler, say), this list (the origin, which emitted
    // `start`) emits it, `to` still the destination; if both are gone,
    // nothing is emitted.
    scheduleEnd: (d) => {
      const dest = registry.entryFor(d.to)
      const destGone = dest == null && d.to !== d.from && registry.wasList(d.to)
      registry.deferEnd((host) => {
        const row = d.item === undefined || host.el !== d.to ? null : rowByKey(d.to, host.keyOf(d.item, d.newIndex))
        host.emit('end', { interaction: 'pointer', item: d.item, el: row ?? liveEl(d.el), from: d.from, to: d.to, oldIndex: d.oldIndex, newIndex: d.newIndex, originalEvent: d.event })
      }, destGone ? null : dest ?? entry, entry)
    },
  })
  instance = sortable.instance
  appliedOptions = $props.options
  // Runtime `option(name, v)` values this list remembers (Lit keeps them when
  // the element is moved in the DOM and mounts again) apply to the new
  // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
  // first mount.
  const remembered: any = $data.optionOverrides
  if (remembered != null) {
    for (const name of Object.keys(remembered)) instance.option(name, remembered[name])
  }

  const listEl = $refs.listEl
  const stopNative = (ev) => { if (ev.target === listEl) ev.stopPropagation() }
  for (const name of SORTABLE_DOM_EVENTS) listEl?.addEventListener(name, stopNative)
  // A focused row that stops being focusable (its tabindex goes when the
  // keyboard turns off) is blurred at once, during the framework's DOM
  // update, with focus going nowhere (`relatedTarget` null): it would land on
  // <body>. Move it to the list instead.
  const rowBlurred = (ev) => {
    if (listEl == null) return
    const row: any = ev.target
    if (ev.relatedTarget != null || row == null || row.parentNode !== listEl) return
    if (!row.classList.contains('rozie-sortable-item') || row.hasAttribute('tabindex') || !row.isConnected) return
    if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1')
    listEl.focus()
  }
  listEl?.addEventListener('focusout', rowBlurred)
  unhookNativeEvents = () => {
    for (const name of SORTABLE_DOM_EVENTS) listEl?.removeEventListener(name, stopNative)
    listEl?.removeEventListener('focusout', rowBlurred)
  }

  // Register with the keyboard registry. Other instances call these methods
  // when a keyboard lift hands a row between lists.
  entry = {
    el: listEl,
    group: () => effectiveGroup(),
    label: () => $props.listLabel,
    // A handle-mode list without a handle selector has its keyboard off.
    keyboardEnabled: () => keyboardEnabled() && !(handleMode() && handleSelector() == null),
    items: () => $props.items,
    keyOf: (item, i) => String(keyFor(item, i)),
    labelOf: (item, i, row: HTMLElement | null = null) => String(labelOf(item, i, row)),
    message: (kind, ctx) => announcementText($props.announcements, kind, ctx),
    onKey: (key, shift) => holderKey(key, shift),
    write: (next) => { $model.items = next },
    setLifted: (i) => { $data.liftedIndex = i },
    // The same text twice in a row would not change the region, and a screen
    // reader would not read it again ("Apple is already first", twice): a
    // repeat alternates a trailing no-break space, which is not spoken.
    announce: (text) => {
      const next = text !== '' && text === lastSpoken ? text + '\u00A0' : text
      lastSpoken = next
      $data.ariaLiveText = next
    },
    focusRow: (item, i) => refocusRow(item, i),
    focusNear: (i) => focusNearRow(i),
    rowEl: (i) => {
      const list = $props.items
      if (i < 0 || i >= list.length) return null
      return rowByKey(listEl, String(keyFor(list[i], i)))
    },
    // Always set (an equal value is a no-op on every target): a compare
    // against $data would read React's render-time ref, stale when two peer
    // changes land in one commit (one list unmounts, another mounts).
    peersChanged: (v) => {
      $data.hasHopPeer = v
    },
    emit: (name, payload) => {
      if (name === 'add') $emit('add', payload)
      else if (name === 'remove') $emit('remove', payload)
      else if (name === 'reorder') $emit('reorder', payload)
      else if (name === 'start') $emit('start', payload)
      else if (name === 'end') $emit('end', payload)
    },
  }
  unregisterEntry = registry.register(entry)
  const strayKey = (ev) => onStrayKey(ev)
  // A pointer press means the user moved on: keys lost to <body> after it
  // are not routed to the lift.
  const pointerPress = () => { if (registry.lift != null) registry.lift.focusPending = false }
  document.addEventListener('keydown', strayKey)
  document.addEventListener('pointerdown', pointerPress, true)
  unhookStrayKeys = () => {
    document.removeEventListener('keydown', strayKey)
    document.removeEventListener('pointerdown', pointerPress, true)
  }
  // $onMount's cleanup-return: closing over a setup-local (`sortable`) does
  // not survive the Solid emitter's setup/cleanup split — it scopes cleanup
  // outside the setup IIFE. Closing over `instance` / `unregisterEntry`
  // (module-scope `let`s) works on every target.
  return () => {
    instance?.destroy()
    // Unmounting while holding a keyboard lift ends it (its `end` comes from
    // the origin list, if that one is still mounted).
    if (registry.lift != null && registry.lift.holder === entry) loseLift(true)
    unregisterEntry?.()
    unregisterEntry = null
    unhookNativeEvents?.()
    unhookNativeEvents = null
    unhookStrayKeys?.()
    unhookStrayKeys = null
  }
})

// Reconcile prop changes into the live SortableJS instance without
// re-creating it. instance.option(name, value) is SortableJS's supported
// runtime update path for these fields.
//
// `forceFallback` is the ONE remaining construction-time-only knob — NOT
// reapplied here — changing it at runtime would require destroying and
// recreating the SortableJS instance. Consumers that need to flip it at
// runtime should re-key the <SortableList> on that value (see
// SortableListShowcaseDemo for the canonical pattern). `group` and
// `cloneable` both route through the shared `resolveGroup()` helper — so
// toggling `cloneable` live now correctly recomputes the clone-mode shape
// instead of forwarding a raw `$props.group` (the bug this fixes: the group
// watcher used to forward `$props.group` verbatim, bypassing the
// cloneable-derived object form). `swapThreshold` is read live by SortableJS
// on every dragover (never cached), so it is also safely runtime-updatable.
$watch(() => $props.disabled,      (v) => {
  instance?.option('disabled', v)
  setOverride('disabled', v)
})
// A runtime `option('animation', v)` and `options.animation` both win over
// the prop (see liveOption).
$watch(() => $props.animation,     (v) => instance?.option('animation', liveOption('animation', v)))
// `options` changed after mount: SortableJS read it once, at construction, so
// reapply each key whose value changed (a dropped key goes back to the value
// it has without `options`). The keyboard follows the same value, so mouse
// and keyboard agree without a remount.
$watch(() => $props.options, () => {
  if (!instance) return
  const next = $props.options
  const base = {
    animation:     $props.animation,
    disabled:      $props.disabled,
    group:         resolveGroup() ?? null,
    handle:        $props.handle,
    ghostClass:    $props.ghostClass,
    chosenClass:   $props.chosenClass,
    dragClass:     $props.dragClass,
    filter:        $props.filter,
    swapThreshold: $props.swapThreshold,
    easing:        $props.easing,
    sort:          true,
    draggable:     ROW_DRAGGABLE,
  }
  // A fresh inline function with the same content (React re-renders) is
  // applied so SortableJS runs the newest closure, but it is no change: a
  // runtime `option(name, v)` still in force keeps winning over it.
  const applied = reapplyOptions(instance, appliedOptions, next, base, {
    keep: (key, prev) => {
      const ov: any = $data.optionOverrides
      return ov != null && Object.prototype.hasOwnProperty.call(ov, key) && ov[key] !== prev
    },
    refreshed: (key) => {
      if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key))
    },
  })
  appliedOptions = next
  for (const key of applied) {
    // The keyboard reads the value SortableJS now runs with. A remembered
    // runtime `animation` / `handle` / `group` is superseded by the newer
    // `options` value.
    if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key))
    else if (TRACKED_OPTIONS.includes(key)) clearOverride(key)
  }
  if (applied.includes('group')) registry.notifyPeers()
})
// Every way the keyboard turns off (the `disabled` / `disableKeyboard` props,
// `options.disabled`, `option('disabled', v)`) re-runs this one check.
$watch(() => [$props.disabled, $props.disableKeyboard, $props.options, $data.optionOverrides], () => {
  if (!keyboardEnabled()) keyboardTurnedOff()
})
// `options.group` wins over `group` / `cloneable` (see effectiveGroup), for
// the mouse as for the keyboard.
// A group change can change which lists can take each other's rows: every
// list rechecks its Shift instructions.
const applyGroup = () => {
  instance?.option('group', effectiveGroup())
  registry.notifyPeers()
}
$watch(() => $props.group,         ()  => applyGroup())
$watch(() => $props.cloneable,     ()  => applyGroup())
$watch(() => $props.swapThreshold, (v) => instance?.option('swapThreshold', v))
$watch(() => $props.handle,        (v) => { instance?.option('handle', liveOption('handle', v)); warnIfHandleMissing() })
$watch(() => $props.keyboardTrigger, () => warnIfHandleMissing())
$watch(() => $props.ghostClass,    (v) => instance?.option('ghostClass',    v))
$watch(() => $props.chosenClass,   (v) => instance?.option('chosenClass',   v))
$watch(() => $props.dragClass,     (v) => instance?.option('dragClass',     v))
$watch(() => $props.filter,        (v) => { instance?.option('filter', v); setOverride('filter', v) })
$watch(() => $props.easing,        (v) => instance?.option('easing',        v))
// The items of the list holding a keyboard lift changed. If the lifted item
// is gone (by key, then by reference) the lift ends (no write; `end` still
// fires). If it is still there, the highlight follows it to its index (the
// consumer may have inserted or removed rows before it), and if its row
// element was re-created and focus fell to <body> with it, focus goes back to
// the lifted row.
$watch(() => $props.items, () => {
  const lift = registry.lift
  if (lift == null || lift.holder !== entry) return
  const i = registry.indexOfLift()
  if (i < 0) {
    loseLift()
    return
  }
  if ($data.liftedIndex !== i) $data.liftedIndex = i
  // Once the holder has rendered the lifted row, that is the lifted row
  // element. After a hop this drops the source's old row, which the source
  // may reuse for another item (index keys).
  const row = entry.rowEl(i)
  if (row != null) lift.liftedRowEl = row
  focusNearRow(i, lift.key)
})

// Imperative handle (Phase 21 $expose). The SortableJS imperative surface a
// consumer can't drive through props alone — exposed uniformly to all 6 targets.
// Each guards the pre-mount/destroyed `instance = null`. Collision-clear: none of
// the 4 verb names collide with the 16 props or the 5 events — `option` is a
// distinct identifier from the `options` prop, so ROZ121 is clear.
function getInstance() { return instance }
// toArray()/sort() use the rows' data-id keys — every row carries
// :data-id="keyFor(item, index)", so toArray() returns the current key order
// (set itemKey for stable object-list keys).
function toArray() { return instance ? instance.toArray() : [] }
// sort(order) reorders the bound items by those keys and writes them back
// (the framework re-renders the rows; SortableJS never moves them behind the
// model). Listed keys come first, in order; the rest follow in their order. No
// event fires: it is the consumer's own call. With `useAnimation` (and a
// non-zero `animation`) the rows slide from where they were.
function sort(order, useAnimation = true) {
  const list = $props.items
  const next = orderByKeys(list, order ?? [], keyFor)
  if (next.every((item, i) => item === list[i])) return
  const animate = useAnimation && instance != null
  if (animate) instance.captureAnimationState()
  $model.items = next
  if (animate) {
    const sortable = instance
    afterFlush(() => sortable.animateAll())
  }
}
// option(name) reads a live SortableJS option; option(name, value) sets one — the
// runtime escape hatch for any SortableJS option beyond the curated props.
// Setting `disabled`, `filter`, `draggable` or `sort` also applies to the
// keyboard; `option('disabled', true)` mid-lift ends the lift this list holds.
// A runtime `animation` is kept over later `animation` prop changes.
function option(name, value) {
  if (!instance) return undefined
  if (value === undefined) return instance.option(name)
  instance.option(name, value)
  if (TRACKED_OPTIONS.includes(name)) setOverride(name, value)
  if (name === 'disabled' && value) keyboardTurnedOff()
  // After the re-render, so every list reads the new group (React reads
  // state as of its last render).
  if (name === 'group') afterFlush(() => registry.notifyPeers())
  return value
}

$expose({ getInstance, toArray, sort, option })
</script>

<template>
<div class="rozie-sortable-wrap">
  <div
    :class="['rozie-sortable-list', $props.listClass]"
    ref="listEl"
    r-external
    part="list"
    role="list"
    :aria-label="$props.listLabel"
  >
    <!-- #header / #footer render inside the list element, around the rows.
         Only when filled: on Lit an unfilled <slot> is still an element child,
         and SortableJS then never treats an empty list as empty. -->
    <slot r-if="$slots.header" name="header" />
    <div
      r-for="item, index in $props.items"
      :key="keyFor(item, index)"
      :class="['rozie-sortable-item', itemClassFor(item, index), $data.liftedIndex === index ? 'rozie-sortable-item-lifted' : '']"
      :style="itemStyleFor(item, index)"
      :data-id="keyFor(item, index)"
      role="listitem"
      :tabindex="rowTabbable() ? 0 : null"
      :aria-describedby="rowTabbable() ? $data.instructionsId : null"
      @keydown="onRowKeyDown($event, index)"
    >
      <slot :item="item" :index="index" :instructionsId="$data.instructionsId" />
    </div>
    <slot r-if="$slots.footer" name="footer" />
  </div>
  <div
    class="rozie-sortable-aria-live"
    data-rozie-sortable-aria-live
    aria-live="polite"
    aria-atomic="true"
  >{{ $data.ariaLiveText }}</div>
  <span hidden :id="$data.instructionsId">{{ instructionsText() }}</span>
</div>
</template>

<style>
.rozie-sortable-wrap { display: block; }
.rozie-sortable-list { display: block; }
.rozie-sortable-item { display: block; outline: none; }
/* Focus ring (keyboard focus only). One colour for every color scheme: the
   component doesn't own the row background, so the ring must pass on light
   and dark rows alike. #1a73e8 has 4.5:1 contrast on white, 4.1:1 on #f5f5f7,
   4.2:1 on #121212 and 3.7:1 on #1e1e1e (WCAG 1.4.11 asks 3:1). Set
   --rozie-sortable-list-ring for another row background. */
.rozie-sortable-item:focus-visible { outline: 2px solid var(--rozie-sortable-list-ring, #1a73e8); outline-offset: -2px; }
.rozie-sortable-item-lifted {
  background: rgba(26, 115, 232, 0.1);
  box-shadow: 0 0 0 3px var(--rozie-sortable-list-ring, #1a73e8) inset;
}
/* aria-live announcer — visually hidden, accessible to screen readers. */
.rozie-sortable-aria-live {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
</style>

</rozie>

Compiled output ​

vue
<template>

<div class="rozie-sortable-wrap" v-bind="$attrs">
  <div :class="['rozie-sortable-list', props.listClass]" ref="listElRef" part="list" role="list" :aria-label="(props.listLabel) ?? undefined">
    
    <template v-if="$slots.header"><slot name="header"></slot></template><div v-for="(item, index) in items" :key="keyFor(item, index)" :class="['rozie-sortable-item', itemClassFor(item, index), liftedIndex === index ? 'rozie-sortable-item-lifted' : '']" :style="itemStyleFor(item, index)" :data-id="keyFor(item, index)" role="listitem" :tabindex="(rowTabbable() ? 0 : undefined) ?? undefined" :aria-describedby="(rowTabbable() ? instructionsId : undefined) ?? undefined" @keydown="onRowKeyDown($event, index)">
      <slot :item="item" :index="index" :instructionsId="instructionsId"></slot>
    </div>
    <template v-if="$slots.footer"><slot name="footer"></slot></template></div>
  <div class="rozie-sortable-aria-live" data-rozie-sortable-aria-live="" aria-live="polite" aria-atomic="true">{{ ariaLiveText }}</div>
  <span hidden :id="instructionsId">{{ instructionsText() }}</span>
</div>

</template>

<script lang="ts">
/** The kind of message the list speaks during keyboard reordering (a key of the `announcements` prop). */
export type AnnouncementKind = 'lifted' | 'moved' | 'movedToList' | 'dropped' | 'droppedInList' | 'atStart' | 'atEnd' | 'notSortable' | 'noListBefore' | 'noListAfter' | 'cancelledReturnedToList' | 'cancelledReturned' | 'cancelledStays' | 'cancelledRemoved' | 'liftEnded';
/** What an `announcements` function receives. */
export interface AnnouncementContext {
  /** The row's screen-reader label (`labelFor`, else `item.label`, else the row's text). */
  label: string;
  /** The item value. */
  item: unknown;
  /** The name of the list the message is about (`listLabel`, or `list 2 of 3`). */
  list: string;
  /** 1-based position of the row in `list` (kinds that have a position). */
  position?: number;
  /** How many rows `list` holds (kinds that have a position). */
  total?: number;
  /** The list the row came from (`movedToList` only). */
  fromList?: string;
}
/** The `announcements` prop: one optional function per message kind; `null` or `''` says nothing. */
export type Announcements = Partial<Record<AnnouncementKind, (ctx: AnnouncementContext) => string | null | undefined>>;
/** The payload every `start` / `end` / `reorder` / `add` / `remove` event carries, for pointer and keyboard alike. */
export interface SortablePayload {
  /** Which input made the change. */
  interaction: 'pointer' | 'keyboard';
  /** The item's data value (never an element). */
  item: unknown;
  /** The row element; null when there is none (a lost lift, a removed clone copy). */
  el: HTMLElement | null;
  /** The list element the row came from. */
  from: HTMLElement;
  /** The list element the row went to. */
  to: HTMLElement;
  /** Item-row index in `from`; -1 for `add`. */
  oldIndex: number;
  /** Item-row index in `to`; -1 for `remove` and a lost lift. */
  newIndex: number;
  /** Pointer only: the raw SortableJS event. */
  originalEvent?: unknown;
}
/** Which element drives keyboard reordering (the `keyboardTrigger` prop). */
export type SortableKeyboardTrigger = 'row' | 'handle';
/** Which arrow keys move a lifted row within the list (the `orientation` prop). */
export type SortableOrientation = 'vertical' | 'horizontal';
</script>

<script setup lang="ts">
import { computed, getCurrentInstance, onBeforeUnmount, onMounted, ref, watch } from 'vue';

import { ROW_DRAGGABLE, orderByKeys, reapplyOptions, useSortableJS } from './internal/useSortableJS';
import { afterFlush, canHop, getKeyboardRegistry, isRenderable, nextInstructionsId, rowLiftable } from './internal/keyboardRegistry';
import { announcementText, defaultInstructions, fallbackLabel } from './internal/announcements';

const props = withDefaults(
  defineProps<{
    /**
     * The per-row key the framework reconciler tracks each item by across a reorder — either a property name (e.g. `itemKey="id"` reads `item.id`) or an `(item, index) => key` function. With neither, id-less object items get a stable synthetic key via an internal `WeakMap` (survives reorder by object identity); primitive items fall back to index — pass a function for reorderable duplicate primitives.
     */
    itemKey?: string | ((...args: any[]) => any) | null;
    /**
     * CSS selector identifying the per-row drag handle, so a drag starts only from that element rather than anywhere in the row. Authored class names render literally on every target (React included), so a plain `.grip` works; `$classSelector('grip')` is an optional, typo-checked way to author it. `options.handle` and `option('handle', v)` win over this prop, for the keyboard (`keyboardTrigger: 'handle'`) as for the mouse.
     */
    handle?: string | null;
    /**
     * SortableJS group name enabling cross-list drag — two lists sharing a `group` accept items between each other (the source fires `remove`, the destination fires `add`). Set `cloneable: true` to flip a string group into clone-mode. Lists that share a `group` also exchange rows by keyboard: Shift+arrow while a row is lifted hops it to the previous or next list of the same group (in source order), subject to the same pull/put rules as a mouse drag. `options.group` takes precedence over this prop, for keyboard hops as for drags. Function-valued `pull`/`put` cannot be evaluated without a drag, so those lists are unreachable by keyboard. Set `itemKey` on grouped lists.
     */
    group?: string | null;
    /**
     * Reorder animation duration in milliseconds. `0` disables the animation. Reapplied live via `instance.option('animation', v)` (no remount). `options.animation`, and a runtime `option('animation', v)`, win over this prop.
     */
    animation?: number;
    /**
     * Temporarily disable dragging without unmounting — reapplied live via `instance.option('disabled', v)` (no remount). Also suppresses keyboard reordering: a disabled list is not sortable by any input, so rows lose their `tabindex` and the keydown handler no-ops. Turning it on while a row is lifted ends the lift where the row is (`Lift ended`, and `end` fires); `options.disabled` and `option('disabled', v)` do the same.
     */
    disabled?: boolean;
    /**
     * Opt out of keyboard reordering (Space lift / Arrow move / Shift+Arrow hop between lists / Esc cancel / Enter drop) while leaving pointer drag enabled. Rows drop out of the tab order (no `tabindex`) and the keydown handler no-ops. Keyboard access is gated on `!disabled && !disableKeyboard`. Turning it on while a row is lifted ends the lift where the row is.
     */
    disableKeyboard?: boolean;
    /**
     * Which element drives keyboard reordering. `'row'` (default): rows are tab stops and the keys on the focused row drive reordering. `'handle'`: rows are NOT tab stops, and only keys pressed inside the element matched by `handle` (inside that row) drive the same Space/Enter lift-drop, Arrow move, Shift+Arrow hop and Escape cancel flow; handled keys call preventDefault so a handle `<button>`'s click does not fire. The consumer owns the handle markup (recommended: a `<button>` with its own aria-label such as "Reorder Hero banner") and the component adds no tabindex or role to slot content. `'handle'` without `handle` turns keyboard reordering off and logs a console warning. `disabled`/`disableKeyboard` still apply. Typed as `SortableKeyboardTrigger` (`'row' | 'handle'`); at runtime any value other than `'handle'` behaves as `'row'`.
     */
    keyboardTrigger?: SortableKeyboardTrigger;
    /**
     * Verbatim SortableJS options pass-through for anything not covered by the named props. The named props win on key conflict but `options` lands AFTER them in the merge so consumers can override defaults; handler keys (`onStart`, `onEnd`, `onUpdate`, `onAdd`, `onRemove`, `onClone`) are stripped — the helper owns those paths. Runtime-updatable: when `options` changes, each key whose value changed is reapplied via `instance.option(key, v)` (no remount), so mouse and keyboard obey the same values; a key you drop goes back to its named prop (or, for `sort` and `draggable`, the component default), and any other dropped key keeps its last value until you set it. `forceFallback` is still read only at construction.
     */
    options?: Record<string, any>;
    /**
     * Optional `(item, idx) => string` returning the screen-reader label for the aria-live announcer during keyboard drag. Defaults to `item.label`; without a `label` field, the row's text (whitespace collapsed, without nested lists or hidden content), else `String(item)` for a primitive, else `item {position}`.
     */
    labelFor?: ((...args: any[]) => any) | null;
    /**
     * Class name applied to the drop-placeholder (ghost) element while dragging. Forwarded live via `instance.option`, so toggling it at runtime takes effect without a remount.
     */
    ghostClass?: string | null;
    /**
     * Class name applied to the currently-chosen item while dragging. Forwarded live via `instance.option` (no remount needed to change it).
     */
    chosenClass?: string | null;
    /**
     * Class name applied to the dragging element. Only takes effect in fallback mode (`forceFallback: true`). Forwarded live via `instance.option`.
     */
    dragClass?: string | null;
    /**
     * CSS selector that prevents drag initiation on matching rows (locked items). SortableJS checks it at `mousedown`/`touchstart` and aborts the drag if it matches. The keyboard honours it too: a row that matches (the row element, or its slot root: the row template's single element when nothing else sits beside it) cannot be lifted with Space/Enter; any other matching control (a `.js-remove` button, an `input`) blocks only presses on itself. `options.filter` (which may also be a SortableJS filter function) takes precedence. A `data-*` attribute selector (e.g. `[data-locked]`) is the most robust choice across all targets.
     */
    filter?: string | null;
    /**
     * CSS easing function for the reorder animation (e.g. `'ease-in'`, `'cubic-bezier(0.4, 0, 0.2, 1)'`). Runtime-updatable.
     */
    easing?: string | null;
    /**
     * Force SortableJS's mouse-event drag path over HTML5 DnD — useful for touch devices, consistent cross-browser behavior, and synthetic test drivers (and `dragClass` only applies in this mode). **Construction-time only**: SortableJS reads it once at construction, so re-key the `<SortableList>` to toggle it at runtime.
     */
    forceFallback?: boolean;
    /**
     * SortableJS swap threshold (0..1) — a lower value makes rows swap earlier as the dragged item overlaps a neighbor. Reapplied live via `instance.option('swapThreshold', v)` — SortableJS reads it on every dragover, so no remount is needed.
     */
    swapThreshold?: number;
    /**
     * High-level prop that REPLACES a string `group` with SortableJS's `{ name, pull: 'clone', put: false }` clone-mode object form — the source deposits a COPY onto the destination and keeps its own array unchanged, and takes nothing back: no row can be dropped or keyboard-hopped into it (the palette → canvas pattern). With `group: null` it is a no-op (a clone-mode list with no group name has no peer to clone into). Reapplied live — toggling `cloneable` (or changing `group`) recomputes the clone-mode shape and reapplies it via `instance.option('group', …)`, no remount.
     */
    cloneable?: boolean;
    /**
     * Extra class(es) merged onto the list container (the SortableJS root) alongside the base `rozie-sortable-list` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding), normalized identically across all six targets — the hook for bridging a CSS framework (`.list-group`) or a flex/grid parent onto the component.
     */
    listClass?: string | any[] | Record<string, any>;
    /**
     * Extra class(es) merged onto every item row alongside the base `rozie-sortable-item` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding) applied uniformly, OR an `(item, index) => class` function for per-row classes evaluated at render time. Normalized identically across all six targets.
     */
    itemClass?: string | any[] | Record<string, any> | ((...args: any[]) => any);
    /**
     * The list's human name, such as `"Top sidebar"`. Sets `aria-label` on the list container (`role="list"`) and names the list in keyboard announcements when a row moves between lists (`Moved Hero banner to Top sidebar, position 1 of 4`, `Dropped Hero banner in Top sidebar at position 3 of 4`, `No list after Top sidebar`). Pass the same words as the zone's visible heading. With no label, announcements fall back to a neutral `list 2 of 3`, counting the mounted lists of the same group in hop (source) order.
     */
    listLabel?: string | null;
    /**
     * Which arrow keys move a lifted row within the list: `'vertical'` (default) uses ↑/↓, `'horizontal'` uses ←/→. A horizontal list's default spoken instructions say "Use the left and right arrow keys to move" (`role="list"` has no `aria-orientation`). Typed as `SortableOrientation` (`'vertical' | 'horizontal'`).
     */
    orientation?: SortableOrientation;
    /**
     * How many positions Page Up / Page Down move a lifted row. The move stops at the first or last position when fewer rows remain.
     */
    pageStep?: number;
    /**
     * Replaces the spoken keyboard instructions. The text sits in a hidden element referenced by `aria-describedby` from each tabbable row (row mode) or from the consumer's handle via the `instructionsId` slot prop (handle mode). Default: "Press Space or Enter to pick up, and again to drop. Use the up and down arrow keys to move, Home and End to jump to the start or end, Page Up and Page Down to move several places, and Escape to cancel." (with `orientation: 'horizontal'`, "the left and right arrow keys"; a `sort: false` list says only "Press Space or Enter to pick up, and again to drop. Press Escape to cancel."). When another mounted list could take this list's rows (by the group rules of `group`, `options.group` or `option('group', v)`), the default adds "Hold Shift with an arrow key to move to another list." (updated as lists mount, unmount or change group).
     */
    keyboardInstructions?: string | null;
    /**
     * Rewords or translates what the list says during keyboard reordering. An object of optional functions keyed by message kind (`lifted`, `moved`, `movedToList`, `dropped`, `droppedInList`, `atStart`, `atEnd`, `notSortable`, `noListBefore`, `noListAfter`, `cancelledReturnedToList`, `cancelledReturned`, `cancelledStays`, `cancelledRemoved`, `liftEnded`). Each receives a context (`label`, `item`, `list`, and for kinds with a position `position` (1-based) and `total`; `movedToList` also `fromList`) and returns the text to speak; `null` or `''` says nothing. Kinds without a function keep the default English text (see "Announcements"). Define the object in your script and bind it (Angular templates reject inline arrow functions), e.g. `const announcements = { moved: ({ label, position, total }) => label + ' → ' + position + '/' + total }`. Typed as `Announcements`, exported with `AnnouncementKind` and `AnnouncementContext`.
     * @example
     * <SortableList v-model:items="todos" :announcements="announcements" />
     */
    announcements?: Announcements | null;
    /**
     * Per-row inline style applied to the `.rozie-sortable-item` wrapper. Accepts a CSS `String`, a flat style object (`Record<string, string | number>`), or an `(item, index) => string | object` function for per-row styling. Because it lands on the wrapper — the direct child of the list container — it can drive CSS-grid placement (`grid-column` / `grid-row` / `align-self`) when `listClass` sets `display: grid`. Normalized per target; `null` / empty drops the attribute.
     */
    itemStyle?: string | Record<string, any> | ((...args: any[]) => any) | null;
  }>(),
  { itemKey: null, handle: null, group: null, animation: 150, disabled: false, disableKeyboard: false, keyboardTrigger: 'row', options: () => ({}), labelFor: null, ghostClass: null, chosenClass: null, dragClass: null, filter: null, easing: null, forceFallback: false, swapThreshold: 1, cloneable: false, listClass: '', itemClass: '', listLabel: null, orientation: 'vertical', pageStep: 5, keyboardInstructions: null, announcements: null, itemStyle: null }
);

const __rozieVm = getCurrentInstance()!;
/** Whether the consumer binds a value (not `undefined`) to the two-way prop `name`. */
const __rozieBound = (name: string): boolean => {
  const raw = __rozieVm.vnode.props;
  if (!raw) return false;
  const kebab = name.replace(/\B([A-Z])/g, '-$1').toLowerCase();
  return (name in raw ? raw[name] : raw[kebab]) !== undefined;
};
/**
 * The bound items array. The sole `model: true` prop — two-way bind it (`r-model:items` / `v-model:items` / `bind:items` / `[(items)]`) and SortableList writes the re-ordered array back whenever a drag, cross-list move, or keyboard reorder commits, with no manual `onChange → setState` wiring.
 * @example
 * <SortableList v-model:items="todos" itemKey="id" />
 */
const __rozieModel_items = defineModel<any[]>('items', { default: () => [] });
const items = computed<any[]>({
  get: () => __rozieModel_items.value,
  set: (v) => { if (__rozieBound('items')) __rozieVm.emit('update:items', v); else __rozieModel_items.value = v; },
});

const emit = defineEmits<{
  reorder: [payload: SortablePayload];
  add: [payload: SortablePayload];
  remove: [payload: SortablePayload];
  start: [payload: SortablePayload];
  end: [payload: SortablePayload];
}>();

defineSlots<{
  header(props: {  }): any;
  default(props: { item: any; index: any; instructionsId: any }): any;
  footer(props: {  }): any;
}>();

const liftedIndex = ref<any>(null);
const ariaLiveText = ref('');
const instructionsId = ref<any>(null);
const optionOverrides = ref({});
const hasHopPeer = ref(false);

const listElRef = ref<HTMLElement>();

let instance: any = null;
// The `options` object SortableJS was last given (see the `options` watcher).
let appliedOptions: any = null;
// Keyboard lift state lives in the shared registry (one active keyboard lift
// per page, so a later task can hand a lifted row between lists).
// `$data.liftedIndex` is only its mirror, for the lifted-row styling.
const registry = getKeyboardRegistry();
// This list's registry entry (a ListEntry), built and registered in $onMount.
let entry: any = null;
let unregisterEntry: any = null;
// Removes the listeners that keep SortableJS's own DOM events inside the list.
let unhookNativeEvents: any = null;
// Removes the document keydown listener that catches keys lost to <body>.
let unhookStrayKeys: any = null;
// SortableJS also dispatches its events as BUBBLING native DOM events
// (`start`, `end`, `add`, `remove`, `change`, …) on the list element, before
// it calls the option callbacks. An output binding on the component host
// (Angular's `(start)` / `(end)` / `(add)` / `(remove)`, a Lit listener) also
// catches a native DOM event of the same name, so a consumer would get the raw
// SortableJS event as an extra event. The component re-emits the committed
// events itself, so stop the raw ones at the list element (only events
// dispatched ON the list — an `<input>`'s own `change` is untouched).
const SORTABLE_DOM_EVENTS = ['choose', 'unchoose', 'start', 'end', 'add', 'update', 'sort', 'remove', 'filter', 'clone', 'change', 'select', 'deselect'];
// role="list" takes no aria-orientation, so a horizontal list says which
// arrow keys move in its instructions instead. A `sort: false` list leaves out
// the move sentence, and a list whose rows another mounted list could take
// (by the group SortableJS runs with, `options.group` included) says how to
// hop.
const instructionsText = () => {
  if (props.keyboardInstructions != null) return props.keyboardInstructions;
  return defaultInstructions({
    horizontal: props.orientation === 'horizontal',
    sortable: liveOption('sort', true) !== false,
    grouped: effectiveGroup() != null && hasHopPeer.value
  });
};
// Instance-scoped synthetic-id store for id-less object items. Keyed by object
// IDENTITY, so the same object keeps its synthetic id across a reorder (the
// framework reconciler then rebinds the row component instance to its ORIGINAL
// item, not its slot position — the data-corruption fix).
//
// Phase 73 item #11-b removed the former "fold the WeakMap + counter into ONE
// member-mutated object const" workaround: `hoistModuleLet`'s reachability
// walk now also roots at helpers called ONLY from a template expression
// (`keyFor` is called from `:key`/`:data-id`, never from a hook), so the bare
// `let __rowKeySeq = 0` below hoists to a `useRef` on React exactly like the
// hook-reached case — no more per-render reset. Verified in codegen.
const __rowKeyMap = new WeakMap();
let __rowKeySeq = 0;
// 4-tier per-row key precedence. Its return feeds BOTH :key and :data-id.
const keyFor = (item: any, index: any) => {
  // (a) function itemKey: consumer-supplied (item, index) => key.
  if (typeof props.itemKey === 'function') {
    return props.itemKey(item, index);
  }
  // (b) string itemKey: a property name on a non-null object item.
  if (typeof props.itemKey === 'string' && item !== null && typeof item === 'object' && item[props.itemKey] != null) {
    return item[props.itemKey];
  }
  // (c) id-less object (or function) item: assign-on-first-sight WeakMap
  //     synthetic id. Survives reorder because it is keyed by object identity.
  if (item !== null && typeof item === 'object' || typeof item === 'function') {
    if (!__rowKeyMap.has(item)) {
      __rowKeyMap.set(item, '__rk' + __rowKeySeq++);
    }
    return __rowKeyMap.get(item);
  }
  // (d) primitive item: fall back to index. NOTE: duplicate primitives are
  //     unsafe to reorder this way — pass a function itemKey for those.
  return index;
};
// Resolve the SortableJS `group` option: `cloneable` is a high-level Rozie
// prop that REPLACES a string `group` with SortableJS's
// `{ name, pull: 'clone', put: false }` clone-mode object form (a palette
// takes nothing back, by mouse or keyboard). When
// `cloneable:false`, pass `$props.group` through verbatim. When
// `cloneable:true` AND `$props.group` is null, leave it null — a clone-mode
// list without a group name is not meaningful (no peer list can join the
// cross-list flow). Shared by $onMount construction AND the group/cloneable
// $watch reconcile below — single source of truth, no duplicated ternary.
const resolveGroup = () => props.cloneable && typeof props.group === 'string' ? {
  name: props.group,
  pull: 'clone' as const,
  put: false as const
} : props.group ?? undefined;
// The group SortableJS actually runs with: a runtime `option('group', v)`,
// else `options.group` (it lands after the named props in the merge), else
// the `group` / `cloneable` props. Keyboard hops follow the same rules as the
// mouse, so they read this one.
const effectiveGroup = () => {
  const ov: any = optionOverrides.value;
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, 'group')) return ov.group;
  const o: any = props.options;
  return o != null && o.group != null ? o.group : resolveGroup();
};
// Resolve itemClass for a row: a static value (string | array | object) OR a
// per-row (item, index) => class function. The result is fed into the :class
// array and normalized by each target's class path (rozieClass / clsx / native).
const itemClassFor = (item: any, index: any) => {
  const v = props.itemClass;
  return typeof v === 'function' ? v(item, index) : v;
};
// Resolve itemStyle for a row: a static value (string | object) OR a per-row
// (item, index) => style function. Returns string | object | null; the dynamic
// :style binding normalizes it per target. null / empty → attribute dropped.
const itemStyleFor = (item: any, index: any) => {
  const s = typeof props.itemStyle === 'function' ? props.itemStyle(item, index) : props.itemStyle;
  return s == null || s === '' ? null : s;
};
// Read the display label for an item — used by the aria-live announcer.
// Phase 16 R7 / D-08: $props.labelFor reads as `null` on all 6 targets when
// the consumer omits it (Plan 16-01 prop-default coercion fix); the check is
// a plain null compare — NO runtime callable-type coercion. Without
// `labelFor` or a `label` field, the row's text (`row`), else `String(item)`
// for a primitive, else `item {position}`.
const labelOf = (item: any, idx: any, row: HTMLElement | null = null) => {
  if (props.labelFor !== null) return props.labelFor(item, idx);
  if (item !== null && typeof item === 'object' && item.label != null) return item.label;
  return fallbackLabel(item, idx, row);
};
// The text this list's live region showed last (see the registry entry's
// `announce`).
let lastSpoken = '';
// Keyboard handler (Phase 16 R7): Space/Enter lift and drop; while lifted,
// ArrowUp/ArrowDown (ArrowLeft/ArrowRight when horizontal), Home/End and
// PageUp/PageDown move the row, and Escape returns it to where it was lifted
// from. The lift itself lives in the shared keyboard registry. After
// any array-reorder write, refocusRow() keeps focus on the moved row (or its
// handle) on all six targets.
//
// Note: `index` is passed directly as a number. Plan 16-02 (Solid call-arg
// accessor unwrap) ensures Solid's <For> alias unwraps to `index()` at the
// call site — no runtime callable-type coercion needed in user source.
// Keyboard reordering is available only when the list is not disabled AND the
// `disableKeyboard` opt-out is off. Drives BOTH the row tabindex (rows are
// focusable only when reorderable) and the onRowKeyDown guard below. Reads
// straight off $props so the tabindex binding re-evaluates reactively when
// `disabled`/`disableKeyboard` toggle at runtime.
//
// The keyboard follows the SortableJS options the mouse obeys: `disabled`
// (the prop, `options.disabled`, or `option('disabled', v)`), `filter` and
// `draggable` (which rows lift, see rowLiftable) and `sort: false` (no moves
// within the list). `liveOption` reads the value SortableJS runs with: one set
// at runtime, else `options`, else the named prop.
const KEYBOARD_OPTIONS = ['disabled', 'filter', 'draggable', 'sort'];
const liveOption = (name: any, fallback: any) => {
  const ov: any = optionOverrides.value;
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, name)) return ov[name];
  const o: any = props.options;
  if (o != null && o[name] !== undefined) return o[name];
  return fallback;
};
const setOverride = (name: any, value: any) => {
  optionOverrides.value = {
    ...optionOverrides.value,
    [name]: value
  };
};
const clearOverride = (name: any) => {
  const ov: any = optionOverrides.value;
  if (ov == null || !Object.prototype.hasOwnProperty.call(ov, name)) return;
  const next = {
    ...ov
  };
  delete next[name];
  optionOverrides.value = next;
};
// Options whose runtime value (`option(name, v)`) is remembered, so a later
// change of the matching prop doesn't overwrite it: the keyboard ones, plus
// `animation`, `handle` and `group` (runtime override → `options` → prop).
const TRACKED_OPTIONS = [...KEYBOARD_OPTIONS, 'animation', 'handle', 'group'];
const keyboardEnabled = () => !props.disableKeyboard && !liveOption('disabled', props.disabled);
// The handle selector SortableJS runs with (`option('handle', v)`, else
// `options.handle`, else the `handle` prop): the keyboard reads the same one.
const handleSelector = () => liveOption('handle', props.handle);
// keyboardTrigger='handle' mode: rows are not tab stops and the keys are read
// from the consumer's handle element instead. Any other value is 'row' mode.
const handleMode = () => props.keyboardTrigger === 'handle';
// Rows are tab stops only in row mode (and only while keyboard is enabled).
const rowTabbable = () => keyboardEnabled() && !handleMode();
// One-time-per-change dev warning: handle mode needs a handle selector. Without
// one the keyboard is OFF (see the onRowKeyDown gate) — never a silent fallback
// to row mode, which would re-introduce the tab stops the consumer opted out of.
const warnIfHandleMissing = () => {
  if (handleMode() && handleSelector() == null) {
    console.warn('[rozie-sortable-list] keyboardTrigger is "handle" but no handle selector is set, so keyboard reordering is off. Pass a handle selector (e.g. handle=".grip") or use keyboardTrigger "row".');
  }
};
// True only when a keydown originated inside a `handle` element that belongs to
// THIS row. Walks the COMPOSED ancestor chain from the event target up to (but
// excluding) the row (currentTarget): assignedSlot -> parentNode -> shadow host.
// Plain closest()/contains() stop at a shadow boundary, and Lit renders a Rozie
// consumer's slot content inside the SortableList shadow root while plain-HTML
// consumers project light-DOM nodes through a <slot>. composedPath() is not
// used because React's synthetic event does not expose it. Another
// .rozie-sortable-item met first means the key came from a NESTED list's row,
// which must not reorder this (outer) list.
const isHandleKeyOrigin = ($event: any) => {
  const sel = handleSelector();
  if (sel == null) return false;
  const row = $event.currentTarget;
  let n: any = $event.target;
  while (n && n !== row) {
    if (n.nodeType === 1) {
      if (n.matches(sel)) {
        // Matched a handle: it counts only if this row is reachable from here
        // without crossing a different sortable item.
        let m: any = n.assignedSlot ?? n.parentNode ?? n.host;
        while (m && m !== row) {
          if (m.nodeType === 1 && m.classList.contains('rozie-sortable-item')) return false;
          m = m.assignedSlot ?? m.parentNode ?? m.host;
        }
        return m === row;
      }
      if (n.classList.contains('rozie-sortable-item')) return false;
    }
    n = n.assignedSlot ?? n.parentNode ?? n.host;
  }
  return false;
};
// Put focus back on the MOVED row (row mode) or its handle (handle mode) after
// a reorder write. Looks the row up by KEY (data-id), not by index, so it finds
// the moved row whether this runs before the framework commit (the row element
// is the same one) or after it (Svelte/Solid/Lit re-create the DOM) — and it is
// correct for index-keyed primitive lists too. Direct children of the list
// container only: that skips nested-list rows and the header/footer slot
// content.
//
// Two passes. (1) A microtask covers targets that commit synchronously or in an
// earlier microtask (Vue's scheduler flush is queued by the model write, before
// this one). (2) A timer + rAF "heal" pass covers targets whose DOM commit is
// scheduled AFTER the key handler returns (Angular): the commit can MOVE the
// focused row, and moving a focused node blurs it, so a Home/End/Escape jump or
// a rapid Space/Arrow/Arrow/Space burst would otherwise end with focus on
// <body>. The heal pass never steals: it acts only when focus has been lost to
// <body>. (`$restoreFocus(selector, index)` is not enough here: it is a no-op on
// Vue/Angular, where a long jump moves the focused row itself, and it looks the
// row up by index, which can land on a neighbour on Lit.) The $refs read
// happens here, synchronously, inside an event handler — which is safe.
const refocusRow = (item: any, idx: any) => {
  const listEl = listElRef.value;
  const sel = handleSelector();
  const useHandle = handleMode();
  const key = String(keyFor(item, idx));
  // While this refocus is outstanding, a key that falls to <body> belongs to
  // the lift (see onStrayKey). Cleared once the row has focus again, or by a
  // pointer press anywhere.
  const pending = registry.lift;
  if (pending != null) pending.focusPending = true;
  const focusIt = (onlyIfLost: any) => {
    if (!listEl) return;
    if (useHandle && sel == null) return;
    if (onlyIfLost && document.activeElement && document.activeElement !== document.body) return;
    for (const row of Array.from(listEl.children) as any[]) {
      if (row.getAttribute('data-id') === key) {
        const target = useHandle ? row.querySelector(sel) : row;
        if (target && typeof target.focus === 'function') {
          target.focus();
          const l = registry.lift;
          if (l != null && l === pending && l.key === key) {
            l.focusPending = false;
            // This row is the lifted row element now (see the items watcher).
            l.liftedRowEl = row;
          }
        }
        return;
      }
    }
  };
  queueMicrotask(() => focusIt(false));
  setTimeout(() => focusIt(true), 0);
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => focusIt(true));
};
// `el` in an event payload: the row element while it is in the page, else
// null (a row that left with an unmounted list is no row of any list).
const liveEl = (el: any) => el != null && el.isConnected ? el : null;
// The row element carrying `data-id === key` among a list element's direct
// children (skips nested-list rows and header/footer slot content).
const rowByKey = (listEl: any, key: any) => {
  if (!listEl || key == null) return null;
  for (const row of Array.from(listEl.children) as any[]) {
    if (row.getAttribute('data-id') === key) return row;
  }
  return null;
};
// After the consumer changed the items of the list holding a lift, put focus
// on the row (or its handle) whose key is `key`, else the row nearest `index`
// (or the list itself when it has no rows left) — but only once focus has fallen to <body> (the focused row's element went
// away: the lift was lost, or a framework that keys rows by object identity
// re-created the lifted row). Never steals focus from anywhere else. Same
// three passes as refocusRow, for targets that commit late.
const focusNearRow = (index: number, key: string | null = null) => {
  const listEl = listElRef.value;
  const sel = handleSelector();
  const useHandle = handleMode();
  const focusIt = () => {
    if (!listEl) return;
    if (useHandle && sel == null) return;
    if (document.activeElement && document.activeElement !== document.body) return;
    const rows = Array.from(listEl.children).filter((r: any) => r.hasAttribute('data-id') && r.classList.contains('rozie-sortable-item')) as any[];
    if (rows.length === 0) {
      // The list is now empty: focus the list itself (out of the tab order)
      // so keyboard and screen-reader users stay where they were.
      if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
      listEl.focus();
      return;
    }
    const row = rows.find((r: any) => key != null && r.getAttribute('data-id') === key) ?? rows[Math.max(0, Math.min(rows.length - 1, index))];
    const target = useHandle ? row.querySelector(sel) : row;
    if (target && typeof target.focus === 'function') target.focus();
  };
  queueMicrotask(focusIt);
  setTimeout(focusIt, 0);
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(focusIt);
};
// Speak `text` from `target`'s aria-live region. The region that spoke last
// is cleared when it belongs to another list, so a message is heard once, from
// the list the row is in now, and never from a list that just lost it.
const speak = (target: any, text: any) => {
  const prev = registry.speaker;
  if (prev != null && prev !== target && registry.has(prev)) prev.announce('');
  registry.speaker = target;
  target.announce(text);
};
// Say announcement `kind` from `target`, in `target`'s words: its
// `announcements` function for that kind, else the default text (see
// ./internal/announcements). `index` is the row's 0-based position in
// `target`, `row` the row element its label is read from (when there is no
// `labelFor` or `label` field), and `total` how many rows `target` holds after
// the change (null for the kinds without a position). A function returning
// null or '' clears the region, so nothing is said.
const say = (target: any, kind: AnnouncementKind, item: unknown, index: number, row: HTMLElement | null, total: number | null = null, fromList: any = null) => {
  const ctx: any = {
    item,
    list: registry.listName(target)
  };
  // The label is read only when the text needs it (a default with `{label}`,
  // or an override that reads `label`), so `labelFor` is not called for a
  // message that doesn't name the row (`Lift ended`: the item has left).
  let label: string | null = null;
  Object.defineProperty(ctx, 'label', {
    enumerable: true,
    get: () => {
      if (label === null) label = target.labelOf(item, index, row);
      return label;
    }
  });
  if (total != null) {
    ctx.position = index + 1;
    ctx.total = total;
  }
  if (fromList != null) ctx.fromList = registry.listName(fromList);
  speak(target, target.message(kind, ctx));
};
// The lifted item is no longer in the list holding it: the consumer changed
// that list's items (or re-keyed the item), or the list is unmounting. End the
// lift without writing anything (the item is wherever the consumer's data put
// it). `end` still fires once, with `item` = the lifted value and `el: null`
// (there is no row), so keyboard `start` / `end` pair (unless the holder and the origin have both unmounted). Lost to a consumer change (not an
// unmount), the holder says `Lift ended` and, if focus fell to <body> with the
// row, focuses its row nearest where the lifted row was.
const loseLift = (unmounting = false) => {
  const lift = registry.lift;
  if (!lift) return;
  const h = lift.holder;
  registry.lift = null;
  h.setLifted(null);
  if (!unmounting) {
    say(h, 'liftEnded', lift.item, lift.index ?? lift.origin.index, lift.liftedRowEl);
    h.focusNear(lift.index ?? lift.origin.index);
  }
  const payload = {
    interaction: 'keyboard' as const,
    item: lift.item,
    el: null,
    from: lift.origin.list.el,
    to: h.el,
    oldIndex: lift.origin.index,
    newIndex: -1
  };
  // Like every `end`, in a task after the writes, from the holder. An
  // unmounted list never emits (Angular rejects an emit from a destroyed
  // component): when the holder is unmounting, the origin list (which emitted
  // `start`) ends the lift if it is still mounted, so `start` and `end` pair;
  // if it is gone too, nothing is emitted.
  registry.deferEnd((host: any) => host.emit('end', payload), h, lift.origin.list);
};
// Keyboard `start` / `end` (the same payload as every other event): `item` is
// the item value, `el` its row element. `start` fires from the origin list
// (`from`), `end` from the list the row ends up in (`to`). `el` is the row in
// that list when it is rendered, else `fallbackEl` (the row element the move
// started from, before a target re-rendered). `end` is called after
// `registry.lift` is cleared, so a consumer `end` handler that writes the
// items (re-keying a clone copy) is not mistaken for a lost lift, and it is
// emitted in a task (`registry.deferEnd`), after the writes AND the re-render
// they schedule: a consumer `end` handler reads the new state on every target
// (React included, whose handler closure is the one from the latest render).
// If `to` has unmounted by then, `from` (the origin, which emitted `start`)
// emits it instead, `to` unchanged in the payload; an unmounted list never
// emits.
const keyboardStartEnd = (name: any, lift: any, from: any, to: any, oldIndex: any, newIndex: any, fallbackEl: HTMLElement | null = null) => {
  const fire = (host: any) => host.emit(name, {
    interaction: 'keyboard',
    item: lift ? lift.item : null,
    el: (lift && host === to ? rowByKey(host.el, lift.key) : null) ?? liveEl(fallbackEl),
    from: from.el,
    to: to.el,
    oldIndex,
    newIndex
  });
  if (name === 'end') registry.deferEnd(fire, to, from);else fire(from);
};
// Move the lifted row to `toIndex` (clamped) within the list holding it.
// Works through the registry entry, so it acts on the current holder. `dir`
// is the key's direction (-1 toward the start), for when the row can't move.
const moveLiftTo = (toIndex: any, dir: any) => {
  const lift = registry.lift;
  if (!lift) return;
  const h = lift.holder;
  const from = registry.indexOfLift();
  if (from < 0) {
    loseLift();
    return;
  }
  const items = h.items();
  const to = Math.max(0, Math.min(items.length - 1, toIndex));
  // The moved row's element, read before the write (an index key changes).
  const el = h.rowEl(from);
  if (to === from) {
    // Nowhere to go: say so (the row is already at that end).
    say(h, dir < 0 ? 'atStart' : 'atEnd', items[from], from, el ?? lift.liftedRowEl, items.length);
    return;
  }
  const next = [...items];
  const [moved] = next.splice(from, 1);
  next.splice(to, 0, moved);
  // Index keys (primitive items without itemKey) change with the position.
  // Update the lift BEFORE writing: a target whose watchers run synchronously
  // on the write must already see where the row is going.
  lift.key = h.keyOf(moved, to);
  lift.index = to;
  h.write(next);
  h.setLifted(to);
  // Name the row that MOVED from the local `moved` item: on React/Vue/Lit the
  // items prop still holds the pre-write array here. Labels come from the
  // holder's own `labelFor`.
  say(h, 'moved', moved, to, el, items.length);
  h.focusRow(moved, to);
  h.emit('reorder', {
    interaction: 'keyboard',
    item: moved,
    el,
    from: h.el,
    to: h.el,
    oldIndex: from,
    newIndex: to
  });
};
// Hop the lifted row to the next (`dir` 1) or previous (-1) list it could
// also reach by mouse, in composed-tree source order. One hand-off: the source
// writes its items without the row, the destination writes them with it, and
// the destination becomes the holder. As with the mouse, the destination
// emits `add` first, then the source emits `remove`. A forward hop lands
// first, a backward hop lands last.
const hop = (dir: any) => {
  const lift = registry.lift;
  if (!lift) return;
  const from = lift.holder;
  const i = registry.indexOfLift();
  if (i < 0) {
    loseLift();
    return;
  }
  const fromItems = from.items();
  const data = fromItems[i];
  const el = from.rowEl(i);
  // Keep the lifted row element current: lists nested inside it (a grid
  // widget's columns) are never hop targets. Before a target re-renders the
  // row may not exist yet, so keep the last known element then.
  lift.liftedRowEl = el ?? lift.liftedRowEl;
  const to = registry.findHopTarget(from, dir);
  if (to == null) {
    say(from, dir === 1 ? 'noListAfter' : 'noListBefore', data, i, el ?? lift.liftedRowEl);
    return;
  }
  const origin = lift.origin;
  const toItems = to.items();
  // A clone copy hopping back into the list it was cloned from merges with
  // its original there (that list never gave it up), rather than adding a
  // second row with the same key.
  if (lift.copy && to === origin.list) {
    let home = toItems.indexOf(data);
    if (home < 0) home = Math.max(0, Math.min(toItems.length - 1, origin.index));
    lift.holder = to;
    lift.copy = false;
    lift.key = to.keyOf(toItems[home], home);
    lift.item = toItems[home];
    lift.index = home;
    const rest = [...fromItems];
    rest.splice(i, 1);
    from.write(rest);
    from.emit('remove', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: i,
      newIndex: -1
    });
    from.setLifted(null);
    to.setLifted(home);
    say(to, 'movedToList', data, home, el, toItems.length, from);
    to.focusRow(toItems[home], home);
    return;
  }
  // The first hop out of a clone source (`pull: 'clone'`) leaves the source
  // untouched and carries a copy (the same item value the mouse path
  // inserts); from then on the copy moves like any row.
  const cloneOut = canHop(from.group(), to.group()).copy && from === origin.list && !lift.copy;
  const at = dir === 1 ? 0 : toItems.length;
  // Update the lift BEFORE writing, so a target whose watchers run
  // synchronously on a write already sees the new holder.
  lift.holder = to;
  lift.key = to.keyOf(data, at);
  lift.index = at;
  lift.hopped = true;
  if (cloneOut) {
    lift.copy = true;
  } else {
    const rest = [...fromItems];
    rest.splice(i, 1);
    from.write(rest);
  }
  const next = [...toItems];
  next.splice(at, 0, data);
  to.write(next);
  // The destination has not rendered its new row yet: `el` is the row the
  // move started from. `add` (destination) before `remove` (source), as by
  // mouse.
  to.emit('add', {
    interaction: 'keyboard',
    item: data,
    el,
    from: from.el,
    to: to.el,
    oldIndex: -1,
    newIndex: at
  });
  if (!cloneOut) from.emit('remove', {
    interaction: 'keyboard',
    item: data,
    el,
    from: from.el,
    to: to.el,
    oldIndex: i,
    newIndex: -1
  });
  from.setLifted(null);
  to.setLifted(at);
  say(to, 'movedToList', data, at, el, toItems.length + 1, from);
  to.focusRow(data, at);
};
// End the active keyboard lift. 'drop' leaves the row where it is ('off' too,
// announced as `Lift ended`: the holder's keyboard was turned off); 'cancel'
// returns it to the list and position it was lifted from (after hops, a
// reverse hand-off with its own `remove` / `add`; a clone copy is removed).
// Emits `end` once, from the list the row ends up in.
const endLift = (kind: any) => {
  const lift = registry.lift;
  if (!lift) return;
  const h = lift.holder;
  const origin = lift.origin;
  const at = registry.indexOfLift();
  if (at < 0) {
    loseLift();
    return;
  }
  const items = h.items();
  const item = items[at];
  // The lifted row's element, read before any write below. Right after a hop
  // the holder may not have rendered it yet: its label is read from the
  // lifted row element then.
  const el = h.rowEl(at);
  const row = el ?? lift.liftedRowEl;
  if (kind === 'drop' || kind === 'off') {
    // A row that hopped always names its list, even back in its origin. The
    // keyboard turned off mid-lift ('off') ends it where it is, too.
    if (kind === 'off') say(h, 'liftEnded', item, at, row);else say(h, lift.hopped ? 'droppedInList' : 'dropped', item, at, row, items.length);
    h.setLifted(null);
    registry.lift = null;
    keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
    return;
  }
  if (h !== origin.list && !registry.has(origin.list) && lift.copy) {
    // A clone copy is removed on cancel even when its source list has
    // unmounted (the source never gave its item up). Focus moves to the
    // neighbouring row, if any. The lift ends BEFORE the write: the copy is
    // leaving on purpose, and a target whose items watcher runs synchronously
    // on the write (Solid) must not take it for a lost lift (a second `end`).
    registry.lift = null;
    const rest = [...items];
    rest.splice(at, 1);
    h.write(rest);
    h.emit('remove', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: h.el,
      oldIndex: at,
      newIndex: -1
    });
    h.setLifted(null);
    say(h, 'cancelledRemoved', item, at, row);
    if (rest.length > 0) {
      const k = Math.min(at, rest.length - 1);
      h.focusRow(rest[k], k);
    }
    // The copy is gone, so there is no row: `el: null`.
    const fromEl = origin.list.el;
    registry.deferEnd((host: any) => host.emit('end', {
      interaction: 'keyboard',
      item,
      el: null,
      from: fromEl,
      to: h.el,
      oldIndex: origin.index,
      newIndex: -1
    }), h, origin.list);
    return;
  }
  if (h !== origin.list && (!registry.has(origin.list) || !isRenderable(origin.list.el) || !origin.list.keyboardEnabled())) {
    // The origin list has unmounted, is hidden, or has its keyboard off:
    // there is nowhere to return to (focus would be stranded), so the row
    // stays where it is (the lift ends as a drop at its position).
    say(h, 'cancelledStays', item, at, row, items.length);
    h.setLifted(null);
    registry.lift = null;
    keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
    return;
  }
  if (h === origin.list) {
    const to = Math.max(0, Math.min(items.length - 1, origin.index));
    if (to !== at) {
      const next = [...items];
      next.splice(at, 1);
      next.splice(to, 0, item);
      lift.key = h.keyOf(item, to);
      h.write(next);
      h.focusRow(item, to);
      h.emit('reorder', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: h.el,
        oldIndex: at,
        newIndex: to
      });
    }
    say(h, lift.hopped ? 'cancelledReturnedToList' : 'cancelledReturned', item, to, row, items.length);
    h.setLifted(null);
    registry.lift = null;
    keyboardStartEnd('end', lift, origin.list, h, origin.index, to, el);
    return;
  }
  // Reverse hand-off from the current holder back to the origin list.
  const home = origin.list;
  const homeItems = home.items();
  let back;
  if (lift.copy) {
    // The clone source never gave its item up: drop the copy, focus the
    // original.
    back = homeItems.indexOf(item);
    if (back < 0) back = Math.max(0, Math.min(homeItems.length - 1, origin.index));
  } else {
    back = Math.min(origin.index, homeItems.length);
  }
  lift.holder = home;
  lift.key = home.keyOf(item, back);
  const rest = [...items];
  rest.splice(at, 1);
  h.write(rest);
  if (!lift.copy) {
    const next = [...homeItems];
    next.splice(back, 0, item);
    home.write(next);
    // `add` (destination) before `remove` (source), as by mouse.
    home.emit('add', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: home.el,
      oldIndex: -1,
      newIndex: back
    });
  }
  h.emit('remove', {
    interaction: 'keyboard',
    item,
    el,
    from: h.el,
    to: home.el,
    oldIndex: at,
    newIndex: -1
  });
  h.setLifted(null);
  // `home` holds the lift during its write, so a target whose items watcher
  // runs synchronously on the write (Solid) highlighted the row there: clear it.
  home.setLifted(null);
  say(home, 'cancelledReturnedToList', item, back, row, homeItems.length + (lift.copy ? 0 : 1));
  home.focusRow(lift.copy ? homeItems[back] : item, back);
  registry.lift = null;
  keyboardStartEnd('end', lift, home, home, origin.index, back, lift.copy ? home.rowEl(back) : el);
};
// This list's keyboard was turned off (`disabled`, `disableKeyboard`, or
// `option('disabled', true)`): a lift it holds ends where the row is, with
// its `end`.
const endLiftIfHeld = () => {
  const lift = registry.lift;
  if (lift != null && lift.holder === entry) endLift('off');
};
// In row mode the rows leave the tab order when the keyboard turns off, and a
// focused element that stops being focusable drops focus to <body>. If one of
// this list's rows still has focus (a target whose watcher runs before its DOM
// update), move it to the list itself (out of the tab order), like an emptied
// list. Once the DOM update has run, the `focusout` listener added in $onMount
// does it instead.
const keepFocusOffBody = () => {
  const listEl = entry ? entry.el : null;
  if (!listEl) return;
  const root: any = listEl.getRootNode();
  const a: any = root != null ? root.activeElement : null;
  if (a == null || a.parentNode !== listEl || !a.classList.contains('rozie-sortable-item')) return;
  if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
  listEl.focus();
};
const keyboardTurnedOff = () => {
  endLiftIfHeld();
  keepFocusOffBody();
};
// Lift the row at `index` of this list.
const startLift = (index: any) => {
  if (!entry) return;
  // A previous drag's or lift's `end` that is still pending fires first, so
  // every `end` comes before the next `start`.
  registry.flushEnds();
  const item = items.value[index];
  registry.lift = {
    holder: entry,
    key: entry.keyOf(item, index),
    item,
    copy: false,
    hopped: false,
    origin: {
      list: entry,
      index
    },
    liftedRowEl: entry.rowEl(index),
    index
  };
  liftedIndex.value = index;
  say(entry, 'lifted', item, index, registry.lift.liftedRowEl, items.value.length);
  keyboardStartEnd('start', registry.lift, entry, entry, index, index);
};
const onRowKeyDown = ($event: any, index: any) => {
  // Origin guard — must run FIRST, before the keyboardEnabled() check.
  //  - handle mode (keyboardTrigger='handle'): reorder keys apply ONLY when the
  //    keydown came from inside this row's `handle` element. A missing `handle`
  //    selector means keyboard is OFF (warned in warnIfHandleMissing).
  //  - row mode (quick 260716-ggq): reorder keys apply ONLY when the row
  //    element ITSELF is focused. A slotted interactive child (an <input>,
  //    <button>, etc. rendered into the row's default slot) bubbles its own
  //    keydown up to this handler — without this guard, Space/Enter typed into
  //    that child would be hijacked for lift/drop instead of reaching the
  //    child.
  if (handleMode()) {
    if (handleSelector() == null || !isHandleKeyOrigin($event)) return;
  } else if ($event.target !== $event.currentTarget) {
    return;
  }
  // Defense-in-depth: when keyboard reordering is off the rows carry no
  // tabindex and can't receive focus, but a consumer-focused row (or a
  // programmatic .focus()) must still no-op here rather than reorder.
  if (!keyboardEnabled()) return;
  // While a lift exists, reorder keys in the list holding it act on it. A key
  // from ANOTHER list of the holder's group is routed to the holder only when
  // it comes from the lifted row element itself (its old row, still there
  // before the frameworks re-render after a hop; compared by element, so a
  // row of another list that shares the lifted row's key is not it) or while a refocus after a move is
  // outstanding (a fast burst). Any other row — and every row of an unrelated
  // list (another group, or none) — keeps single-list behaviour: Space/Enter
  // there drops the foreign lift and lifts its own row, other keys do nothing.
  const lift = registry.lift;
  const key = $event.key;
  if (lift != null) {
    const mine = groupNameOf(effectiveGroup());
    const sameGroup = mine != null && mine === groupNameOf(lift.holder.group());
    const fromLiftedRow = lift.liftedRowEl != null && $event.currentTarget === lift.liftedRowEl;
    if (lift.holder === entry || sameGroup && (fromLiftedRow || lift.focusPending === true)) {
      if (lift.holder.onKey(key, !!$event.shiftKey)) $event.preventDefault();
      return;
    }
  }
  // Space (' ' on browsers; KeyboardEvent.key === ' ') OR Enter — lift. A row
  // the mouse can't drag (it matches `filter`, or not `draggable`) can't be
  // lifted either: the key is left alone (not prevented).
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    const rules = {
      filter: liveOption('filter', props.filter),
      draggable: liveOption('draggable', undefined),
      sortable: instance
    };
    if (!rowLiftable($event.currentTarget as any, rules)) return;
    $event.preventDefault();
    if (lift != null) endLift('drop');
    startLift(index);
  }
};
// The group NAME of a SortableJS group option (string or object form).
const groupNameOf = (g: any) => g == null ? null : typeof g === 'string' ? g : g.name ?? null;
// A reorder key for the lift THIS list holds (routed here from any list via
// the registry entry's onKey). Returns true when the key was handled. Every
// key except Space/Enter acts only while lifted, so it never steals keys from
// fields inside a row.
const holderKey = (key: any, shift: any) => {
  const lift = registry.lift;
  if (lift == null || lift.holder !== entry) return false;
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    endLift('drop');
    return true;
  }
  if (key === 'Escape') {
    endLift('cancel');
    return true;
  }
  const horizontal = props.orientation === 'horizontal';
  const prevKey = horizontal ? 'ArrowLeft' : 'ArrowUp';
  const nextKey = horizontal ? 'ArrowRight' : 'ArrowDown';
  if (shift && (key === nextKey || key === prevKey)) {
    // Hopping is on wherever a group is set; an ungrouped list ignores it.
    if (effectiveGroup() == null) return false;
    hop(key === nextKey ? 1 : -1);
    return true;
  }
  const from = registry.indexOfLift();
  if (from < 0) {
    loseLift();
    return false;
  }
  // pageStep below 1 (or not a number) still moves by at least one position.
  const step = Math.max(1, Math.floor(Number(props.pageStep) || 1));
  let to: any = null;
  if (key === nextKey) to = from + 1;else if (key === prevKey) to = from - 1;else if (key === 'Home') to = 0;else if (key === 'End') to = entry.items().length - 1;else if (key === 'PageDown') to = from + step;else if (key === 'PageUp') to = from - step;
  if (to === null) return false;
  // `sort: false`: no moves within the list (as by mouse). The key is still
  // taken, so it does not scroll the page while a row is lifted, and says why
  // nothing moved.
  if (liveOption('sort', true) === false) {
    say(entry, 'notSortable', entry.items()[from], from, entry.rowEl(from) ?? lift.liftedRowEl);
    return true;
  }
  moveLiftTo(to, key === prevKey || key === 'Home' || key === 'PageUp' ? -1 : 1);
  return true;
};
// A key pressed while focus has fallen to <body> during a lift. A hop removes
// the focused row from one list and the destination may render (and take
// focus) only after the handler returns (Angular), so the next key of a fast
// burst can reach <body>. The list holding the lift handles it as if it had
// landed on the lifted row, then puts focus back on that row.
//
// Only while a refocus of ours is outstanding (`focusPending`): focus that left
// the lifted row for any other reason (the user clicked elsewhere or tabbed
// away) keeps today's behaviour, and those keys are not ours. Modified keys
// and keys someone already handled are never taken.
const onStrayKey = (ev: any) => {
  const lift = registry.lift;
  if (lift == null || lift.holder !== entry || !lift.focusPending) return;
  if (ev.defaultPrevented || ev.ctrlKey || ev.metaKey || ev.altKey) return;
  const t = ev.target;
  if (t !== document.body && t !== document.documentElement) return;
  const item = lift.item;
  const at = registry.indexOfLift();
  if (!holderKey(ev.key, !!ev.shiftKey)) return;
  ev.preventDefault();
  const now = registry.lift;
  if (now != null) now.holder.focusRow(now.item, registry.indexOfLift());else if (at >= 0) entry.focusRow(item, at);
};

// SortableJS wiring lives in `useSortableJS()` (./internal/useSortableJS).
// The helper owns the SortableJS-vs-reconciler dance — DOM-restore hardening
// against fragile-event paths, identity-based item lookup over fragile
// `e.oldIndex`, and the single-onEnd disambiguation that collapses
// onUpdate / onAdd / onRemove into one handler.
//
// What stays here is purely declarative: which array to read, what to write
// back, what to emit, and how to bridge `afterCommit` to the Lit-only
// `$reconcileAfterDomMutation()` sigil.
// `options.group` wins over `group` / `cloneable` (see effectiveGroup), for
// the mouse as for the keyboard.
// A group change can change which lists can take each other's rows: every
// list rechecks its Shift instructions.
const applyGroup = () => {
  instance?.option('group', effectiveGroup());
  registry.notifyPeers();
};
// Imperative handle (Phase 21 $expose). The SortableJS imperative surface a
// consumer can't drive through props alone — exposed uniformly to all 6 targets.
// Each guards the pre-mount/destroyed `instance = null`. Collision-clear: none of
// the 4 verb names collide with the 16 props or the 5 events — `option` is a
// distinct identifier from the `options` prop, so ROZ121 is clear.
function getInstance() {
  return instance;
}
// toArray()/sort() use the rows' data-id keys — every row carries
// :data-id="keyFor(item, index)", so toArray() returns the current key order
// (set itemKey for stable object-list keys).
function toArray() {
  return instance ? instance.toArray() : [];
}
// sort(order) reorders the bound items by those keys and writes them back
// (the framework re-renders the rows; SortableJS never moves them behind the
// model). Listed keys come first, in order; the rest follow in their order. No
// event fires: it is the consumer's own call. With `useAnimation` (and a
// non-zero `animation`) the rows slide from where they were.
function sort(order: any, useAnimation = true) {
  const list = items.value;
  const next = orderByKeys(list, order ?? [], keyFor);
  if (next.every((item: any, i: any) => item === list[i])) return;
  const animate = useAnimation && instance != null;
  if (animate) instance.captureAnimationState();
  items.value = next;
  if (animate) {
    const sortable = instance;
    afterFlush(() => sortable.animateAll());
  }
}
// option(name) reads a live SortableJS option; option(name, value) sets one — the
// runtime escape hatch for any SortableJS option beyond the curated props.
// Setting `disabled`, `filter`, `draggable` or `sort` also applies to the
// keyboard; `option('disabled', true)` mid-lift ends the lift this list holds.
// A runtime `animation` is kept over later `animation` prop changes.
function option(name: any, value: any) {
  if (!instance) return undefined;
  if (value === undefined) return instance.option(name);
  instance.option(name, value);
  if (TRACKED_OPTIONS.includes(name)) setOverride(name, value);
  if (name === 'disabled' && value) keyboardTurnedOff();
  // After the re-render, so every list reads the new group (React reads
  // state as of its last render).
  if (name === 'group') afterFlush(() => registry.notifyPeers());
  return value;
}

let _cleanup_0: (() => void) | undefined;
onMounted(() => {
  // Kept across a Lit element's disconnect and reconnect (mount runs again).
  if (instructionsId.value == null) instructionsId.value = nextInstructionsId();
  warnIfHandleMissing();
  // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
  // when the options object below references it.
  const sortable = useSortableJS(listElRef.value!, {
    items: () => items.value,
    onCommit: (next: any) => {
      items.value = next;
    },
    options: {
      animation: props.animation,
      disabled: props.disabled,
      group: resolveGroup(),
      handle: props.handle,
      ghostClass: props.ghostClass,
      chosenClass: props.chosenClass,
      dragClass: props.dragClass,
      filter: props.filter,
      forceFallback: props.forceFallback,
      swapThreshold: props.swapThreshold,
      easing: props.easing,
      ...props.options
    },
    // Lit lit-html `repeat` directive caches its part array by sentinel-
    // comment node identity; SortableJS's physical DOM mutation desyncs
    // that cache. The sigil lowers to `__rozieReconcileAfterDomMutation(this)`
    // on Lit (real call) and `void 0` on the other 5 targets (no-op).
    afterCommit: () => void 0,
    // Every pointer event carries the same payload as the keyboard ones, with
    // item-row indices and the raw SortableJS event as `originalEvent`.
    onChange: (c: any) => {
      const payload = {
        interaction: 'pointer' as const,
        item: c.item,
        el: c.el,
        from: c.from,
        to: c.to,
        oldIndex: c.oldIndex,
        newIndex: c.newIndex,
        originalEvent: c.event
      };
      if (c.kind === 'reorder') emit('reorder', payload);else if (c.kind === 'add') emit('add', payload);else if (c.kind === 'remove') emit('remove', payload);
    },
    onStart: (d: any) => {
      // A pointer drag ends any active keyboard lift first.
      if (registry.lift != null) endLift('drop');
      // That lift's `end` (pending until a task) comes before this `start`.
      registry.flushEnds();
      emit('start', {
        interaction: 'pointer',
        item: d.item,
        el: d.el,
        from: d.from,
        to: d.to,
        oldIndex: d.oldIndex,
        newIndex: d.newIndex,
        originalEvent: d.event
      });
    },
    // `end` comes from the list the row ended up in: the destination when it
    // is a SortableList, else (dropped outside, or into a SortableJS list
    // that isn't one of ours) this source list. It goes through the
    // registry's `deferEnd`, like a keyboard `end`: it fires in a task after
    // every list involved has written its items and the re-render those
    // writes scheduled, and before the next drag's or lift's `start`. An
    // unmounted list never emits: if the destination has unmounted by then
    // (in its own `add` handler, say), this list (the origin, which emitted
    // `start`) emits it, `to` still the destination; if both are gone,
    // nothing is emitted.
    scheduleEnd: (d: any) => {
      const dest = registry.entryFor(d.to);
      const destGone = dest == null && d.to !== d.from && registry.wasList(d.to);
      registry.deferEnd((host: any) => {
        const row = d.item === undefined || host.el !== d.to ? null : rowByKey(d.to, host.keyOf(d.item, d.newIndex));
        host.emit('end', {
          interaction: 'pointer',
          item: d.item,
          el: row ?? liveEl(d.el),
          from: d.from,
          to: d.to,
          oldIndex: d.oldIndex,
          newIndex: d.newIndex,
          originalEvent: d.event
        });
      }, destGone ? null : dest ?? entry, entry);
    }
  });
  instance = sortable.instance;
  appliedOptions = props.options;
  // Runtime `option(name, v)` values this list remembers (Lit keeps them when
  // the element is moved in the DOM and mounts again) apply to the new
  // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
  // first mount.
  const remembered: any = optionOverrides.value;
  if (remembered != null) {
    for (const name of Object.keys(remembered) as any) instance.option(name, remembered[name]);
  }
  const listEl = listElRef.value;
  const stopNative = (ev: any) => {
    if (ev.target === listEl) ev.stopPropagation();
  };
  for (const name of SORTABLE_DOM_EVENTS as any) listEl?.addEventListener(name, stopNative);
  // A focused row that stops being focusable (its tabindex goes when the
  // keyboard turns off) is blurred at once, during the framework's DOM
  // update, with focus going nowhere (`relatedTarget` null): it would land on
  // <body>. Move it to the list instead.
  const rowBlurred = (ev: any) => {
    if (listEl == null) return;
    const row: any = ev.target;
    if (ev.relatedTarget != null || row == null || row.parentNode !== listEl) return;
    if (!row.classList.contains('rozie-sortable-item') || row.hasAttribute('tabindex') || !row.isConnected) return;
    if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
    listEl.focus();
  };
  listEl?.addEventListener('focusout', rowBlurred);
  unhookNativeEvents = () => {
    for (const name of SORTABLE_DOM_EVENTS as any) listEl?.removeEventListener(name, stopNative);
    listEl?.removeEventListener('focusout', rowBlurred);
  };

  // Register with the keyboard registry. Other instances call these methods
  // when a keyboard lift hands a row between lists.
  entry = {
    el: listEl,
    group: () => effectiveGroup(),
    label: () => props.listLabel,
    // A handle-mode list without a handle selector has its keyboard off.
    keyboardEnabled: () => keyboardEnabled() && !(handleMode() && handleSelector() == null),
    items: () => items.value,
    keyOf: (item: any, i: any) => String(keyFor(item, i)),
    labelOf: (item: any, i: any, row: HTMLElement | null = null) => String(labelOf(item, i, row)),
    message: (kind: any, ctx: any) => announcementText(props.announcements, kind, ctx),
    onKey: (key: any, shift: any) => holderKey(key, shift),
    write: (next: any) => {
      items.value = next;
    },
    setLifted: (i: any) => {
      liftedIndex.value = i;
    },
    // The same text twice in a row would not change the region, and a screen
    // reader would not read it again ("Apple is already first", twice): a
    // repeat alternates a trailing no-break space, which is not spoken.
    announce: (text: any) => {
      const next = text !== '' && text === lastSpoken ? text + '\u00A0' : text;
      lastSpoken = next;
      ariaLiveText.value = next;
    },
    focusRow: (item: any, i: any) => refocusRow(item, i),
    focusNear: (i: any) => focusNearRow(i),
    rowEl: (i: any) => {
      const list = items.value;
      if (i < 0 || i >= list.length) return null;
      return rowByKey(listEl, String(keyFor(list[i], i)));
    },
    // Always set (an equal value is a no-op on every target): a compare
    // against $data would read React's render-time ref, stale when two peer
    // changes land in one commit (one list unmounts, another mounts).
    peersChanged: (v: any) => {
      hasHopPeer.value = v;
    },
    emit: (name: any, payload: any) => {
      if (name === 'add') emit('add', payload);else if (name === 'remove') emit('remove', payload);else if (name === 'reorder') emit('reorder', payload);else if (name === 'start') emit('start', payload);else if (name === 'end') emit('end', payload);
    }
  };
  unregisterEntry = registry.register(entry);
  const strayKey = (ev: any) => onStrayKey(ev);
  // A pointer press means the user moved on: keys lost to <body> after it
  // are not routed to the lift.
  const pointerPress = () => {
    if (registry.lift != null) registry.lift.focusPending = false;
  };
  document.addEventListener('keydown', strayKey);
  document.addEventListener('pointerdown', pointerPress, true);
  unhookStrayKeys = () => {
    document.removeEventListener('keydown', strayKey);
    document.removeEventListener('pointerdown', pointerPress, true);
  };
  // $onMount's cleanup-return: closing over a setup-local (`sortable`) does
  // not survive the Solid emitter's setup/cleanup split — it scopes cleanup
  // outside the setup IIFE. Closing over `instance` / `unregisterEntry`
  // (module-scope `let`s) works on every target.
  _cleanup_0 = () => {
    instance?.destroy();
    // Unmounting while holding a keyboard lift ends it (its `end` comes from
    // the origin list, if that one is still mounted).
    if (registry.lift != null && registry.lift.holder === entry) loseLift(true);
    unregisterEntry?.();
    unregisterEntry = null;
    unhookNativeEvents?.();
    unhookNativeEvents = null;
    unhookStrayKeys?.();
    unhookStrayKeys = null;
  };
});
onBeforeUnmount(() => { _cleanup_0?.(); });

watch(() => props.disabled, (v: any) => {
  instance?.option('disabled', v);
  setOverride('disabled', v);
}, { flush: 'post' });
watch(() => props.animation, (v: any) => instance?.option('animation', liveOption('animation', v)), { flush: 'post' });
watch(() => props.options, () => {
  if (!instance) return;
  const next = props.options;
  const base = {
    animation: props.animation,
    disabled: props.disabled,
    group: resolveGroup() ?? null,
    handle: props.handle,
    ghostClass: props.ghostClass,
    chosenClass: props.chosenClass,
    dragClass: props.dragClass,
    filter: props.filter,
    swapThreshold: props.swapThreshold,
    easing: props.easing,
    sort: true,
    draggable: ROW_DRAGGABLE
  };
  // A fresh inline function with the same content (React re-renders) is
  // applied so SortableJS runs the newest closure, but it is no change: a
  // runtime `option(name, v)` still in force keeps winning over it.
  const applied = reapplyOptions(instance, appliedOptions, next, base, {
    keep: (key: any, prev: any) => {
      const ov: any = optionOverrides.value;
      return ov != null && Object.prototype.hasOwnProperty.call(ov, key) && ov[key] !== prev;
    },
    refreshed: (key: any) => {
      if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key));
    }
  });
  appliedOptions = next;
  for (const key of applied as any) {
    // The keyboard reads the value SortableJS now runs with. A remembered
    // runtime `animation` / `handle` / `group` is superseded by the newer
    // `options` value.
    if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key));else if (TRACKED_OPTIONS.includes(key)) clearOverride(key);
  }
  if (applied.includes('group')) registry.notifyPeers();
}, { flush: 'post' });
watch(() => [props.disabled, props.disableKeyboard, props.options, optionOverrides.value], () => {
  if (!keyboardEnabled()) keyboardTurnedOff();
}, { flush: 'post' });
watch(() => props.group, () => applyGroup(), { flush: 'post' });
watch(() => props.cloneable, () => applyGroup(), { flush: 'post' });
watch(() => props.swapThreshold, (v: any) => instance?.option('swapThreshold', v), { flush: 'post' });
watch(() => props.handle, (v: any) => {
  instance?.option('handle', liveOption('handle', v));
  warnIfHandleMissing();
}, { flush: 'post' });
watch(() => props.keyboardTrigger, () => warnIfHandleMissing(), { flush: 'post' });
watch(() => props.ghostClass, (v: any) => instance?.option('ghostClass', v), { flush: 'post' });
watch(() => props.chosenClass, (v: any) => instance?.option('chosenClass', v), { flush: 'post' });
watch(() => props.dragClass, (v: any) => instance?.option('dragClass', v), { flush: 'post' });
watch(() => props.filter, (v: any) => {
  instance?.option('filter', v);
  setOverride('filter', v);
}, { flush: 'post' });
watch(() => props.easing, (v: any) => instance?.option('easing', v), { flush: 'post' });
watch(() => items.value, () => {
  const lift = registry.lift;
  if (lift == null || lift.holder !== entry) return;
  const i = registry.indexOfLift();
  if (i < 0) {
    loseLift();
    return;
  }
  if (liftedIndex.value !== i) liftedIndex.value = i;
  // Once the holder has rendered the lifted row, that is the lifted row
  // element. After a hop this drops the source's old row, which the source
  // may reuse for another item (index keys).
  const row = entry.rowEl(i);
  if (row != null) lift.liftedRowEl = row;
  focusNearRow(i, lift.key);
}, { flush: 'post' });

defineExpose({ getInstance, toArray, sort, option });
</script>

<style scoped>
.rozie-sortable-wrap { display: block; }
.rozie-sortable-list { display: block; }
.rozie-sortable-item { display: block; outline: none; }
.rozie-sortable-item:focus-visible { outline: 2px solid var(--rozie-sortable-list-ring, #1a73e8); outline-offset: -2px; }
.rozie-sortable-item-lifted {
  background: rgba(26, 115, 232, 0.1);
  box-shadow: 0 0 0 3px var(--rozie-sortable-list-ring, #1a73e8) inset;
}
.rozie-sortable-aria-live {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
</style>
tsx
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { flushSync } from 'react-dom';
import { clsx, parseInlineStyle, rozieAttr, rozieDisplay, useControllableState } from '@rozie/runtime-react';
import './SortableList.css';
import { ROW_DRAGGABLE, orderByKeys, reapplyOptions, useSortableJS } from './internal/useSortableJS';
import { afterFlush, canHop, getKeyboardRegistry, isRenderable, nextInstructionsId, rowLiftable } from './internal/keyboardRegistry';
import { announcementText, defaultInstructions, fallbackLabel } from './internal/announcements';

/** The kind of message the list speaks during keyboard reordering (a key of the `announcements` prop). */
export type AnnouncementKind = 'lifted' | 'moved' | 'movedToList' | 'dropped' | 'droppedInList' | 'atStart' | 'atEnd' | 'notSortable' | 'noListBefore' | 'noListAfter' | 'cancelledReturnedToList' | 'cancelledReturned' | 'cancelledStays' | 'cancelledRemoved' | 'liftEnded';
/** What an `announcements` function receives. */
export interface AnnouncementContext {
  /** The row's screen-reader label (`labelFor`, else `item.label`, else the row's text). */
  label: string;
  /** The item value. */
  item: unknown;
  /** The name of the list the message is about (`listLabel`, or `list 2 of 3`). */
  list: string;
  /** 1-based position of the row in `list` (kinds that have a position). */
  position?: number;
  /** How many rows `list` holds (kinds that have a position). */
  total?: number;
  /** The list the row came from (`movedToList` only). */
  fromList?: string;
}
/** The `announcements` prop: one optional function per message kind; `null` or `''` says nothing. */
export type Announcements = Partial<Record<AnnouncementKind, (ctx: AnnouncementContext) => string | null | undefined>>;
/** The payload every `start` / `end` / `reorder` / `add` / `remove` event carries, for pointer and keyboard alike. */
export interface SortablePayload {
  /** Which input made the change. */
  interaction: 'pointer' | 'keyboard';
  /** The item's data value (never an element). */
  item: unknown;
  /** The row element; null when there is none (a lost lift, a removed clone copy). */
  el: HTMLElement | null;
  /** The list element the row came from. */
  from: HTMLElement;
  /** The list element the row went to. */
  to: HTMLElement;
  /** Item-row index in `from`; -1 for `add`. */
  oldIndex: number;
  /** Item-row index in `to`; -1 for `remove` and a lost lift. */
  newIndex: number;
  /** Pointer only: the raw SortableJS event. */
  originalEvent?: unknown;
}
/** Which element drives keyboard reordering (the `keyboardTrigger` prop). */
export type SortableKeyboardTrigger = 'row' | 'handle';
/** Which arrow keys move a lifted row within the list (the `orientation` prop). */
export type SortableOrientation = 'vertical' | 'horizontal';

interface ChildrenCtx { item: any; index: any; instructionsId: any; }

interface SortableListProps extends Omit<import('react').ComponentPropsWithoutRef<'div'>, 'items' | 'defaultItems' | 'onItemsChange' | 'itemKey' | 'handle' | 'group' | 'animation' | 'disabled' | 'disableKeyboard' | 'keyboardTrigger' | 'options' | 'labelFor' | 'ghostClass' | 'chosenClass' | 'dragClass' | 'filter' | 'easing' | 'forceFallback' | 'swapThreshold' | 'cloneable' | 'listClass' | 'itemClass' | 'listLabel' | 'orientation' | 'pageStep' | 'keyboardInstructions' | 'announcements' | 'itemStyle' | 'onReorder' | 'onAdd' | 'onRemove' | 'onStart' | 'onEnd' | 'renderHeader' | 'children' | 'renderFooter' | 'slots' | 'dangerouslySetInnerHTML'> {
  /**
   * The bound items array. The sole `model: true` prop — two-way bind it (`r-model:items` / `v-model:items` / `bind:items` / `[(items)]`) and SortableList writes the re-ordered array back whenever a drag, cross-list move, or keyboard reorder commits, with no manual `onChange → setState` wiring.
   * @example
   * <SortableList items={todos} onItemsChange={setTodos} itemKey="id" />
   */
  items?: any[];
  defaultItems?: any[];
  onItemsChange?: (items: any[]) => void;
  /**
   * The per-row key the framework reconciler tracks each item by across a reorder — either a property name (e.g. `itemKey="id"` reads `item.id`) or an `(item, index) => key` function. With neither, id-less object items get a stable synthetic key via an internal `WeakMap` (survives reorder by object identity); primitive items fall back to index — pass a function for reorderable duplicate primitives.
   */
  itemKey?: (string | ((...args: any[]) => any)) | null;
  /**
   * CSS selector identifying the per-row drag handle, so a drag starts only from that element rather than anywhere in the row. Authored class names render literally on every target (React included), so a plain `.grip` works; `$classSelector('grip')` is an optional, typo-checked way to author it. `options.handle` and `option('handle', v)` win over this prop, for the keyboard (`keyboardTrigger: 'handle'`) as for the mouse.
   */
  handle?: (string) | null;
  /**
   * SortableJS group name enabling cross-list drag — two lists sharing a `group` accept items between each other (the source fires `remove`, the destination fires `add`). Set `cloneable: true` to flip a string group into clone-mode. Lists that share a `group` also exchange rows by keyboard: Shift+arrow while a row is lifted hops it to the previous or next list of the same group (in source order), subject to the same pull/put rules as a mouse drag. `options.group` takes precedence over this prop, for keyboard hops as for drags. Function-valued `pull`/`put` cannot be evaluated without a drag, so those lists are unreachable by keyboard. Set `itemKey` on grouped lists.
   */
  group?: (string) | null;
  /**
   * Reorder animation duration in milliseconds. `0` disables the animation. Reapplied live via `instance.option('animation', v)` (no remount). `options.animation`, and a runtime `option('animation', v)`, win over this prop.
   */
  animation?: number;
  /**
   * Temporarily disable dragging without unmounting — reapplied live via `instance.option('disabled', v)` (no remount). Also suppresses keyboard reordering: a disabled list is not sortable by any input, so rows lose their `tabindex` and the keydown handler no-ops. Turning it on while a row is lifted ends the lift where the row is (`Lift ended`, and `end` fires); `options.disabled` and `option('disabled', v)` do the same.
   */
  disabled?: boolean;
  /**
   * Opt out of keyboard reordering (Space lift / Arrow move / Shift+Arrow hop between lists / Esc cancel / Enter drop) while leaving pointer drag enabled. Rows drop out of the tab order (no `tabindex`) and the keydown handler no-ops. Keyboard access is gated on `!disabled && !disableKeyboard`. Turning it on while a row is lifted ends the lift where the row is.
   */
  disableKeyboard?: boolean;
  /**
   * Which element drives keyboard reordering. `'row'` (default): rows are tab stops and the keys on the focused row drive reordering. `'handle'`: rows are NOT tab stops, and only keys pressed inside the element matched by `handle` (inside that row) drive the same Space/Enter lift-drop, Arrow move, Shift+Arrow hop and Escape cancel flow; handled keys call preventDefault so a handle `<button>`'s click does not fire. The consumer owns the handle markup (recommended: a `<button>` with its own aria-label such as "Reorder Hero banner") and the component adds no tabindex or role to slot content. `'handle'` without `handle` turns keyboard reordering off and logs a console warning. `disabled`/`disableKeyboard` still apply. Typed as `SortableKeyboardTrigger` (`'row' | 'handle'`); at runtime any value other than `'handle'` behaves as `'row'`.
   */
  keyboardTrigger?: SortableKeyboardTrigger;
  /**
   * Verbatim SortableJS options pass-through for anything not covered by the named props. The named props win on key conflict but `options` lands AFTER them in the merge so consumers can override defaults; handler keys (`onStart`, `onEnd`, `onUpdate`, `onAdd`, `onRemove`, `onClone`) are stripped — the helper owns those paths. Runtime-updatable: when `options` changes, each key whose value changed is reapplied via `instance.option(key, v)` (no remount), so mouse and keyboard obey the same values; a key you drop goes back to its named prop (or, for `sort` and `draggable`, the component default), and any other dropped key keeps its last value until you set it. `forceFallback` is still read only at construction.
   */
  options?: Record<string, any>;
  /**
   * Optional `(item, idx) => string` returning the screen-reader label for the aria-live announcer during keyboard drag. Defaults to `item.label`; without a `label` field, the row's text (whitespace collapsed, without nested lists or hidden content), else `String(item)` for a primitive, else `item {position}`.
   */
  labelFor?: ((...args: any[]) => any) | null;
  /**
   * Class name applied to the drop-placeholder (ghost) element while dragging. Forwarded live via `instance.option`, so toggling it at runtime takes effect without a remount.
   */
  ghostClass?: (string) | null;
  /**
   * Class name applied to the currently-chosen item while dragging. Forwarded live via `instance.option` (no remount needed to change it).
   */
  chosenClass?: (string) | null;
  /**
   * Class name applied to the dragging element. Only takes effect in fallback mode (`forceFallback: true`). Forwarded live via `instance.option`.
   */
  dragClass?: (string) | null;
  /**
   * CSS selector that prevents drag initiation on matching rows (locked items). SortableJS checks it at `mousedown`/`touchstart` and aborts the drag if it matches. The keyboard honours it too: a row that matches (the row element, or its slot root: the row template's single element when nothing else sits beside it) cannot be lifted with Space/Enter; any other matching control (a `.js-remove` button, an `input`) blocks only presses on itself. `options.filter` (which may also be a SortableJS filter function) takes precedence. A `data-*` attribute selector (e.g. `[data-locked]`) is the most robust choice across all targets.
   */
  filter?: (string) | null;
  /**
   * CSS easing function for the reorder animation (e.g. `'ease-in'`, `'cubic-bezier(0.4, 0, 0.2, 1)'`). Runtime-updatable.
   */
  easing?: (string) | null;
  /**
   * Force SortableJS's mouse-event drag path over HTML5 DnD — useful for touch devices, consistent cross-browser behavior, and synthetic test drivers (and `dragClass` only applies in this mode). **Construction-time only**: SortableJS reads it once at construction, so re-key the `<SortableList>` to toggle it at runtime.
   */
  forceFallback?: boolean;
  /**
   * SortableJS swap threshold (0..1) — a lower value makes rows swap earlier as the dragged item overlaps a neighbor. Reapplied live via `instance.option('swapThreshold', v)` — SortableJS reads it on every dragover, so no remount is needed.
   */
  swapThreshold?: number;
  /**
   * High-level prop that REPLACES a string `group` with SortableJS's `{ name, pull: 'clone', put: false }` clone-mode object form — the source deposits a COPY onto the destination and keeps its own array unchanged, and takes nothing back: no row can be dropped or keyboard-hopped into it (the palette → canvas pattern). With `group: null` it is a no-op (a clone-mode list with no group name has no peer to clone into). Reapplied live — toggling `cloneable` (or changing `group`) recomputes the clone-mode shape and reapplies it via `instance.option('group', …)`, no remount.
   */
  cloneable?: boolean;
  /**
   * Extra class(es) merged onto the list container (the SortableJS root) alongside the base `rozie-sortable-list` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding), normalized identically across all six targets — the hook for bridging a CSS framework (`.list-group`) or a flex/grid parent onto the component.
   */
  listClass?: string | any[] | Record<string, any>;
  /**
   * Extra class(es) merged onto every item row alongside the base `rozie-sortable-item` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding) applied uniformly, OR an `(item, index) => class` function for per-row classes evaluated at render time. Normalized identically across all six targets.
   */
  itemClass?: string | any[] | Record<string, any> | ((...args: any[]) => any);
  /**
   * The list's human name, such as `"Top sidebar"`. Sets `aria-label` on the list container (`role="list"`) and names the list in keyboard announcements when a row moves between lists (`Moved Hero banner to Top sidebar, position 1 of 4`, `Dropped Hero banner in Top sidebar at position 3 of 4`, `No list after Top sidebar`). Pass the same words as the zone's visible heading. With no label, announcements fall back to a neutral `list 2 of 3`, counting the mounted lists of the same group in hop (source) order.
   */
  listLabel?: (string) | null;
  /**
   * Which arrow keys move a lifted row within the list: `'vertical'` (default) uses ↑/↓, `'horizontal'` uses ←/→. A horizontal list's default spoken instructions say "Use the left and right arrow keys to move" (`role="list"` has no `aria-orientation`). Typed as `SortableOrientation` (`'vertical' | 'horizontal'`).
   */
  orientation?: SortableOrientation;
  /**
   * How many positions Page Up / Page Down move a lifted row. The move stops at the first or last position when fewer rows remain.
   */
  pageStep?: number;
  /**
   * Replaces the spoken keyboard instructions. The text sits in a hidden element referenced by `aria-describedby` from each tabbable row (row mode) or from the consumer's handle via the `instructionsId` slot prop (handle mode). Default: "Press Space or Enter to pick up, and again to drop. Use the up and down arrow keys to move, Home and End to jump to the start or end, Page Up and Page Down to move several places, and Escape to cancel." (with `orientation: 'horizontal'`, "the left and right arrow keys"; a `sort: false` list says only "Press Space or Enter to pick up, and again to drop. Press Escape to cancel."). When another mounted list could take this list's rows (by the group rules of `group`, `options.group` or `option('group', v)`), the default adds "Hold Shift with an arrow key to move to another list." (updated as lists mount, unmount or change group).
   */
  keyboardInstructions?: (string) | null;
  /**
   * Rewords or translates what the list says during keyboard reordering. An object of optional functions keyed by message kind (`lifted`, `moved`, `movedToList`, `dropped`, `droppedInList`, `atStart`, `atEnd`, `notSortable`, `noListBefore`, `noListAfter`, `cancelledReturnedToList`, `cancelledReturned`, `cancelledStays`, `cancelledRemoved`, `liftEnded`). Each receives a context (`label`, `item`, `list`, and for kinds with a position `position` (1-based) and `total`; `movedToList` also `fromList`) and returns the text to speak; `null` or `''` says nothing. Kinds without a function keep the default English text (see "Announcements"). Define the object in your script and bind it (Angular templates reject inline arrow functions), e.g. `const announcements = { moved: ({ label, position, total }) => label + ' → ' + position + '/' + total }`. Typed as `Announcements`, exported with `AnnouncementKind` and `AnnouncementContext`.
   * @example
   * <SortableList items={todos} onItemsChange={setTodos} announcements={announcements} />
   */
  announcements?: (Announcements) | null;
  /**
   * Per-row inline style applied to the `.rozie-sortable-item` wrapper. Accepts a CSS `String`, a flat style object (`Record<string, string | number>`), or an `(item, index) => string | object` function for per-row styling. Because it lands on the wrapper — the direct child of the list container — it can drive CSS-grid placement (`grid-column` / `grid-row` / `align-self`) when `listClass` sets `display: grid`. Normalized per target; `null` / empty drops the attribute.
   */
  itemStyle?: (string | Record<string, any> | ((...args: any[]) => any)) | null;
  onReorder?: (payload: SortablePayload) => void;
  onAdd?: (payload: SortablePayload) => void;
  onRemove?: (payload: SortablePayload) => void;
  onStart?: (payload: SortablePayload) => void;
  onEnd?: (payload: SortablePayload) => void;
  renderHeader?: () => ReactNode;
  children?: ReactNode | ((ctx: ChildrenCtx) => ReactNode);
  renderFooter?: () => ReactNode;
  slots?: Record<string, () => import('react').ReactNode>;
}

export interface SortableListHandle {
  getInstance: (...args: any[]) => any;
  toArray: (...args: any[]) => any;
  sort: (...args: any[]) => any;
  option: (...args: any[]) => any;
}

const SortableList = forwardRef<SortableListHandle, SortableListProps>(function SortableList(_props: SortableListProps, ref): JSX.Element {
  const __defaultOptions = useState(() => (() => ({}))())[0];
  const props: Omit<SortableListProps, 'itemKey' | 'handle' | 'group' | 'animation' | 'disabled' | 'disableKeyboard' | 'keyboardTrigger' | 'options' | 'labelFor' | 'ghostClass' | 'chosenClass' | 'dragClass' | 'filter' | 'easing' | 'forceFallback' | 'swapThreshold' | 'cloneable' | 'listClass' | 'itemClass' | 'listLabel' | 'orientation' | 'pageStep' | 'keyboardInstructions' | 'announcements' | 'itemStyle'> & { itemKey: (string | ((...args: any[]) => any)) | null; handle: (string) | null; group: (string) | null; animation: number; disabled: boolean; disableKeyboard: boolean; keyboardTrigger: SortableKeyboardTrigger; options: Record<string, any>; labelFor: ((...args: any[]) => any) | null; ghostClass: (string) | null; chosenClass: (string) | null; dragClass: (string) | null; filter: (string) | null; easing: (string) | null; forceFallback: boolean; swapThreshold: number; cloneable: boolean; listClass: string | any[] | Record<string, any>; itemClass: string | any[] | Record<string, any> | ((...args: any[]) => any); listLabel: (string) | null; orientation: SortableOrientation; pageStep: number; keyboardInstructions: (string) | null; announcements: (Announcements) | null; itemStyle: (string | Record<string, any> | ((...args: any[]) => any)) | null } = {
    ..._props,
    itemKey: _props.itemKey ?? null,
    handle: _props.handle ?? null,
    group: _props.group ?? null,
    animation: _props.animation ?? 150,
    disabled: _props.disabled ?? false,
    disableKeyboard: _props.disableKeyboard ?? false,
    keyboardTrigger: _props.keyboardTrigger ?? 'row',
    options: _props.options ?? __defaultOptions,
    labelFor: _props.labelFor ?? null,
    ghostClass: _props.ghostClass ?? null,
    chosenClass: _props.chosenClass ?? null,
    dragClass: _props.dragClass ?? null,
    filter: _props.filter ?? null,
    easing: _props.easing ?? null,
    forceFallback: _props.forceFallback ?? false,
    swapThreshold: _props.swapThreshold ?? 1,
    cloneable: _props.cloneable ?? false,
    listClass: _props.listClass ?? '',
    itemClass: _props.itemClass ?? '',
    listLabel: _props.listLabel ?? null,
    orientation: _props.orientation ?? 'vertical',
    pageStep: _props.pageStep ?? 5,
    keyboardInstructions: _props.keyboardInstructions ?? null,
    announcements: _props.announcements ?? null,
    itemStyle: _props.itemStyle ?? null,
  };
  const attrs: Record<string, unknown> = (() => {
    const { items, itemKey, handle, group, animation, disabled, disableKeyboard, keyboardTrigger, options, labelFor, ghostClass, chosenClass, dragClass, filter, easing, forceFallback, swapThreshold, cloneable, listClass, itemClass, listLabel, orientation, pageStep, keyboardInstructions, announcements, itemStyle, defaultValue, onItemsChange, defaultItems, onReorder, onAdd, onRemove, onStart, onEnd, renderHeader, children, renderFooter, slots, ...rest } = _props as SortableListProps & Record<string, unknown>;
    void items; void itemKey; void handle; void group; void animation; void disabled; void disableKeyboard; void keyboardTrigger; void options; void labelFor; void ghostClass; void chosenClass; void dragClass; void filter; void easing; void forceFallback; void swapThreshold; void cloneable; void listClass; void itemClass; void listLabel; void orientation; void pageStep; void keyboardInstructions; void announcements; void itemStyle; void defaultValue; void onItemsChange; void defaultItems; void onReorder; void onAdd; void onRemove; void onStart; void onEnd; void renderHeader; void children; void renderFooter; void slots;
    return rest;
  })();
  const entry = useRef<any>(null);
  const instance = useRef<any>(null);
  const appliedOptions = useRef<any>(null);
  const unhookNativeEvents = useRef<any>(null);
  const lastSpoken = useRef('');
  const unregisterEntry = useRef<any>(null);
  const unhookStrayKeys = useRef<any>(null);
  const __rowKeySeq = useRef(0);
  const [items, setItems] = useControllableState({
    value: props.items,
    defaultValue: props.defaultItems ?? (() => [])(),
    onValueChange: props.onItemsChange,
  });
  const _animationRef = useRef(props.animation);
  _animationRef.current = props.animation;
  const _announcementsRef = useRef(props.announcements);
  _announcementsRef.current = props.announcements;
  const _chosenClassRef = useRef(props.chosenClass);
  _chosenClassRef.current = props.chosenClass;
  const _disabledRef = useRef(props.disabled);
  _disabledRef.current = props.disabled;
  const _dragClassRef = useRef(props.dragClass);
  _dragClassRef.current = props.dragClass;
  const _easingRef = useRef(props.easing);
  _easingRef.current = props.easing;
  const _filterRef = useRef(props.filter);
  _filterRef.current = props.filter;
  const _forceFallbackRef = useRef(props.forceFallback);
  _forceFallbackRef.current = props.forceFallback;
  const _ghostClassRef = useRef(props.ghostClass);
  _ghostClassRef.current = props.ghostClass;
  const _handleRef = useRef(props.handle);
  _handleRef.current = props.handle;
  const _listLabelRef = useRef(props.listLabel);
  _listLabelRef.current = props.listLabel;
  const _onAddRef = useRef(props.onAdd);
  _onAddRef.current = props.onAdd;
  const _onEndRef = useRef(props.onEnd);
  _onEndRef.current = props.onEnd;
  const _onRemoveRef = useRef(props.onRemove);
  _onRemoveRef.current = props.onRemove;
  const _onReorderRef = useRef(props.onReorder);
  _onReorderRef.current = props.onReorder;
  const _onStartRef = useRef(props.onStart);
  _onStartRef.current = props.onStart;
  const _optionsRef = useRef(props.options);
  _optionsRef.current = props.options;
  const _swapThresholdRef = useRef(props.swapThreshold);
  _swapThresholdRef.current = props.swapThreshold;
  const _itemsRef = useRef(items);
  _itemsRef.current = items;
  const [liftedIndex, setLiftedIndex] = useState<any>(null);
  const [ariaLiveText, setAriaLiveText] = useState('');
  const [instructionsId, setInstructionsId] = useState<any>(null);
  const [optionOverrides, setOptionOverrides] = useState<Record<string, any>>({});
  const [hasHopPeer, setHasHopPeer] = useState(false);
  const _instructionsIdRef = useRef(instructionsId);
  _instructionsIdRef.current = instructionsId;
  const _optionOverridesRef = useRef(optionOverrides);
  _optionOverridesRef.current = optionOverrides;
  const listEl = useRef<HTMLDivElement | null>(null);
  const _watch0First = useRef(true);
  const _watch1First = useRef(true);
  const _watch2First = useRef(true);
  const _watch3First = useRef(true);
  const _watch4First = useRef(true);
  const _watch5First = useRef(true);
  const _watch6First = useRef(true);
  const _watch7First = useRef(true);
  const _watch8First = useRef(true);
  const _watch9First = useRef(true);
  const _watch10First = useRef(true);
  const _watch11First = useRef(true);
  const _watch12First = useRef(true);
  const _watch13First = useRef(true);
  const _watch14First = useRef(true);

  // The `options` object SortableJS was last given (see the `options` watcher).
  // Keyboard lift state lives in the shared registry (one active keyboard lift
  // per page, so a later task can hand a lifted row between lists).
  // `$data.liftedIndex` is only its mirror, for the lifted-row styling.
  const registry = useMemo(() => getKeyboardRegistry(), []);
  // This list's registry entry (a ListEntry), built and registered in $onMount.
  // Removes the listeners that keep SortableJS's own DOM events inside the list.
  // Removes the document keydown listener that catches keys lost to <body>.
  // SortableJS also dispatches its events as BUBBLING native DOM events
  // (`start`, `end`, `add`, `remove`, `change`, …) on the list element, before
  // it calls the option callbacks. An output binding on the component host
  // (Angular's `(start)` / `(end)` / `(add)` / `(remove)`, a Lit listener) also
  // catches a native DOM event of the same name, so a consumer would get the raw
  // SortableJS event as an extra event. The component re-emits the committed
  // events itself, so stop the raw ones at the list element (only events
  // dispatched ON the list — an `<input>`'s own `change` is untouched).
  const SORTABLE_DOM_EVENTS = useMemo(() => ['choose', 'unchoose', 'start', 'end', 'add', 'update', 'sort', 'remove', 'filter', 'clone', 'change', 'select', 'deselect'], []);
  // role="list" takes no aria-orientation, so a horizontal list says which
  // arrow keys move in its instructions instead. A `sort: false` list leaves out
  // the move sentence, and a list whose rows another mounted list could take
  // (by the group SortableJS runs with, `options.group` included) says how to
  // hop.
  function instructionsText() {
    if (props.keyboardInstructions != null) return props.keyboardInstructions;
    return defaultInstructions({
      horizontal: props.orientation === 'horizontal',
      sortable: liveOption('sort', true) !== false,
      grouped: effectiveGroup() != null && hasHopPeer
    });
  }

  // Instance-scoped synthetic-id store for id-less object items. Keyed by object
  // IDENTITY, so the same object keeps its synthetic id across a reorder (the
  // framework reconciler then rebinds the row component instance to its ORIGINAL
  // item, not its slot position — the data-corruption fix).
  //
  // Phase 73 item #11-b removed the former "fold the WeakMap + counter into ONE
  // member-mutated object const" workaround: `hoistModuleLet`'s reachability
  // walk now also roots at helpers called ONLY from a template expression
  // (`keyFor` is called from `:key`/`:data-id`, never from a hook), so the bare
  // `let __rowKeySeq = 0` below hoists to a `useRef` on React exactly like the
  // hook-reached case — no more per-render reset. Verified in codegen.
  const __rowKeyMap = useMemo(() => new WeakMap(), []);
  // 4-tier per-row key precedence. Its return feeds BOTH :key and :data-id.
  const { itemKey: _rozieProp_itemKey } = props;
    const keyFor = useCallback((item: any, index: any) => {
    // (a) function itemKey: consumer-supplied (item, index) => key.
    if (typeof _rozieProp_itemKey === 'function') {
      return _rozieProp_itemKey(item, index);
    }
    // (b) string itemKey: a property name on a non-null object item.
    if (typeof _rozieProp_itemKey === 'string' && item !== null && typeof item === 'object' && item[_rozieProp_itemKey] != null) {
      return item[_rozieProp_itemKey];
    }
    // (c) id-less object (or function) item: assign-on-first-sight WeakMap
    //     synthetic id. Survives reorder because it is keyed by object identity.
    if (item !== null && typeof item === 'object' || typeof item === 'function') {
      if (!__rowKeyMap.has(item)) {
        __rowKeyMap.set(item, '__rk' + __rowKeySeq.current++);
      }
      return __rowKeyMap.get(item);
    }
    // (d) primitive item: fall back to index. NOTE: duplicate primitives are
    //     unsafe to reorder this way — pass a function itemKey for those.
    return index;
  }, [_rozieProp_itemKey]);
  // Resolve the SortableJS `group` option: `cloneable` is a high-level Rozie
  // prop that REPLACES a string `group` with SortableJS's
  // `{ name, pull: 'clone', put: false }` clone-mode object form (a palette
  // takes nothing back, by mouse or keyboard). When
  // `cloneable:false`, pass `$props.group` through verbatim. When
  // `cloneable:true` AND `$props.group` is null, leave it null — a clone-mode
  // list without a group name is not meaningful (no peer list can join the
  // cross-list flow). Shared by $onMount construction AND the group/cloneable
  // $watch reconcile below — single source of truth, no duplicated ternary.
  const resolveGroup = useCallback(() => props.cloneable && typeof props.group === 'string' ? {
    name: props.group,
    pull: 'clone' as const,
    put: false as const
  } : props.group ?? undefined, [props.cloneable, props.group]);
  // The group SortableJS actually runs with: a runtime `option('group', v)`,
  // else `options.group` (it lands after the named props in the merge), else
  // the `group` / `cloneable` props. Keyboard hops follow the same rules as the
  // mouse, so they read this one.
  const effectiveGroup = useCallback(() => {
    const ov: any = optionOverrides;
    if (ov != null && Object.prototype.hasOwnProperty.call(ov, 'group')) return ov.group;
    const o: any = props.options;
    return o != null && o.group != null ? o.group : resolveGroup();
  }, [optionOverrides, props.options, resolveGroup]);
  // Resolve itemClass for a row: a static value (string | array | object) OR a
  // per-row (item, index) => class function. The result is fed into the :class
  // array and normalized by each target's class path (rozieClass / clsx / native).
  function itemClassFor(item: any, index: any) {
    const v = props.itemClass;
    return typeof v === 'function' ? v(item, index) : v;
  }

  // Resolve itemStyle for a row: a static value (string | object) OR a per-row
  // (item, index) => style function. Returns string | object | null; the dynamic
  // :style binding normalizes it per target. null / empty → attribute dropped.
  function itemStyleFor(item: any, index: any) {
    const s = typeof props.itemStyle === 'function' ? props.itemStyle(item, index) : props.itemStyle;
    return s == null || s === '' ? null : s;
  }

  // Read the display label for an item — used by the aria-live announcer.
  // Phase 16 R7 / D-08: $props.labelFor reads as `null` on all 6 targets when
  // the consumer omits it (Plan 16-01 prop-default coercion fix); the check is
  // a plain null compare — NO runtime callable-type coercion. Without
  // `labelFor` or a `label` field, the row's text (`row`), else `String(item)`
  // for a primitive, else `item {position}`.
  const { labelFor: _rozieProp_labelFor } = props;
    const labelOf = useCallback((item: any, idx: any, row: HTMLElement | null = null) => {
    if (_rozieProp_labelFor !== null) return _rozieProp_labelFor(item, idx);
    if (item !== null && typeof item === 'object' && item.label != null) return item.label;
    return fallbackLabel(item, idx, row);
  }, [_rozieProp_labelFor]);
  // The text this list's live region showed last (see the registry entry's
  // `announce`).
  // Keyboard handler (Phase 16 R7): Space/Enter lift and drop; while lifted,
  // ArrowUp/ArrowDown (ArrowLeft/ArrowRight when horizontal), Home/End and
  // PageUp/PageDown move the row, and Escape returns it to where it was lifted
  // from. The lift itself lives in the shared keyboard registry. After
  // any array-reorder write, refocusRow() keeps focus on the moved row (or its
  // handle) on all six targets.
  //
  // Note: `index` is passed directly as a number. Plan 16-02 (Solid call-arg
  // accessor unwrap) ensures Solid's <For> alias unwraps to `index()` at the
  // call site — no runtime callable-type coercion needed in user source.
  // Keyboard reordering is available only when the list is not disabled AND the
  // `disableKeyboard` opt-out is off. Drives BOTH the row tabindex (rows are
  // focusable only when reorderable) and the onRowKeyDown guard below. Reads
  // straight off $props so the tabindex binding re-evaluates reactively when
  // `disabled`/`disableKeyboard` toggle at runtime.
  //
  // The keyboard follows the SortableJS options the mouse obeys: `disabled`
  // (the prop, `options.disabled`, or `option('disabled', v)`), `filter` and
  // `draggable` (which rows lift, see rowLiftable) and `sort: false` (no moves
  // within the list). `liveOption` reads the value SortableJS runs with: one set
  // at runtime, else `options`, else the named prop.
  const KEYBOARD_OPTIONS = useMemo(() => ['disabled', 'filter', 'draggable', 'sort'], []);
  function liveOption(name: any, fallback: any) {
    const ov: any = optionOverrides;
    if (ov != null && Object.prototype.hasOwnProperty.call(ov, name)) return ov[name];
    const o: any = props.options;
    if (o != null && o[name] !== undefined) return o[name];
    return fallback;
  }
  function setOverride(name: any, value: any) {
    setOptionOverrides(prev => ({
      ...prev,
      [name]: value
    }));
  }
  function clearOverride(name: any) {
    const ov: any = optionOverrides;
    if (ov == null || !Object.prototype.hasOwnProperty.call(ov, name)) return;
    const next = {
      ...ov
    };
    delete next[name];
    setOptionOverrides(next);
  }
  // Options whose runtime value (`option(name, v)`) is remembered, so a later
  // change of the matching prop doesn't overwrite it: the keyboard ones, plus
  // `animation`, `handle` and `group` (runtime override → `options` → prop).
  const TRACKED_OPTIONS = useMemo(() => [...KEYBOARD_OPTIONS, 'animation', 'handle', 'group'], []);
  const keyboardEnabled = useCallback(() => !props.disableKeyboard && !liveOption('disabled', props.disabled), [liveOption, props.disableKeyboard, props.disabled]);
  // The handle selector SortableJS runs with (`option('handle', v)`, else
  // `options.handle`, else the `handle` prop): the keyboard reads the same one.
  const handleSelector = useCallback(() => liveOption('handle', props.handle), [liveOption, props.handle]);
  // keyboardTrigger='handle' mode: rows are not tab stops and the keys are read
  // from the consumer's handle element instead. Any other value is 'row' mode.
  const handleMode = useCallback(() => props.keyboardTrigger === 'handle', [props.keyboardTrigger]);
  // Rows are tab stops only in row mode (and only while keyboard is enabled).
  function rowTabbable() {
    return keyboardEnabled() && !handleMode();
  }

  // One-time-per-change dev warning: handle mode needs a handle selector. Without
  // one the keyboard is OFF (see the onRowKeyDown gate) — never a silent fallback
  // to row mode, which would re-introduce the tab stops the consumer opted out of.
  const warnIfHandleMissing = useCallback(() => {
    if (handleMode() && handleSelector() == null) {
      console.warn('[rozie-sortable-list] keyboardTrigger is "handle" but no handle selector is set, so keyboard reordering is off. Pass a handle selector (e.g. handle=".grip") or use keyboardTrigger "row".');
    }
  }, [handleMode, handleSelector]);
  // True only when a keydown originated inside a `handle` element that belongs to
  // THIS row. Walks the COMPOSED ancestor chain from the event target up to (but
  // excluding) the row (currentTarget): assignedSlot -> parentNode -> shadow host.
  // Plain closest()/contains() stop at a shadow boundary, and Lit renders a Rozie
  // consumer's slot content inside the SortableList shadow root while plain-HTML
  // consumers project light-DOM nodes through a <slot>. composedPath() is not
  // used because React's synthetic event does not expose it. Another
  // .rozie-sortable-item met first means the key came from a NESTED list's row,
  // which must not reorder this (outer) list.
  function isHandleKeyOrigin($event: any) {
    const sel = handleSelector();
    if (sel == null) return false;
    const row = $event.currentTarget;
    let n: any = $event.target;
    while (n && n !== row) {
      if (n.nodeType === 1) {
        if (n.matches(sel)) {
          // Matched a handle: it counts only if this row is reachable from here
          // without crossing a different sortable item.
          let m: any = n.assignedSlot ?? n.parentNode ?? n.host;
          while (m && m !== row) {
            if (m.nodeType === 1 && m.classList.contains('rozie-sortable-item')) return false;
            m = m.assignedSlot ?? m.parentNode ?? m.host;
          }
          return m === row;
        }
        if (n.classList.contains('rozie-sortable-item')) return false;
      }
      n = n.assignedSlot ?? n.parentNode ?? n.host;
    }
    return false;
  }

  // Put focus back on the MOVED row (row mode) or its handle (handle mode) after
  // a reorder write. Looks the row up by KEY (data-id), not by index, so it finds
  // the moved row whether this runs before the framework commit (the row element
  // is the same one) or after it (Svelte/Solid/Lit re-create the DOM) — and it is
  // correct for index-keyed primitive lists too. Direct children of the list
  // container only: that skips nested-list rows and the header/footer slot
  // content.
  //
  // Two passes. (1) A microtask covers targets that commit synchronously or in an
  // earlier microtask (Vue's scheduler flush is queued by the model write, before
  // this one). (2) A timer + rAF "heal" pass covers targets whose DOM commit is
  // scheduled AFTER the key handler returns (Angular): the commit can MOVE the
  // focused row, and moving a focused node blurs it, so a Home/End/Escape jump or
  // a rapid Space/Arrow/Arrow/Space burst would otherwise end with focus on
  // <body>. The heal pass never steals: it acts only when focus has been lost to
  // <body>. (`$restoreFocus(selector, index)` is not enough here: it is a no-op on
  // Vue/Angular, where a long jump moves the focused row itself, and it looks the
  // row up by index, which can land on a neighbour on Lit.) The $refs read
  // happens here, synchronously, inside an event handler — which is safe.
  const refocusRow = useCallback((item: any, idx: any) => {
    const listEl$local = listEl.current;
    const sel = handleSelector();
    const useHandle = handleMode();
    const key = String(keyFor(item, idx));
    // While this refocus is outstanding, a key that falls to <body> belongs to
    // the lift (see onStrayKey). Cleared once the row has focus again, or by a
    // pointer press anywhere.
    const pending = registry.lift;
    if (pending != null) pending.focusPending = true;
    const focusIt = (onlyIfLost: any) => {
      if (!listEl$local) return;
      if (useHandle && sel == null) return;
      if (onlyIfLost && document.activeElement && document.activeElement !== document.body) return;
      for (const row of Array.from(listEl$local.children) as any[]) {
        if (row.getAttribute('data-id') === key) {
          const target = useHandle ? row.querySelector(sel) : row;
          if (target && typeof target.focus === 'function') {
            target.focus();
            const l = registry.lift;
            if (l != null && l === pending && l.key === key) {
              l.focusPending = false;
              // This row is the lifted row element now (see the items watcher).
              l.liftedRowEl = row;
            }
          }
          return;
        }
      }
    };
    queueMicrotask(() => focusIt(false));
    setTimeout(() => focusIt(true), 0);
    if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => focusIt(true));
  }, [handleMode, handleSelector, keyFor]);
  // `el` in an event payload: the row element while it is in the page, else
  // null (a row that left with an unmounted list is no row of any list).
  const liveEl = useCallback((el: any) => el != null && el.isConnected ? el : null, []);
  // The row element carrying `data-id === key` among a list element's direct
  // children (skips nested-list rows and header/footer slot content).
  const rowByKey = useCallback((listEl: any, key: any) => {
    if (!listEl || key == null) return null;
    for (const row of Array.from(listEl.children) as any[]) {
      if (row.getAttribute('data-id') === key) return row;
    }
    return null;
  }, []);
  // After the consumer changed the items of the list holding a lift, put focus
  // on the row (or its handle) whose key is `key`, else the row nearest `index`
  // (or the list itself when it has no rows left) — but only once focus has fallen to <body> (the focused row's element went
  // away: the lift was lost, or a framework that keys rows by object identity
  // re-created the lifted row). Never steals focus from anywhere else. Same
  // three passes as refocusRow, for targets that commit late.
  const focusNearRow = useCallback((index: number, key: string | null = null) => {
    const listEl$local = listEl.current;
    const sel = handleSelector();
    const useHandle = handleMode();
    const focusIt = () => {
      if (!listEl$local) return;
      if (useHandle && sel == null) return;
      if (document.activeElement && document.activeElement !== document.body) return;
      const rows = Array.from(listEl$local.children).filter((r: any) => r.hasAttribute('data-id') && r.classList.contains('rozie-sortable-item')) as any[];
      if (rows.length === 0) {
        // The list is now empty: focus the list itself (out of the tab order)
        // so keyboard and screen-reader users stay where they were.
        if (!listEl$local.hasAttribute('tabindex')) listEl$local.setAttribute('tabindex', '-1');
        listEl$local.focus();
        return;
      }
      const row = rows.find((r: any) => key != null && r.getAttribute('data-id') === key) ?? rows[Math.max(0, Math.min(rows.length - 1, index))];
      const target = useHandle ? row.querySelector(sel) : row;
      if (target && typeof target.focus === 'function') target.focus();
    };
    queueMicrotask(focusIt);
    setTimeout(focusIt, 0);
    if (typeof requestAnimationFrame === 'function') requestAnimationFrame(focusIt);
  }, [handleMode, handleSelector]);
  // Speak `text` from `target`'s aria-live region. The region that spoke last
  // is cleared when it belongs to another list, so a message is heard once, from
  // the list the row is in now, and never from a list that just lost it.
  function speak(target: any, text: any) {
    const prev = registry.speaker;
    if (prev != null && prev !== target && registry.has(prev)) prev.announce('');
    registry.speaker = target;
    target.announce(text);
  }

  // Say announcement `kind` from `target`, in `target`'s words: its
  // `announcements` function for that kind, else the default text (see
  // ./internal/announcements). `index` is the row's 0-based position in
  // `target`, `row` the row element its label is read from (when there is no
  // `labelFor` or `label` field), and `total` how many rows `target` holds after
  // the change (null for the kinds without a position). A function returning
  // null or '' clears the region, so nothing is said.
  function say(target: any, kind: AnnouncementKind, item: unknown, index: number, row: HTMLElement | null, total: number | null = null, fromList: any = null) {
    const ctx: any = {
      item,
      list: registry.listName(target)
    };
    // The label is read only when the text needs it (a default with `{label}`,
    // or an override that reads `label`), so `labelFor` is not called for a
    // message that doesn't name the row (`Lift ended`: the item has left).
    let label: string | null = null;
    Object.defineProperty(ctx, 'label', {
      enumerable: true,
      get: () => {
        if (label === null) label = target.labelOf(item, index, row);
        return label;
      }
    });
    if (total != null) {
      ctx.position = index + 1;
      ctx.total = total;
    }
    if (fromList != null) ctx.fromList = registry.listName(fromList);
    speak(target, target.message(kind, ctx));
  }

  // The lifted item is no longer in the list holding it: the consumer changed
  // that list's items (or re-keyed the item), or the list is unmounting. End the
  // lift without writing anything (the item is wherever the consumer's data put
  // it). `end` still fires once, with `item` = the lifted value and `el: null`
  // (there is no row), so keyboard `start` / `end` pair (unless the holder and the origin have both unmounted). Lost to a consumer change (not an
  // unmount), the holder says `Lift ended` and, if focus fell to <body> with the
  // row, focuses its row nearest where the lifted row was.
  const loseLift = useCallback((unmounting = false) => {
    const lift = registry.lift;
    if (!lift) return;
    const h = lift.holder;
    registry.lift = null;
    h.setLifted(null);
    if (!unmounting) {
      say(h, 'liftEnded', lift.item, lift.index ?? lift.origin.index, lift.liftedRowEl);
      h.focusNear(lift.index ?? lift.origin.index);
    }
    const payload = {
      interaction: 'keyboard' as const,
      item: lift.item,
      el: null,
      from: lift.origin.list.el,
      to: h.el,
      oldIndex: lift.origin.index,
      newIndex: -1
    };
    // Like every `end`, in a task after the writes, from the holder. An
    // unmounted list never emits (Angular rejects an emit from a destroyed
    // component): when the holder is unmounting, the origin list (which emitted
    // `start`) ends the lift if it is still mounted, so `start` and `end` pair;
    // if it is gone too, nothing is emitted.
    registry.deferEnd((host: any) => host.emit('end', payload), h, lift.origin.list);
  }, [say]);
  // Keyboard `start` / `end` (the same payload as every other event): `item` is
  // the item value, `el` its row element. `start` fires from the origin list
  // (`from`), `end` from the list the row ends up in (`to`). `el` is the row in
  // that list when it is rendered, else `fallbackEl` (the row element the move
  // started from, before a target re-rendered). `end` is called after
  // `registry.lift` is cleared, so a consumer `end` handler that writes the
  // items (re-keying a clone copy) is not mistaken for a lost lift, and it is
  // emitted in a task (`registry.deferEnd`), after the writes AND the re-render
  // they schedule: a consumer `end` handler reads the new state on every target
  // (React included, whose handler closure is the one from the latest render).
  // If `to` has unmounted by then, `from` (the origin, which emitted `start`)
  // emits it instead, `to` unchanged in the payload; an unmounted list never
  // emits.
  function keyboardStartEnd(name: any, lift: any, from: any, to: any, oldIndex: any, newIndex: any, fallbackEl: HTMLElement | null = null) {
    const fire = (host: any) => host.emit(name, {
      interaction: 'keyboard',
      item: lift ? lift.item : null,
      el: (lift && host === to ? rowByKey(host.el, lift.key) : null) ?? liveEl(fallbackEl),
      from: from.el,
      to: to.el,
      oldIndex,
      newIndex
    });
    if (name === 'end') registry.deferEnd(fire, to, from);else fire(from);
  }

  // Move the lifted row to `toIndex` (clamped) within the list holding it.
  // Works through the registry entry, so it acts on the current holder. `dir`
  // is the key's direction (-1 toward the start), for when the row can't move.
  function moveLiftTo(toIndex: any, dir: any) {
    const lift = registry.lift;
    if (!lift) return;
    const h = lift.holder;
    const from = registry.indexOfLift();
    if (from < 0) {
      loseLift();
      return;
    }
    const items = h.items();
    const to = Math.max(0, Math.min(items.length - 1, toIndex));
    // The moved row's element, read before the write (an index key changes).
    const el = h.rowEl(from);
    if (to === from) {
      // Nowhere to go: say so (the row is already at that end).
      say(h, dir < 0 ? 'atStart' : 'atEnd', items[from], from, el ?? lift.liftedRowEl, items.length);
      return;
    }
    const next = [...items];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    // Index keys (primitive items without itemKey) change with the position.
    // Update the lift BEFORE writing: a target whose watchers run synchronously
    // on the write must already see where the row is going.
    lift.key = h.keyOf(moved, to);
    lift.index = to;
    h.write(next);
    h.setLifted(to);
    // Name the row that MOVED from the local `moved` item: on React/Vue/Lit the
    // items prop still holds the pre-write array here. Labels come from the
    // holder's own `labelFor`.
    say(h, 'moved', moved, to, el, items.length);
    h.focusRow(moved, to);
    h.emit('reorder', {
      interaction: 'keyboard',
      item: moved,
      el,
      from: h.el,
      to: h.el,
      oldIndex: from,
      newIndex: to
    });
  }

  // Hop the lifted row to the next (`dir` 1) or previous (-1) list it could
  // also reach by mouse, in composed-tree source order. One hand-off: the source
  // writes its items without the row, the destination writes them with it, and
  // the destination becomes the holder. As with the mouse, the destination
  // emits `add` first, then the source emits `remove`. A forward hop lands
  // first, a backward hop lands last.
  function hop(dir: any) {
    const lift = registry.lift;
    if (!lift) return;
    const from = lift.holder;
    const i = registry.indexOfLift();
    if (i < 0) {
      loseLift();
      return;
    }
    const fromItems = from.items();
    const data = fromItems[i];
    const el = from.rowEl(i);
    // Keep the lifted row element current: lists nested inside it (a grid
    // widget's columns) are never hop targets. Before a target re-renders the
    // row may not exist yet, so keep the last known element then.
    lift.liftedRowEl = el ?? lift.liftedRowEl;
    const to = registry.findHopTarget(from, dir);
    if (to == null) {
      say(from, dir === 1 ? 'noListAfter' : 'noListBefore', data, i, el ?? lift.liftedRowEl);
      return;
    }
    const origin = lift.origin;
    const toItems = to.items();
    // A clone copy hopping back into the list it was cloned from merges with
    // its original there (that list never gave it up), rather than adding a
    // second row with the same key.
    if (lift.copy && to === origin.list) {
      let home = toItems.indexOf(data);
      if (home < 0) home = Math.max(0, Math.min(toItems.length - 1, origin.index));
      lift.holder = to;
      lift.copy = false;
      lift.key = to.keyOf(toItems[home], home);
      lift.item = toItems[home];
      lift.index = home;
      const rest = [...fromItems];
      rest.splice(i, 1);
      from.write(rest);
      from.emit('remove', {
        interaction: 'keyboard',
        item: data,
        el,
        from: from.el,
        to: to.el,
        oldIndex: i,
        newIndex: -1
      });
      from.setLifted(null);
      to.setLifted(home);
      say(to, 'movedToList', data, home, el, toItems.length, from);
      to.focusRow(toItems[home], home);
      return;
    }
    // The first hop out of a clone source (`pull: 'clone'`) leaves the source
    // untouched and carries a copy (the same item value the mouse path
    // inserts); from then on the copy moves like any row.
    const cloneOut = canHop(from.group(), to.group()).copy && from === origin.list && !lift.copy;
    const at = dir === 1 ? 0 : toItems.length;
    // Update the lift BEFORE writing, so a target whose watchers run
    // synchronously on a write already sees the new holder.
    lift.holder = to;
    lift.key = to.keyOf(data, at);
    lift.index = at;
    lift.hopped = true;
    if (cloneOut) {
      lift.copy = true;
    } else {
      const rest = [...fromItems];
      rest.splice(i, 1);
      from.write(rest);
    }
    const next = [...toItems];
    next.splice(at, 0, data);
    to.write(next);
    // The destination has not rendered its new row yet: `el` is the row the
    // move started from. `add` (destination) before `remove` (source), as by
    // mouse.
    to.emit('add', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: -1,
      newIndex: at
    });
    if (!cloneOut) from.emit('remove', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: i,
      newIndex: -1
    });
    from.setLifted(null);
    to.setLifted(at);
    say(to, 'movedToList', data, at, el, toItems.length + 1, from);
    to.focusRow(data, at);
  }

  // End the active keyboard lift. 'drop' leaves the row where it is ('off' too,
  // announced as `Lift ended`: the holder's keyboard was turned off); 'cancel'
  // returns it to the list and position it was lifted from (after hops, a
  // reverse hand-off with its own `remove` / `add`; a clone copy is removed).
  // Emits `end` once, from the list the row ends up in.
  const endLift = useCallback((kind: any) => {
    const lift = registry.lift;
    if (!lift) return;
    const h = lift.holder;
    const origin = lift.origin;
    const at = registry.indexOfLift();
    if (at < 0) {
      loseLift();
      return;
    }
    const items = h.items();
    const item = items[at];
    // The lifted row's element, read before any write below. Right after a hop
    // the holder may not have rendered it yet: its label is read from the
    // lifted row element then.
    const el = h.rowEl(at);
    const row = el ?? lift.liftedRowEl;
    if (kind === 'drop' || kind === 'off') {
      // A row that hopped always names its list, even back in its origin. The
      // keyboard turned off mid-lift ('off') ends it where it is, too.
      if (kind === 'off') say(h, 'liftEnded', item, at, row);else say(h, lift.hopped ? 'droppedInList' : 'dropped', item, at, row, items.length);
      h.setLifted(null);
      registry.lift = null;
      keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
      return;
    }
    if (h !== origin.list && !registry.has(origin.list) && lift.copy) {
      // A clone copy is removed on cancel even when its source list has
      // unmounted (the source never gave its item up). Focus moves to the
      // neighbouring row, if any. The lift ends BEFORE the write: the copy is
      // leaving on purpose, and a target whose items watcher runs synchronously
      // on the write (Solid) must not take it for a lost lift (a second `end`).
      registry.lift = null;
      const rest = [...items];
      rest.splice(at, 1);
      h.write(rest);
      h.emit('remove', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: h.el,
        oldIndex: at,
        newIndex: -1
      });
      h.setLifted(null);
      say(h, 'cancelledRemoved', item, at, row);
      if (rest.length > 0) {
        const k = Math.min(at, rest.length - 1);
        h.focusRow(rest[k], k);
      }
      // The copy is gone, so there is no row: `el: null`.
      const fromEl = origin.list.el;
      registry.deferEnd((host: any) => host.emit('end', {
        interaction: 'keyboard',
        item,
        el: null,
        from: fromEl,
        to: h.el,
        oldIndex: origin.index,
        newIndex: -1
      }), h, origin.list);
      return;
    }
    if (h !== origin.list && (!registry.has(origin.list) || !isRenderable(origin.list.el) || !origin.list.keyboardEnabled())) {
      // The origin list has unmounted, is hidden, or has its keyboard off:
      // there is nowhere to return to (focus would be stranded), so the row
      // stays where it is (the lift ends as a drop at its position).
      say(h, 'cancelledStays', item, at, row, items.length);
      h.setLifted(null);
      registry.lift = null;
      keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
      return;
    }
    if (h === origin.list) {
      const to = Math.max(0, Math.min(items.length - 1, origin.index));
      if (to !== at) {
        const next = [...items];
        next.splice(at, 1);
        next.splice(to, 0, item);
        lift.key = h.keyOf(item, to);
        h.write(next);
        h.focusRow(item, to);
        h.emit('reorder', {
          interaction: 'keyboard',
          item,
          el,
          from: h.el,
          to: h.el,
          oldIndex: at,
          newIndex: to
        });
      }
      say(h, lift.hopped ? 'cancelledReturnedToList' : 'cancelledReturned', item, to, row, items.length);
      h.setLifted(null);
      registry.lift = null;
      keyboardStartEnd('end', lift, origin.list, h, origin.index, to, el);
      return;
    }
    // Reverse hand-off from the current holder back to the origin list.
    const home = origin.list;
    const homeItems = home.items();
    let back;
    if (lift.copy) {
      // The clone source never gave its item up: drop the copy, focus the
      // original.
      back = homeItems.indexOf(item);
      if (back < 0) back = Math.max(0, Math.min(homeItems.length - 1, origin.index));
    } else {
      back = Math.min(origin.index, homeItems.length);
    }
    lift.holder = home;
    lift.key = home.keyOf(item, back);
    const rest = [...items];
    rest.splice(at, 1);
    h.write(rest);
    if (!lift.copy) {
      const next = [...homeItems];
      next.splice(back, 0, item);
      home.write(next);
      // `add` (destination) before `remove` (source), as by mouse.
      home.emit('add', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: home.el,
        oldIndex: -1,
        newIndex: back
      });
    }
    h.emit('remove', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: home.el,
      oldIndex: at,
      newIndex: -1
    });
    h.setLifted(null);
    // `home` holds the lift during its write, so a target whose items watcher
    // runs synchronously on the write (Solid) highlighted the row there: clear it.
    home.setLifted(null);
    say(home, 'cancelledReturnedToList', item, back, row, homeItems.length + (lift.copy ? 0 : 1));
    home.focusRow(lift.copy ? homeItems[back] : item, back);
    registry.lift = null;
    keyboardStartEnd('end', lift, home, home, origin.index, back, lift.copy ? home.rowEl(back) : el);
  }, [keyboardStartEnd, loseLift, say]);
  // This list's keyboard was turned off (`disabled`, `disableKeyboard`, or
  // `option('disabled', true)`): a lift it holds ends where the row is, with
  // its `end`.
  function endLiftIfHeld() {
    const lift = registry.lift;
    if (lift != null && lift.holder === entry.current) endLift('off');
  }

  // In row mode the rows leave the tab order when the keyboard turns off, and a
  // focused element that stops being focusable drops focus to <body>. If one of
  // this list's rows still has focus (a target whose watcher runs before its DOM
  // update), move it to the list itself (out of the tab order), like an emptied
  // list. Once the DOM update has run, the `focusout` listener added in $onMount
  // does it instead.
  function keepFocusOffBody() {
    const listEl = entry.current ? entry.current.el : null;
    if (!listEl) return;
    const root: any = listEl.getRootNode();
    const a: any = root != null ? root.activeElement : null;
    if (a == null || a.parentNode !== listEl || !a.classList.contains('rozie-sortable-item')) return;
    if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
    listEl.focus();
  }
  function keyboardTurnedOff() {
    endLiftIfHeld();
    keepFocusOffBody();
  }

  // Lift the row at `index` of this list.
  function startLift(index: any) {
    if (!entry.current) return;
    // A previous drag's or lift's `end` that is still pending fires first, so
    // every `end` comes before the next `start`.
    registry.flushEnds();
    const item = items[index];
    registry.lift = {
      holder: entry.current,
      key: entry.current.keyOf(item, index),
      item,
      copy: false,
      hopped: false,
      origin: {
        list: entry.current,
        index
      },
      liftedRowEl: entry.current.rowEl(index),
      index
    };
    setLiftedIndex(index);
    say(entry.current, 'lifted', item, index, registry.lift.liftedRowEl, items.length);
    keyboardStartEnd('start', registry.lift, entry.current, entry.current, index, index);
  }
  const onRowKeyDown = useCallback(($event: any, index: any) => {
    // Origin guard — must run FIRST, before the keyboardEnabled() check.
    //  - handle mode (keyboardTrigger='handle'): reorder keys apply ONLY when the
    //    keydown came from inside this row's `handle` element. A missing `handle`
    //    selector means keyboard is OFF (warned in warnIfHandleMissing).
    //  - row mode (quick 260716-ggq): reorder keys apply ONLY when the row
    //    element ITSELF is focused. A slotted interactive child (an <input>,
    //    <button>, etc. rendered into the row's default slot) bubbles its own
    //    keydown up to this handler — without this guard, Space/Enter typed into
    //    that child would be hijacked for lift/drop instead of reaching the
    //    child.
    if (handleMode()) {
      if (handleSelector() == null || !isHandleKeyOrigin($event)) return;
    } else if ($event.target !== $event.currentTarget) {
      return;
    }
    // Defense-in-depth: when keyboard reordering is off the rows carry no
    // tabindex and can't receive focus, but a consumer-focused row (or a
    // programmatic .focus()) must still no-op here rather than reorder.
    if (!keyboardEnabled()) return;
    // While a lift exists, reorder keys in the list holding it act on it. A key
    // from ANOTHER list of the holder's group is routed to the holder only when
    // it comes from the lifted row element itself (its old row, still there
    // before the frameworks re-render after a hop; compared by element, so a
    // row of another list that shares the lifted row's key is not it) or while a refocus after a move is
    // outstanding (a fast burst). Any other row — and every row of an unrelated
    // list (another group, or none) — keeps single-list behaviour: Space/Enter
    // there drops the foreign lift and lifts its own row, other keys do nothing.
    const lift = registry.lift;
    const key = $event.key;
    if (lift != null) {
      const mine = groupNameOf(effectiveGroup());
      const sameGroup = mine != null && mine === groupNameOf(lift.holder.group());
      const fromLiftedRow = lift.liftedRowEl != null && $event.currentTarget === lift.liftedRowEl;
      if (lift.holder === entry.current || sameGroup && (fromLiftedRow || lift.focusPending === true)) {
        if (lift.holder.onKey(key, !!$event.shiftKey)) $event.preventDefault();
        return;
      }
    }
    // Space (' ' on browsers; KeyboardEvent.key === ' ') OR Enter — lift. A row
    // the mouse can't drag (it matches `filter`, or not `draggable`) can't be
    // lifted either: the key is left alone (not prevented).
    if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
      const rules = {
        filter: liveOption('filter', props.filter),
        draggable: liveOption('draggable', undefined),
        sortable: instance.current
      };
      if (!rowLiftable($event.currentTarget as any, rules)) return;
      $event.preventDefault();
      if (lift != null) endLift('drop');
      startLift(index);
    }
  }, [effectiveGroup, endLift, groupNameOf, handleMode, handleSelector, isHandleKeyOrigin, keyboardEnabled, liveOption, props.filter, startLift]);
  // The group NAME of a SortableJS group option (string or object form).
  function groupNameOf(g: any) {
    return g == null ? null : typeof g === 'string' ? g : g.name ?? null;
  }

  // A reorder key for the lift THIS list holds (routed here from any list via
  // the registry entry's onKey). Returns true when the key was handled. Every
  // key except Space/Enter acts only while lifted, so it never steals keys from
  // fields inside a row.
  const holderKey = useCallback((key: any, shift: any) => {
    const lift = registry.lift;
    if (lift == null || lift.holder !== entry.current) return false;
    if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
      endLift('drop');
      return true;
    }
    if (key === 'Escape') {
      endLift('cancel');
      return true;
    }
    const horizontal = props.orientation === 'horizontal';
    const prevKey = horizontal ? 'ArrowLeft' : 'ArrowUp';
    const nextKey = horizontal ? 'ArrowRight' : 'ArrowDown';
    if (shift && (key === nextKey || key === prevKey)) {
      // Hopping is on wherever a group is set; an ungrouped list ignores it.
      if (effectiveGroup() == null) return false;
      hop(key === nextKey ? 1 : -1);
      return true;
    }
    const from = registry.indexOfLift();
    if (from < 0) {
      loseLift();
      return false;
    }
    // pageStep below 1 (or not a number) still moves by at least one position.
    const step = Math.max(1, Math.floor(Number(props.pageStep) || 1));
    let to: any = null;
    if (key === nextKey) to = from + 1;else if (key === prevKey) to = from - 1;else if (key === 'Home') to = 0;else if (key === 'End') to = entry.current.items().length - 1;else if (key === 'PageDown') to = from + step;else if (key === 'PageUp') to = from - step;
    if (to === null) return false;
    // `sort: false`: no moves within the list (as by mouse). The key is still
    // taken, so it does not scroll the page while a row is lifted, and says why
    // nothing moved.
    if (liveOption('sort', true) === false) {
      say(entry.current, 'notSortable', entry.current.items()[from], from, entry.current.rowEl(from) ?? lift.liftedRowEl);
      return true;
    }
    moveLiftTo(to, key === prevKey || key === 'Home' || key === 'PageUp' ? -1 : 1);
    return true;
  }, [effectiveGroup, endLift, hop, liveOption, loseLift, moveLiftTo, props.orientation, props.pageStep, say]);
  // A key pressed while focus has fallen to <body> during a lift. A hop removes
  // the focused row from one list and the destination may render (and take
  // focus) only after the handler returns (Angular), so the next key of a fast
  // burst can reach <body>. The list holding the lift handles it as if it had
  // landed on the lifted row, then puts focus back on that row.
  //
  // Only while a refocus of ours is outstanding (`focusPending`): focus that left
  // the lifted row for any other reason (the user clicked elsewhere or tabbed
  // away) keeps today's behaviour, and those keys are not ours. Modified keys
  // and keys someone already handled are never taken.
  const onStrayKey = useCallback((ev: any) => {
    const lift = registry.lift;
    if (lift == null || lift.holder !== entry.current || !lift.focusPending) return;
    if (ev.defaultPrevented || ev.ctrlKey || ev.metaKey || ev.altKey) return;
    const t = ev.target;
    if (t !== document.body && t !== document.documentElement) return;
    const item = lift.item;
    const at = registry.indexOfLift();
    if (!holderKey(ev.key, !!ev.shiftKey)) return;
    ev.preventDefault();
    const now = registry.lift;
    if (now != null) now.holder.focusRow(now.item, registry.indexOfLift());else if (at >= 0) entry.current.focusRow(item, at);
  }, [holderKey]);
  // SortableJS wiring lives in `useSortableJS()` (./internal/useSortableJS).
  // The helper owns the SortableJS-vs-reconciler dance — DOM-restore hardening
  // against fragile-event paths, identity-based item lookup over fragile
  // `e.oldIndex`, and the single-onEnd disambiguation that collapses
  // onUpdate / onAdd / onRemove into one handler.
  //
  // What stays here is purely declarative: which array to read, what to write
  // back, what to emit, and how to bridge `afterCommit` to the Lit-only
  // `$reconcileAfterDomMutation()` sigil.
  // `options.group` wins over `group` / `cloneable` (see effectiveGroup), for
  // the mouse as for the keyboard.
  // A group change can change which lists can take each other's rows: every
  // list rechecks its Shift instructions.
  function applyGroup() {
    instance.current?.option('group', effectiveGroup());
    registry.notifyPeers();
  }
  // Imperative handle (Phase 21 $expose). The SortableJS imperative surface a
  // consumer can't drive through props alone — exposed uniformly to all 6 targets.
  // Each guards the pre-mount/destroyed `instance = null`. Collision-clear: none of
  // the 4 verb names collide with the 16 props or the 5 events — `option` is a
  // distinct identifier from the `options` prop, so ROZ121 is clear.
  function getInstance() {
    return instance.current;
  }
  // toArray()/sort() use the rows' data-id keys — every row carries
  // :data-id="keyFor(item, index)", so toArray() returns the current key order
  // (set itemKey for stable object-list keys).
  function toArray() {
    return instance.current ? instance.current.toArray() : [];
  }
  // sort(order) reorders the bound items by those keys and writes them back
  // (the framework re-renders the rows; SortableJS never moves them behind the
  // model). Listed keys come first, in order; the rest follow in their order. No
  // event fires: it is the consumer's own call. With `useAnimation` (and a
  // non-zero `animation`) the rows slide from where they were.
  function sort(order: any, useAnimation = true) {
    const list = items;
    const next = orderByKeys(list, order ?? [], keyFor);
    if (next.every((item: any, i: any) => item === list[i])) return;
    const animate = useAnimation && instance.current != null;
    if (animate) instance.current.captureAnimationState();
    setItems(next);
    if (animate) {
      const sortable = instance.current;
      afterFlush(() => sortable.animateAll());
    }
  }
  // option(name) reads a live SortableJS option; option(name, value) sets one — the
  // runtime escape hatch for any SortableJS option beyond the curated props.
  // Setting `disabled`, `filter`, `draggable` or `sort` also applies to the
  // keyboard; `option('disabled', true)` mid-lift ends the lift this list holds.
  // A runtime `animation` is kept over later `animation` prop changes.
  function option(name: any, value: any) {
    if (!instance.current) return undefined;
    if (value === undefined) return instance.current.option(name);
    instance.current.option(name, value);
    if (TRACKED_OPTIONS.includes(name)) setOverride(name, value);
    if (name === 'disabled' && value) keyboardTurnedOff();
    // After the re-render, so every list reads the new group (React reads
    // state as of its last render).
    if (name === 'group') afterFlush(() => registry.notifyPeers());
    return value;
  }

  const _effectiveGroupRef = useRef(effectiveGroup);
  _effectiveGroupRef.current = effectiveGroup;
  const _endLiftRef = useRef(endLift);
  _endLiftRef.current = endLift;
  const _focusNearRowRef = useRef(focusNearRow);
  _focusNearRowRef.current = focusNearRow;
  const _handleModeRef = useRef(handleMode);
  _handleModeRef.current = handleMode;
  const _handleSelectorRef = useRef(handleSelector);
  _handleSelectorRef.current = handleSelector;
  const _holderKeyRef = useRef(holderKey);
  _holderKeyRef.current = holderKey;
  const _keyForRef = useRef(keyFor);
  _keyForRef.current = keyFor;
  const _keyboardEnabledRef = useRef(keyboardEnabled);
  _keyboardEnabledRef.current = keyboardEnabled;
  const _labelOfRef = useRef(labelOf);
  _labelOfRef.current = labelOf;
  const _loseLiftRef = useRef(loseLift);
  _loseLiftRef.current = loseLift;
  const _onStrayKeyRef = useRef(onStrayKey);
  _onStrayKeyRef.current = onStrayKey;
  const _refocusRowRef = useRef(refocusRow);
  _refocusRowRef.current = refocusRow;
  const _resolveGroupRef = useRef(resolveGroup);
  _resolveGroupRef.current = resolveGroup;
  const _warnIfHandleMissingRef = useRef(warnIfHandleMissing);
  _warnIfHandleMissingRef.current = warnIfHandleMissing;
  useEffect(() => {
    // Kept across a Lit element's disconnect and reconnect (mount runs again).
    if (_instructionsIdRef.current == null) setInstructionsId(nextInstructionsId());
    _warnIfHandleMissingRef.current();
    // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
    // when the options object below references it.
    const sortable = useSortableJS(listEl.current!, {
      items: () => _itemsRef.current,
      onCommit: (next: any) => {
        setItems(next);
      },
      options: {
        animation: _animationRef.current,
        disabled: _disabledRef.current,
        group: _resolveGroupRef.current(),
        handle: _handleRef.current,
        ghostClass: _ghostClassRef.current,
        chosenClass: _chosenClassRef.current,
        dragClass: _dragClassRef.current,
        filter: _filterRef.current,
        forceFallback: _forceFallbackRef.current,
        swapThreshold: _swapThresholdRef.current,
        easing: _easingRef.current,
        ..._optionsRef.current
      },
      // Lit lit-html `repeat` directive caches its part array by sentinel-
      // comment node identity; SortableJS's physical DOM mutation desyncs
      // that cache. The sigil lowers to `__rozieReconcileAfterDomMutation(this)`
      // on Lit (real call) and `void 0` on the other 5 targets (no-op).
      afterCommit: () => void 0,
      // Every pointer event carries the same payload as the keyboard ones, with
      // item-row indices and the raw SortableJS event as `originalEvent`.
      onChange: (c: any) => {
        const payload = {
          interaction: 'pointer' as const,
          item: c.item,
          el: c.el,
          from: c.from,
          to: c.to,
          oldIndex: c.oldIndex,
          newIndex: c.newIndex,
          originalEvent: c.event
        };
        if (c.kind === 'reorder') _onReorderRef.current && _onReorderRef.current(payload);else if (c.kind === 'add') _onAddRef.current && _onAddRef.current(payload);else if (c.kind === 'remove') _onRemoveRef.current && _onRemoveRef.current(payload);
      },
      onStart: (d: any) => {
        // A pointer drag ends any active keyboard lift first.
        if (registry.lift != null) _endLiftRef.current('drop');
        // That lift's `end` (pending until a task) comes before this `start`.
        registry.flushEnds();
        _onStartRef.current && _onStartRef.current({
          interaction: 'pointer',
          item: d.item,
          el: d.el,
          from: d.from,
          to: d.to,
          oldIndex: d.oldIndex,
          newIndex: d.newIndex,
          originalEvent: d.event
        });
      },
      // `end` comes from the list the row ended up in: the destination when it
      // is a SortableList, else (dropped outside, or into a SortableJS list
      // that isn't one of ours) this source list. It goes through the
      // registry's `deferEnd`, like a keyboard `end`: it fires in a task after
      // every list involved has written its items and the re-render those
      // writes scheduled, and before the next drag's or lift's `start`. An
      // unmounted list never emits: if the destination has unmounted by then
      // (in its own `add` handler, say), this list (the origin, which emitted
      // `start`) emits it, `to` still the destination; if both are gone,
      // nothing is emitted.
      scheduleEnd: (d: any) => {
        const dest = registry.entryFor(d.to);
        const destGone = dest == null && d.to !== d.from && registry.wasList(d.to);
        registry.deferEnd((host: any) => {
          const row = d.item === undefined || host.el !== d.to ? null : rowByKey(d.to, host.keyOf(d.item, d.newIndex));
          host.emit('end', {
            interaction: 'pointer',
            item: d.item,
            el: row ?? liveEl(d.el),
            from: d.from,
            to: d.to,
            oldIndex: d.oldIndex,
            newIndex: d.newIndex,
            originalEvent: d.event
          });
        }, destGone ? null : dest ?? entry.current, entry.current);
      }
    });
    instance.current = sortable.instance;
    appliedOptions.current = _optionsRef.current;
    // Runtime `option(name, v)` values this list remembers (Lit keeps them when
    // the element is moved in the DOM and mounts again) apply to the new
    // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
    // first mount.
    const remembered: any = _optionOverridesRef.current;
    if (remembered != null) {
      for (const name of Object.keys(remembered) as any) instance.current.option(name, remembered[name]);
    }
    const listEl$local = listEl.current;
    const stopNative = (ev: any) => {
      if (ev.target === listEl$local) ev.stopPropagation();
    };
    for (const name of SORTABLE_DOM_EVENTS as any) listEl$local?.addEventListener(name, stopNative);
    // A focused row that stops being focusable (its tabindex goes when the
    // keyboard turns off) is blurred at once, during the framework's DOM
    // update, with focus going nowhere (`relatedTarget` null): it would land on
    // <body>. Move it to the list instead.
    const rowBlurred = (ev: any) => {
      if (listEl$local == null) return;
      const row: any = ev.target;
      if (ev.relatedTarget != null || row == null || row.parentNode !== listEl$local) return;
      if (!row.classList.contains('rozie-sortable-item') || row.hasAttribute('tabindex') || !row.isConnected) return;
      if (!listEl$local.hasAttribute('tabindex')) listEl$local.setAttribute('tabindex', '-1');
      listEl$local.focus();
    };
    listEl$local?.addEventListener('focusout', rowBlurred);
    unhookNativeEvents.current = () => {
      for (const name of SORTABLE_DOM_EVENTS as any) listEl$local?.removeEventListener(name, stopNative);
      listEl$local?.removeEventListener('focusout', rowBlurred);
    };

    // Register with the keyboard registry. Other instances call these methods
    // when a keyboard lift hands a row between lists.
    entry.current = {
      el: listEl$local,
      group: () => _effectiveGroupRef.current(),
      label: () => _listLabelRef.current,
      // A handle-mode list without a handle selector has its keyboard off.
      keyboardEnabled: () => _keyboardEnabledRef.current() && !(_handleModeRef.current() && _handleSelectorRef.current() == null),
      items: () => _itemsRef.current,
      keyOf: (item: any, i: any) => String(_keyForRef.current(item, i)),
      labelOf: (item: any, i: any, row: HTMLElement | null = null) => String(_labelOfRef.current(item, i, row)),
      message: (kind: any, ctx: any) => announcementText(_announcementsRef.current, kind, ctx),
      onKey: (key: any, shift: any) => _holderKeyRef.current(key, shift),
      write: (next: any) => {
        setItems(next);
      },
      setLifted: (i: any) => {
        setLiftedIndex(i);
      },
      // The same text twice in a row would not change the region, and a screen
      // reader would not read it again ("Apple is already first", twice): a
      // repeat alternates a trailing no-break space, which is not spoken.
      announce: (text: any) => {
        const next = text !== '' && text === lastSpoken.current ? text + '\u00A0' : text;
        lastSpoken.current = next;
        setAriaLiveText(next);
      },
      focusRow: (item: any, i: any) => _refocusRowRef.current(item, i),
      focusNear: (i: any) => _focusNearRowRef.current(i),
      rowEl: (i: any) => {
        const list = _itemsRef.current;
        if (i < 0 || i >= list.length) return null;
        return rowByKey(listEl$local, String(_keyForRef.current(list[i], i)));
      },
      // Always set (an equal value is a no-op on every target): a compare
      // against $data would read React's render-time ref, stale when two peer
      // changes land in one commit (one list unmounts, another mounts).
      peersChanged: (v: any) => {
        setHasHopPeer(v);
      },
      emit: (name: any, payload: any) => {
        if (name === 'add') _onAddRef.current && _onAddRef.current(payload);else if (name === 'remove') _onRemoveRef.current && _onRemoveRef.current(payload);else if (name === 'reorder') _onReorderRef.current && _onReorderRef.current(payload);else if (name === 'start') _onStartRef.current && _onStartRef.current(payload);else if (name === 'end') _onEndRef.current && _onEndRef.current(payload);
      }
    };
    unregisterEntry.current = registry.register(entry.current);
    const strayKey = (ev: any) => _onStrayKeyRef.current(ev);
    // A pointer press means the user moved on: keys lost to <body> after it
    // are not routed to the lift.
    const pointerPress = () => {
      if (registry.lift != null) registry.lift.focusPending = false;
    };
    document.addEventListener('keydown', strayKey);
    document.addEventListener('pointerdown', pointerPress, true);
    unhookStrayKeys.current = () => {
      document.removeEventListener('keydown', strayKey);
      document.removeEventListener('pointerdown', pointerPress, true);
    };
    // $onMount's cleanup-return: closing over a setup-local (`sortable`) does
    // not survive the Solid emitter's setup/cleanup split — it scopes cleanup
    // outside the setup IIFE. Closing over `instance` / `unregisterEntry`
    // (module-scope `let`s) works on every target.
    return () => {
      instance.current?.destroy();
      // Unmounting while holding a keyboard lift ends it (its `end` comes from
      // the origin list, if that one is still mounted).
      if (registry.lift != null && registry.lift.holder === entry.current) _loseLiftRef.current(true);
      unregisterEntry.current?.();
      unregisterEntry.current = null;
      unhookNativeEvents.current?.();
      unhookNativeEvents.current = null;
      unhookStrayKeys.current?.();
      unhookStrayKeys.current = null;
    };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch0First.current) { _watch0First.current = false; return; }
    const v = props.disabled;
    instance.current?.option('disabled', v);
    setOverride('disabled', v);
  }, [props.disabled]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch1First.current) { _watch1First.current = false; return; }
    const v = props.animation;
    instance.current?.option('animation', liveOption('animation', v));
  }, [props.animation]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch2First.current) { _watch2First.current = false; return; }
    if (!instance.current) return;
    const next = props.options;
    const base = {
      animation: props.animation,
      disabled: props.disabled,
      group: resolveGroup() ?? null,
      handle: props.handle,
      ghostClass: props.ghostClass,
      chosenClass: props.chosenClass,
      dragClass: props.dragClass,
      filter: props.filter,
      swapThreshold: props.swapThreshold,
      easing: props.easing,
      sort: true,
      draggable: ROW_DRAGGABLE
    };
    // A fresh inline function with the same content (React re-renders) is
    // applied so SortableJS runs the newest closure, but it is no change: a
    // runtime `option(name, v)` still in force keeps winning over it.
    const applied = reapplyOptions(instance.current, appliedOptions.current, next, base, {
      keep: (key: any, prev: any) => {
        const ov: any = optionOverrides;
        return ov != null && Object.prototype.hasOwnProperty.call(ov, key) && ov[key] !== prev;
      },
      refreshed: (key: any) => {
        if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.current.option(key));
      }
    });
    appliedOptions.current = next;
    for (const key of applied as any) {
      // The keyboard reads the value SortableJS now runs with. A remembered
      // runtime `animation` / `handle` / `group` is superseded by the newer
      // `options` value.
      if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.current.option(key));else if (TRACKED_OPTIONS.includes(key)) clearOverride(key);
    }
    if (applied.includes('group')) registry.notifyPeers();
  }, [props.options]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch3First.current) { _watch3First.current = false; return; }
    if (!keyboardEnabled()) keyboardTurnedOff();
  }, [optionOverrides, props.disableKeyboard, props.disabled, props.options]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch4First.current) { _watch4First.current = false; return; }
    applyGroup();
  }, [props.group]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch5First.current) { _watch5First.current = false; return; }
    applyGroup();
  }, [props.cloneable]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch6First.current) { _watch6First.current = false; return; }
    const v = props.swapThreshold;
    instance.current?.option('swapThreshold', v);
  }, [props.swapThreshold]);
  useEffect(() => {
    if (_watch7First.current) { _watch7First.current = false; return; }
    const v = props.handle;
    instance.current?.option('handle', liveOption('handle', v));
    warnIfHandleMissing();
  }, [props.handle]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch8First.current) { _watch8First.current = false; return; }
    warnIfHandleMissing();
  }, [props.keyboardTrigger]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch9First.current) { _watch9First.current = false; return; }
    const v = props.ghostClass;
    instance.current?.option('ghostClass', v);
  }, [props.ghostClass]);
  useEffect(() => {
    if (_watch10First.current) { _watch10First.current = false; return; }
    const v = props.chosenClass;
    instance.current?.option('chosenClass', v);
  }, [props.chosenClass]);
  useEffect(() => {
    if (_watch11First.current) { _watch11First.current = false; return; }
    const v = props.dragClass;
    instance.current?.option('dragClass', v);
  }, [props.dragClass]);
  useEffect(() => {
    if (_watch12First.current) { _watch12First.current = false; return; }
    const v = props.filter;
    instance.current?.option('filter', v);
    setOverride('filter', v);
  }, [props.filter]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (_watch13First.current) { _watch13First.current = false; return; }
    const v = props.easing;
    instance.current?.option('easing', v);
  }, [props.easing]);
  useEffect(() => {
    if (_watch14First.current) { _watch14First.current = false; return; }
    const lift = registry.lift;
    if (lift == null || lift.holder !== entry.current) return;
    const i = registry.indexOfLift();
    if (i < 0) {
      loseLift();
      return;
    }
    if (liftedIndex !== i) setLiftedIndex(i);
    // Once the holder has rendered the lifted row, that is the lifted row
    // element. After a hop this drops the source's old row, which the source
    // may reuse for another item (index keys).
    const row = entry.current.rowEl(i);
    if (row != null) lift.liftedRowEl = row;
    focusNearRow(i, lift.key);
  }, [items]); // eslint-disable-line react-hooks/exhaustive-deps

  const _rozieExposeRef = useRef({ getInstance, toArray, sort, option });
  _rozieExposeRef.current = { getInstance, toArray, sort, option };
  useImperativeHandle(ref, () => ({ getInstance: (...args: Parameters<typeof getInstance>): ReturnType<typeof getInstance> => flushSync(() => _rozieExposeRef.current.getInstance(...args)), toArray: (...args: Parameters<typeof toArray>): ReturnType<typeof toArray> => flushSync(() => _rozieExposeRef.current.toArray(...args)), sort: (...args: Parameters<typeof sort>): ReturnType<typeof sort> => flushSync(() => _rozieExposeRef.current.sort(...args)), option: (...args: Parameters<typeof option>): ReturnType<typeof option> => flushSync(() => _rozieExposeRef.current.option(...args)) }), []);

  return (
    <>
    <div {...attrs} className={clsx("rozie-sortable-wrap", (attrs.className as string | undefined))} data-rozie-s-0af24eae="">
      <div className={clsx(['rozie-sortable-list', props.listClass])} ref={listEl} part="list" role="list" aria-label={rozieAttr(props.listLabel)} data-rozie-s-0af24eae="">
        
        {!!((props.renderHeader ?? props.slots?.['header'])) && ((props.renderHeader ?? props.slots?.['header'])?.())}{items.map((item, index) => <div key={keyFor(item, index)} className={clsx(['rozie-sortable-item', itemClassFor(item, index), liftedIndex === index ? 'rozie-sortable-item-lifted' : ''])} style={parseInlineStyle(itemStyleFor(item, index))} data-id={rozieAttr(keyFor(item, index))} role="listitem" tabIndex={(rowTabbable() ? 0 : undefined) ?? undefined} aria-describedby={rozieAttr(rowTabbable() ? instructionsId : undefined)} onKeyDown={($event) => { onRowKeyDown($event, index); }} data-rozie-s-0af24eae="">
          {typeof (props.children ?? props.slots?.['']) === 'function' ? ((props.children ?? props.slots?.['']) as Function)({ item, index, instructionsId }) : (props.children ?? props.slots?.[''])}
        </div>)}
        {!!((props.renderFooter ?? props.slots?.['footer'])) && ((props.renderFooter ?? props.slots?.['footer'])?.())}</div>
      <div className={"rozie-sortable-aria-live"} data-rozie-sortable-aria-live="" aria-live="polite" aria-atomic="true" data-rozie-s-0af24eae="">{ariaLiveText}</div>
      <span hidden={true} id={rozieAttr(instructionsId)} data-rozie-s-0af24eae="">{rozieDisplay(instructionsText())}</span>
    </div>
    </>
  );
});
export default SortableList;
svelte
<script module lang="ts">
/** The kind of message the list speaks during keyboard reordering (a key of the `announcements` prop). */
export type AnnouncementKind = 'lifted' | 'moved' | 'movedToList' | 'dropped' | 'droppedInList' | 'atStart' | 'atEnd' | 'notSortable' | 'noListBefore' | 'noListAfter' | 'cancelledReturnedToList' | 'cancelledReturned' | 'cancelledStays' | 'cancelledRemoved' | 'liftEnded';
/** What an `announcements` function receives. */
export interface AnnouncementContext {
  /** The row's screen-reader label (`labelFor`, else `item.label`, else the row's text). */
  label: string;
  /** The item value. */
  item: unknown;
  /** The name of the list the message is about (`listLabel`, or `list 2 of 3`). */
  list: string;
  /** 1-based position of the row in `list` (kinds that have a position). */
  position?: number;
  /** How many rows `list` holds (kinds that have a position). */
  total?: number;
  /** The list the row came from (`movedToList` only). */
  fromList?: string;
}
/** The `announcements` prop: one optional function per message kind; `null` or `''` says nothing. */
export type Announcements = Partial<Record<AnnouncementKind, (ctx: AnnouncementContext) => string | null | undefined>>;
/** The payload every `start` / `end` / `reorder` / `add` / `remove` event carries, for pointer and keyboard alike. */
export interface SortablePayload {
  /** Which input made the change. */
  interaction: 'pointer' | 'keyboard';
  /** The item's data value (never an element). */
  item: unknown;
  /** The row element; null when there is none (a lost lift, a removed clone copy). */
  el: HTMLElement | null;
  /** The list element the row came from. */
  from: HTMLElement;
  /** The list element the row went to. */
  to: HTMLElement;
  /** Item-row index in `from`; -1 for `add`. */
  oldIndex: number;
  /** Item-row index in `to`; -1 for `remove` and a lost lift. */
  newIndex: number;
  /** Pointer only: the raw SortableJS event. */
  originalEvent?: unknown;
}
/** Which element drives keyboard reordering (the `keyboardTrigger` prop). */
export type SortableKeyboardTrigger = 'row' | 'handle';
/** Which arrow keys move a lifted row within the list (the `orientation` prop). */
export type SortableOrientation = 'vertical' | 'horizontal';
</script>
<script lang="ts">
import { applyListeners, rozieAttr, rozieClass, rozieDisplay, rozieStyle } from '@rozie/runtime-svelte';

import type { Snippet } from 'svelte';
import { onMount, untrack } from 'svelte';

interface Props extends Omit<import('svelte/elements').SvelteHTMLElements['div'], 'items' | 'itemKey' | 'handle' | 'group' | 'animation' | 'disabled' | 'disableKeyboard' | 'keyboardTrigger' | 'options' | 'labelFor' | 'ghostClass' | 'chosenClass' | 'dragClass' | 'filter' | 'easing' | 'forceFallback' | 'swapThreshold' | 'cloneable' | 'listClass' | 'itemClass' | 'listLabel' | 'orientation' | 'pageStep' | 'keyboardInstructions' | 'announcements' | 'itemStyle' | 'header' | 'children' | 'footer' | 'snippets' | 'onreorder' | 'onadd' | 'onremove' | 'onstart' | 'onend'> {
  /**
   * The bound items array. The sole `model: true` prop — two-way bind it (`r-model:items` / `v-model:items` / `bind:items` / `[(items)]`) and SortableList writes the re-ordered array back whenever a drag, cross-list move, or keyboard reorder commits, with no manual `onChange → setState` wiring.
   * @example
   * <SortableList bind:items={todos} itemKey="id" />
   */
  items?: any[];
  /**
   * The per-row key the framework reconciler tracks each item by across a reorder — either a property name (e.g. `itemKey="id"` reads `item.id`) or an `(item, index) => key` function. With neither, id-less object items get a stable synthetic key via an internal `WeakMap` (survives reorder by object identity); primitive items fall back to index — pass a function for reorderable duplicate primitives.
   */
  itemKey?: (string | ((...args: any[]) => any)) | null;
  /**
   * CSS selector identifying the per-row drag handle, so a drag starts only from that element rather than anywhere in the row. Authored class names render literally on every target (React included), so a plain `.grip` works; `$classSelector('grip')` is an optional, typo-checked way to author it. `options.handle` and `option('handle', v)` win over this prop, for the keyboard (`keyboardTrigger: 'handle'`) as for the mouse.
   */
  handle?: (string) | null;
  /**
   * SortableJS group name enabling cross-list drag — two lists sharing a `group` accept items between each other (the source fires `remove`, the destination fires `add`). Set `cloneable: true` to flip a string group into clone-mode. Lists that share a `group` also exchange rows by keyboard: Shift+arrow while a row is lifted hops it to the previous or next list of the same group (in source order), subject to the same pull/put rules as a mouse drag. `options.group` takes precedence over this prop, for keyboard hops as for drags. Function-valued `pull`/`put` cannot be evaluated without a drag, so those lists are unreachable by keyboard. Set `itemKey` on grouped lists.
   */
  group?: (string) | null;
  /**
   * Reorder animation duration in milliseconds. `0` disables the animation. Reapplied live via `instance.option('animation', v)` (no remount). `options.animation`, and a runtime `option('animation', v)`, win over this prop.
   */
  animation?: number;
  /**
   * Temporarily disable dragging without unmounting — reapplied live via `instance.option('disabled', v)` (no remount). Also suppresses keyboard reordering: a disabled list is not sortable by any input, so rows lose their `tabindex` and the keydown handler no-ops. Turning it on while a row is lifted ends the lift where the row is (`Lift ended`, and `end` fires); `options.disabled` and `option('disabled', v)` do the same.
   */
  disabled?: boolean;
  /**
   * Opt out of keyboard reordering (Space lift / Arrow move / Shift+Arrow hop between lists / Esc cancel / Enter drop) while leaving pointer drag enabled. Rows drop out of the tab order (no `tabindex`) and the keydown handler no-ops. Keyboard access is gated on `!disabled && !disableKeyboard`. Turning it on while a row is lifted ends the lift where the row is.
   */
  disableKeyboard?: boolean;
  /**
   * Which element drives keyboard reordering. `'row'` (default): rows are tab stops and the keys on the focused row drive reordering. `'handle'`: rows are NOT tab stops, and only keys pressed inside the element matched by `handle` (inside that row) drive the same Space/Enter lift-drop, Arrow move, Shift+Arrow hop and Escape cancel flow; handled keys call preventDefault so a handle `<button>`'s click does not fire. The consumer owns the handle markup (recommended: a `<button>` with its own aria-label such as "Reorder Hero banner") and the component adds no tabindex or role to slot content. `'handle'` without `handle` turns keyboard reordering off and logs a console warning. `disabled`/`disableKeyboard` still apply. Typed as `SortableKeyboardTrigger` (`'row' | 'handle'`); at runtime any value other than `'handle'` behaves as `'row'`.
   */
  keyboardTrigger?: SortableKeyboardTrigger;
  /**
   * Verbatim SortableJS options pass-through for anything not covered by the named props. The named props win on key conflict but `options` lands AFTER them in the merge so consumers can override defaults; handler keys (`onStart`, `onEnd`, `onUpdate`, `onAdd`, `onRemove`, `onClone`) are stripped — the helper owns those paths. Runtime-updatable: when `options` changes, each key whose value changed is reapplied via `instance.option(key, v)` (no remount), so mouse and keyboard obey the same values; a key you drop goes back to its named prop (or, for `sort` and `draggable`, the component default), and any other dropped key keeps its last value until you set it. `forceFallback` is still read only at construction.
   */
  options?: any;
  /**
   * Optional `(item, idx) => string` returning the screen-reader label for the aria-live announcer during keyboard drag. Defaults to `item.label`; without a `label` field, the row's text (whitespace collapsed, without nested lists or hidden content), else `String(item)` for a primitive, else `item {position}`.
   */
  labelFor?: ((...args: any[]) => any) | null;
  /**
   * Class name applied to the drop-placeholder (ghost) element while dragging. Forwarded live via `instance.option`, so toggling it at runtime takes effect without a remount.
   */
  ghostClass?: (string) | null;
  /**
   * Class name applied to the currently-chosen item while dragging. Forwarded live via `instance.option` (no remount needed to change it).
   */
  chosenClass?: (string) | null;
  /**
   * Class name applied to the dragging element. Only takes effect in fallback mode (`forceFallback: true`). Forwarded live via `instance.option`.
   */
  dragClass?: (string) | null;
  /**
   * CSS selector that prevents drag initiation on matching rows (locked items). SortableJS checks it at `mousedown`/`touchstart` and aborts the drag if it matches. The keyboard honours it too: a row that matches (the row element, or its slot root: the row template's single element when nothing else sits beside it) cannot be lifted with Space/Enter; any other matching control (a `.js-remove` button, an `input`) blocks only presses on itself. `options.filter` (which may also be a SortableJS filter function) takes precedence. A `data-*` attribute selector (e.g. `[data-locked]`) is the most robust choice across all targets.
   */
  filter?: (string) | null;
  /**
   * CSS easing function for the reorder animation (e.g. `'ease-in'`, `'cubic-bezier(0.4, 0, 0.2, 1)'`). Runtime-updatable.
   */
  easing?: (string) | null;
  /**
   * Force SortableJS's mouse-event drag path over HTML5 DnD — useful for touch devices, consistent cross-browser behavior, and synthetic test drivers (and `dragClass` only applies in this mode). **Construction-time only**: SortableJS reads it once at construction, so re-key the `<SortableList>` to toggle it at runtime.
   */
  forceFallback?: boolean;
  /**
   * SortableJS swap threshold (0..1) — a lower value makes rows swap earlier as the dragged item overlaps a neighbor. Reapplied live via `instance.option('swapThreshold', v)` — SortableJS reads it on every dragover, so no remount is needed.
   */
  swapThreshold?: number;
  /**
   * High-level prop that REPLACES a string `group` with SortableJS's `{ name, pull: 'clone', put: false }` clone-mode object form — the source deposits a COPY onto the destination and keeps its own array unchanged, and takes nothing back: no row can be dropped or keyboard-hopped into it (the palette → canvas pattern). With `group: null` it is a no-op (a clone-mode list with no group name has no peer to clone into). Reapplied live — toggling `cloneable` (or changing `group`) recomputes the clone-mode shape and reapplies it via `instance.option('group', …)`, no remount.
   */
  cloneable?: boolean;
  /**
   * Extra class(es) merged onto the list container (the SortableJS root) alongside the base `rozie-sortable-list` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding), normalized identically across all six targets — the hook for bridging a CSS framework (`.list-group`) or a flex/grid parent onto the component.
   */
  listClass?: string | any[] | any;
  /**
   * Extra class(es) merged onto every item row alongside the base `rozie-sortable-item` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding) applied uniformly, OR an `(item, index) => class` function for per-row classes evaluated at render time. Normalized identically across all six targets.
   */
  itemClass?: string | any[] | any | ((...args: any[]) => any);
  /**
   * The list's human name, such as `"Top sidebar"`. Sets `aria-label` on the list container (`role="list"`) and names the list in keyboard announcements when a row moves between lists (`Moved Hero banner to Top sidebar, position 1 of 4`, `Dropped Hero banner in Top sidebar at position 3 of 4`, `No list after Top sidebar`). Pass the same words as the zone's visible heading. With no label, announcements fall back to a neutral `list 2 of 3`, counting the mounted lists of the same group in hop (source) order.
   */
  listLabel?: (string) | null;
  /**
   * Which arrow keys move a lifted row within the list: `'vertical'` (default) uses ↑/↓, `'horizontal'` uses ←/→. A horizontal list's default spoken instructions say "Use the left and right arrow keys to move" (`role="list"` has no `aria-orientation`). Typed as `SortableOrientation` (`'vertical' | 'horizontal'`).
   */
  orientation?: SortableOrientation;
  /**
   * How many positions Page Up / Page Down move a lifted row. The move stops at the first or last position when fewer rows remain.
   */
  pageStep?: number;
  /**
   * Replaces the spoken keyboard instructions. The text sits in a hidden element referenced by `aria-describedby` from each tabbable row (row mode) or from the consumer's handle via the `instructionsId` slot prop (handle mode). Default: "Press Space or Enter to pick up, and again to drop. Use the up and down arrow keys to move, Home and End to jump to the start or end, Page Up and Page Down to move several places, and Escape to cancel." (with `orientation: 'horizontal'`, "the left and right arrow keys"; a `sort: false` list says only "Press Space or Enter to pick up, and again to drop. Press Escape to cancel."). When another mounted list could take this list's rows (by the group rules of `group`, `options.group` or `option('group', v)`), the default adds "Hold Shift with an arrow key to move to another list." (updated as lists mount, unmount or change group).
   */
  keyboardInstructions?: (string) | null;
  /**
   * Rewords or translates what the list says during keyboard reordering. An object of optional functions keyed by message kind (`lifted`, `moved`, `movedToList`, `dropped`, `droppedInList`, `atStart`, `atEnd`, `notSortable`, `noListBefore`, `noListAfter`, `cancelledReturnedToList`, `cancelledReturned`, `cancelledStays`, `cancelledRemoved`, `liftEnded`). Each receives a context (`label`, `item`, `list`, and for kinds with a position `position` (1-based) and `total`; `movedToList` also `fromList`) and returns the text to speak; `null` or `''` says nothing. Kinds without a function keep the default English text (see "Announcements"). Define the object in your script and bind it (Angular templates reject inline arrow functions), e.g. `const announcements = { moved: ({ label, position, total }) => label + ' → ' + position + '/' + total }`. Typed as `Announcements`, exported with `AnnouncementKind` and `AnnouncementContext`.
   * @example
   * <SortableList bind:items={todos} announcements={announcements} />
   */
  announcements?: (Announcements) | null;
  /**
   * Per-row inline style applied to the `.rozie-sortable-item` wrapper. Accepts a CSS `String`, a flat style object (`Record<string, string | number>`), or an `(item, index) => string | object` function for per-row styling. Because it lands on the wrapper — the direct child of the list container — it can drive CSS-grid placement (`grid-column` / `grid-row` / `align-self`) when `listClass` sets `display: grid`. Normalized per target; `null` / empty drops the attribute.
   */
  itemStyle?: (string | any | ((...args: any[]) => any)) | null;
  header?: Snippet;
  children?: Snippet<[{ item: any; index: any; instructionsId: any }]>;
  footer?: Snippet;
  snippets?: Record<string, any>;
  onreorder?: (payload: SortablePayload) => void;
  onadd?: (payload: SortablePayload) => void;
  onremove?: (payload: SortablePayload) => void;
  onstart?: (payload: SortablePayload) => void;
  onend?: (payload: SortablePayload) => void;
}

let __defaultOptions = (() => ({}))();

let {
  items = $bindable((() => [])()),
  itemKey = null,
  handle = null,
  group = null,
  animation = 150,
  disabled = false,
  disableKeyboard = false,
  keyboardTrigger = 'row',
  options = __defaultOptions,
  labelFor = null,
  ghostClass = null,
  chosenClass = null,
  dragClass = null,
  filter = null,
  easing = null,
  forceFallback = false,
  swapThreshold = 1,
  cloneable = false,
  listClass = '',
  itemClass = '',
  listLabel = null,
  orientation = 'vertical',
  pageStep = 5,
  keyboardInstructions = null,
  announcements = null,
  itemStyle = null,
  header: __headerProp,
  children: __childrenProp,
  footer: __footerProp,
  snippets,
  onreorder,
  onadd,
  onremove,
  onstart,
  onend,
  ...__rozieAttrs
}: Props = $props();

const header = $derived(__headerProp ?? snippets?.header);
const children = $derived(__childrenProp ?? snippets?.children);
const footer = $derived(__footerProp ?? snippets?.footer);

let liftedIndex: any = $state(null);
let ariaLiveText = $state('');
let instructionsId: any = $state(null);
let optionOverrides = $state({});
let hasHopPeer = $state(false);

let listEl = $state<HTMLElement | undefined>(undefined);

import { ROW_DRAGGABLE, orderByKeys, reapplyOptions, useSortableJS } from './internal/useSortableJS';
import { afterFlush, canHop, getKeyboardRegistry, isRenderable, nextInstructionsId, rowLiftable } from './internal/keyboardRegistry';
import { announcementText, defaultInstructions, fallbackLabel } from './internal/announcements';
let instance: any = null;
// The `options` object SortableJS was last given (see the `options` watcher).
let appliedOptions: any = null;
// Keyboard lift state lives in the shared registry (one active keyboard lift
// per page, so a later task can hand a lifted row between lists).
// `$data.liftedIndex` is only its mirror, for the lifted-row styling.
const registry = getKeyboardRegistry();
// This list's registry entry (a ListEntry), built and registered in $onMount.
let entry: any = null;
let unregisterEntry: any = null;
// Removes the listeners that keep SortableJS's own DOM events inside the list.
let unhookNativeEvents: any = null;
// Removes the document keydown listener that catches keys lost to <body>.
let unhookStrayKeys: any = null;
// SortableJS also dispatches its events as BUBBLING native DOM events
// (`start`, `end`, `add`, `remove`, `change`, …) on the list element, before
// it calls the option callbacks. An output binding on the component host
// (Angular's `(start)` / `(end)` / `(add)` / `(remove)`, a Lit listener) also
// catches a native DOM event of the same name, so a consumer would get the raw
// SortableJS event as an extra event. The component re-emits the committed
// events itself, so stop the raw ones at the list element (only events
// dispatched ON the list — an `<input>`'s own `change` is untouched).
const SORTABLE_DOM_EVENTS = ['choose', 'unchoose', 'start', 'end', 'add', 'update', 'sort', 'remove', 'filter', 'clone', 'change', 'select', 'deselect'];
// role="list" takes no aria-orientation, so a horizontal list says which
// arrow keys move in its instructions instead. A `sort: false` list leaves out
// the move sentence, and a list whose rows another mounted list could take
// (by the group SortableJS runs with, `options.group` included) says how to
// hop.
const instructionsText = () => {
  if (keyboardInstructions != null) return keyboardInstructions;
  return defaultInstructions({
    horizontal: orientation === 'horizontal',
    sortable: liveOption('sort', true) !== false,
    grouped: effectiveGroup() != null && hasHopPeer
  });
};
// Instance-scoped synthetic-id store for id-less object items. Keyed by object
// IDENTITY, so the same object keeps its synthetic id across a reorder (the
// framework reconciler then rebinds the row component instance to its ORIGINAL
// item, not its slot position — the data-corruption fix).
//
// Phase 73 item #11-b removed the former "fold the WeakMap + counter into ONE
// member-mutated object const" workaround: `hoistModuleLet`'s reachability
// walk now also roots at helpers called ONLY from a template expression
// (`keyFor` is called from `:key`/`:data-id`, never from a hook), so the bare
// `let __rowKeySeq = 0` below hoists to a `useRef` on React exactly like the
// hook-reached case — no more per-render reset. Verified in codegen.
const __rowKeyMap = new WeakMap();
let __rowKeySeq = 0;
// 4-tier per-row key precedence. Its return feeds BOTH :key and :data-id.
const keyFor = (item: any, index: any) => {
  // (a) function itemKey: consumer-supplied (item, index) => key.
  if (typeof itemKey === 'function') {
    return itemKey(item, index);
  }
  // (b) string itemKey: a property name on a non-null object item.
  if (typeof itemKey === 'string' && item !== null && typeof item === 'object' && item[itemKey] != null) {
    return item[itemKey];
  }
  // (c) id-less object (or function) item: assign-on-first-sight WeakMap
  //     synthetic id. Survives reorder because it is keyed by object identity.
  if (item !== null && typeof item === 'object' || typeof item === 'function') {
    if (!__rowKeyMap.has(item)) {
      __rowKeyMap.set(item, '__rk' + __rowKeySeq++);
    }
    return __rowKeyMap.get(item);
  }
  // (d) primitive item: fall back to index. NOTE: duplicate primitives are
  //     unsafe to reorder this way — pass a function itemKey for those.
  return index;
};
// Resolve the SortableJS `group` option: `cloneable` is a high-level Rozie
// prop that REPLACES a string `group` with SortableJS's
// `{ name, pull: 'clone', put: false }` clone-mode object form (a palette
// takes nothing back, by mouse or keyboard). When
// `cloneable:false`, pass `$props.group` through verbatim. When
// `cloneable:true` AND `$props.group` is null, leave it null — a clone-mode
// list without a group name is not meaningful (no peer list can join the
// cross-list flow). Shared by $onMount construction AND the group/cloneable
// $watch reconcile below — single source of truth, no duplicated ternary.
const resolveGroup = () => cloneable && typeof group === 'string' ? {
  name: group,
  pull: 'clone' as const,
  put: false as const
} : group ?? undefined;
// The group SortableJS actually runs with: a runtime `option('group', v)`,
// else `options.group` (it lands after the named props in the merge), else
// the `group` / `cloneable` props. Keyboard hops follow the same rules as the
// mouse, so they read this one.
const effectiveGroup = () => {
  const ov: any = optionOverrides;
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, 'group')) return ov.group;
  const o: any = options;
  return o != null && o.group != null ? o.group : resolveGroup();
};
// Resolve itemClass for a row: a static value (string | array | object) OR a
// per-row (item, index) => class function. The result is fed into the :class
// array and normalized by each target's class path (rozieClass / clsx / native).
const itemClassFor = (item: any, index: any) => {
  const v = itemClass;
  return typeof v === 'function' ? v(item, index) : v;
};
// Resolve itemStyle for a row: a static value (string | object) OR a per-row
// (item, index) => style function. Returns string | object | null; the dynamic
// :style binding normalizes it per target. null / empty → attribute dropped.
const itemStyleFor = (item: any, index: any) => {
  const s = typeof itemStyle === 'function' ? itemStyle(item, index) : itemStyle;
  return s == null || s === '' ? null : s;
};
// Read the display label for an item — used by the aria-live announcer.
// Phase 16 R7 / D-08: $props.labelFor reads as `null` on all 6 targets when
// the consumer omits it (Plan 16-01 prop-default coercion fix); the check is
// a plain null compare — NO runtime callable-type coercion. Without
// `labelFor` or a `label` field, the row's text (`row`), else `String(item)`
// for a primitive, else `item {position}`.
const labelOf = (item: any, idx: any, row: HTMLElement | null = null) => {
  if (labelFor !== null) return labelFor(item, idx);
  if (item !== null && typeof item === 'object' && item.label != null) return item.label;
  return fallbackLabel(item, idx, row);
};
// The text this list's live region showed last (see the registry entry's
// `announce`).
let lastSpoken = '';
// Keyboard handler (Phase 16 R7): Space/Enter lift and drop; while lifted,
// ArrowUp/ArrowDown (ArrowLeft/ArrowRight when horizontal), Home/End and
// PageUp/PageDown move the row, and Escape returns it to where it was lifted
// from. The lift itself lives in the shared keyboard registry. After
// any array-reorder write, refocusRow() keeps focus on the moved row (or its
// handle) on all six targets.
//
// Note: `index` is passed directly as a number. Plan 16-02 (Solid call-arg
// accessor unwrap) ensures Solid's <For> alias unwraps to `index()` at the
// call site — no runtime callable-type coercion needed in user source.
// Keyboard reordering is available only when the list is not disabled AND the
// `disableKeyboard` opt-out is off. Drives BOTH the row tabindex (rows are
// focusable only when reorderable) and the onRowKeyDown guard below. Reads
// straight off $props so the tabindex binding re-evaluates reactively when
// `disabled`/`disableKeyboard` toggle at runtime.
//
// The keyboard follows the SortableJS options the mouse obeys: `disabled`
// (the prop, `options.disabled`, or `option('disabled', v)`), `filter` and
// `draggable` (which rows lift, see rowLiftable) and `sort: false` (no moves
// within the list). `liveOption` reads the value SortableJS runs with: one set
// at runtime, else `options`, else the named prop.
const KEYBOARD_OPTIONS = ['disabled', 'filter', 'draggable', 'sort'];
const liveOption = (name: any, fallback: any) => {
  const ov: any = optionOverrides;
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, name)) return ov[name];
  const o: any = options;
  if (o != null && o[name] !== undefined) return o[name];
  return fallback;
};
const setOverride = (name: any, value: any) => {
  optionOverrides = {
    ...optionOverrides,
    [name]: value
  };
};
const clearOverride = (name: any) => {
  const ov: any = optionOverrides;
  if (ov == null || !Object.prototype.hasOwnProperty.call(ov, name)) return;
  const next = {
    ...ov
  };
  delete next[name];
  optionOverrides = next;
};
// Options whose runtime value (`option(name, v)`) is remembered, so a later
// change of the matching prop doesn't overwrite it: the keyboard ones, plus
// `animation`, `handle` and `group` (runtime override → `options` → prop).
const TRACKED_OPTIONS = [...KEYBOARD_OPTIONS, 'animation', 'handle', 'group'];
const keyboardEnabled = () => !disableKeyboard && !liveOption('disabled', disabled);
// The handle selector SortableJS runs with (`option('handle', v)`, else
// `options.handle`, else the `handle` prop): the keyboard reads the same one.
const handleSelector = () => liveOption('handle', handle);
// keyboardTrigger='handle' mode: rows are not tab stops and the keys are read
// from the consumer's handle element instead. Any other value is 'row' mode.
const handleMode = () => keyboardTrigger === 'handle';
// Rows are tab stops only in row mode (and only while keyboard is enabled).
const rowTabbable = () => keyboardEnabled() && !handleMode();
// One-time-per-change dev warning: handle mode needs a handle selector. Without
// one the keyboard is OFF (see the onRowKeyDown gate) — never a silent fallback
// to row mode, which would re-introduce the tab stops the consumer opted out of.
const warnIfHandleMissing = () => {
  if (handleMode() && handleSelector() == null) {
    console.warn('[rozie-sortable-list] keyboardTrigger is "handle" but no handle selector is set, so keyboard reordering is off. Pass a handle selector (e.g. handle=".grip") or use keyboardTrigger "row".');
  }
};
// True only when a keydown originated inside a `handle` element that belongs to
// THIS row. Walks the COMPOSED ancestor chain from the event target up to (but
// excluding) the row (currentTarget): assignedSlot -> parentNode -> shadow host.
// Plain closest()/contains() stop at a shadow boundary, and Lit renders a Rozie
// consumer's slot content inside the SortableList shadow root while plain-HTML
// consumers project light-DOM nodes through a <slot>. composedPath() is not
// used because React's synthetic event does not expose it. Another
// .rozie-sortable-item met first means the key came from a NESTED list's row,
// which must not reorder this (outer) list.
const isHandleKeyOrigin = ($event: any) => {
  const sel = handleSelector();
  if (sel == null) return false;
  const row = $event.currentTarget;
  let n: any = $event.target;
  while (n && n !== row) {
    if (n.nodeType === 1) {
      if (n.matches(sel)) {
        // Matched a handle: it counts only if this row is reachable from here
        // without crossing a different sortable item.
        let m: any = n.assignedSlot ?? n.parentNode ?? n.host;
        while (m && m !== row) {
          if (m.nodeType === 1 && m.classList.contains('rozie-sortable-item')) return false;
          m = m.assignedSlot ?? m.parentNode ?? m.host;
        }
        return m === row;
      }
      if (n.classList.contains('rozie-sortable-item')) return false;
    }
    n = n.assignedSlot ?? n.parentNode ?? n.host;
  }
  return false;
};
// Put focus back on the MOVED row (row mode) or its handle (handle mode) after
// a reorder write. Looks the row up by KEY (data-id), not by index, so it finds
// the moved row whether this runs before the framework commit (the row element
// is the same one) or after it (Svelte/Solid/Lit re-create the DOM) — and it is
// correct for index-keyed primitive lists too. Direct children of the list
// container only: that skips nested-list rows and the header/footer slot
// content.
//
// Two passes. (1) A microtask covers targets that commit synchronously or in an
// earlier microtask (Vue's scheduler flush is queued by the model write, before
// this one). (2) A timer + rAF "heal" pass covers targets whose DOM commit is
// scheduled AFTER the key handler returns (Angular): the commit can MOVE the
// focused row, and moving a focused node blurs it, so a Home/End/Escape jump or
// a rapid Space/Arrow/Arrow/Space burst would otherwise end with focus on
// <body>. The heal pass never steals: it acts only when focus has been lost to
// <body>. (`$restoreFocus(selector, index)` is not enough here: it is a no-op on
// Vue/Angular, where a long jump moves the focused row itself, and it looks the
// row up by index, which can land on a neighbour on Lit.) The $refs read
// happens here, synchronously, inside an event handler — which is safe.
const refocusRow = (item: any, idx: any) => {
  const listEl$local = listEl;
  const sel = handleSelector();
  const useHandle = handleMode();
  const key = String(keyFor(item, idx));
  // While this refocus is outstanding, a key that falls to <body> belongs to
  // the lift (see onStrayKey). Cleared once the row has focus again, or by a
  // pointer press anywhere.
  const pending = registry.lift;
  if (pending != null) pending.focusPending = true;
  const focusIt = (onlyIfLost: any) => {
    if (!listEl$local) return;
    if (useHandle && sel == null) return;
    if (onlyIfLost && document.activeElement && document.activeElement !== document.body) return;
    for (const row of Array.from(listEl$local.children) as any[]) {
      if (row.getAttribute('data-id') === key) {
        const target = useHandle ? row.querySelector(sel) : row;
        if (target && typeof target.focus === 'function') {
          target.focus();
          const l = registry.lift;
          if (l != null && l === pending && l.key === key) {
            l.focusPending = false;
            // This row is the lifted row element now (see the items watcher).
            l.liftedRowEl = row;
          }
        }
        return;
      }
    }
  };
  queueMicrotask(() => focusIt(false));
  setTimeout(() => focusIt(true), 0);
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => focusIt(true));
};
// `el` in an event payload: the row element while it is in the page, else
// null (a row that left with an unmounted list is no row of any list).
const liveEl = (el: any) => el != null && el.isConnected ? el : null;
// The row element carrying `data-id === key` among a list element's direct
// children (skips nested-list rows and header/footer slot content).
const rowByKey = (listEl: any, key: any) => {
  if (!listEl || key == null) return null;
  for (const row of Array.from(listEl.children) as any[]) {
    if (row.getAttribute('data-id') === key) return row;
  }
  return null;
};
// After the consumer changed the items of the list holding a lift, put focus
// on the row (or its handle) whose key is `key`, else the row nearest `index`
// (or the list itself when it has no rows left) — but only once focus has fallen to <body> (the focused row's element went
// away: the lift was lost, or a framework that keys rows by object identity
// re-created the lifted row). Never steals focus from anywhere else. Same
// three passes as refocusRow, for targets that commit late.
const focusNearRow = (index: number, key: string | null = null) => {
  const listEl$local = listEl;
  const sel = handleSelector();
  const useHandle = handleMode();
  const focusIt = () => {
    if (!listEl$local) return;
    if (useHandle && sel == null) return;
    if (document.activeElement && document.activeElement !== document.body) return;
    const rows = Array.from(listEl$local.children).filter((r: any) => r.hasAttribute('data-id') && r.classList.contains('rozie-sortable-item')) as any[];
    if (rows.length === 0) {
      // The list is now empty: focus the list itself (out of the tab order)
      // so keyboard and screen-reader users stay where they were.
      if (!listEl$local.hasAttribute('tabindex')) listEl$local.setAttribute('tabindex', '-1');
      listEl$local.focus();
      return;
    }
    const row = rows.find((r: any) => key != null && r.getAttribute('data-id') === key) ?? rows[Math.max(0, Math.min(rows.length - 1, index))];
    const target = useHandle ? row.querySelector(sel) : row;
    if (target && typeof target.focus === 'function') target.focus();
  };
  queueMicrotask(focusIt);
  setTimeout(focusIt, 0);
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(focusIt);
};
// Speak `text` from `target`'s aria-live region. The region that spoke last
// is cleared when it belongs to another list, so a message is heard once, from
// the list the row is in now, and never from a list that just lost it.
const speak = (target: any, text: any) => {
  const prev = registry.speaker;
  if (prev != null && prev !== target && registry.has(prev)) prev.announce('');
  registry.speaker = target;
  target.announce(text);
};
// Say announcement `kind` from `target`, in `target`'s words: its
// `announcements` function for that kind, else the default text (see
// ./internal/announcements). `index` is the row's 0-based position in
// `target`, `row` the row element its label is read from (when there is no
// `labelFor` or `label` field), and `total` how many rows `target` holds after
// the change (null for the kinds without a position). A function returning
// null or '' clears the region, so nothing is said.
const say = (target: any, kind: AnnouncementKind, item: unknown, index: number, row: HTMLElement | null, total: number | null = null, fromList: any = null) => {
  const ctx: any = {
    item,
    list: registry.listName(target)
  };
  // The label is read only when the text needs it (a default with `{label}`,
  // or an override that reads `label`), so `labelFor` is not called for a
  // message that doesn't name the row (`Lift ended`: the item has left).
  let label: string | null = null;
  Object.defineProperty(ctx, 'label', {
    enumerable: true,
    get: () => {
      if (label === null) label = target.labelOf(item, index, row);
      return label;
    }
  });
  if (total != null) {
    ctx.position = index + 1;
    ctx.total = total;
  }
  if (fromList != null) ctx.fromList = registry.listName(fromList);
  speak(target, target.message(kind, ctx));
};
// The lifted item is no longer in the list holding it: the consumer changed
// that list's items (or re-keyed the item), or the list is unmounting. End the
// lift without writing anything (the item is wherever the consumer's data put
// it). `end` still fires once, with `item` = the lifted value and `el: null`
// (there is no row), so keyboard `start` / `end` pair (unless the holder and the origin have both unmounted). Lost to a consumer change (not an
// unmount), the holder says `Lift ended` and, if focus fell to <body> with the
// row, focuses its row nearest where the lifted row was.
const loseLift = (unmounting = false) => {
  const lift = registry.lift;
  if (!lift) return;
  const h = lift.holder;
  registry.lift = null;
  h.setLifted(null);
  if (!unmounting) {
    say(h, 'liftEnded', lift.item, lift.index ?? lift.origin.index, lift.liftedRowEl);
    h.focusNear(lift.index ?? lift.origin.index);
  }
  const payload = {
    interaction: 'keyboard' as const,
    item: lift.item,
    el: null,
    from: lift.origin.list.el,
    to: h.el,
    oldIndex: lift.origin.index,
    newIndex: -1
  };
  // Like every `end`, in a task after the writes, from the holder. An
  // unmounted list never emits (Angular rejects an emit from a destroyed
  // component): when the holder is unmounting, the origin list (which emitted
  // `start`) ends the lift if it is still mounted, so `start` and `end` pair;
  // if it is gone too, nothing is emitted.
  registry.deferEnd((host: any) => host.emit('end', payload), h, lift.origin.list);
};
// Keyboard `start` / `end` (the same payload as every other event): `item` is
// the item value, `el` its row element. `start` fires from the origin list
// (`from`), `end` from the list the row ends up in (`to`). `el` is the row in
// that list when it is rendered, else `fallbackEl` (the row element the move
// started from, before a target re-rendered). `end` is called after
// `registry.lift` is cleared, so a consumer `end` handler that writes the
// items (re-keying a clone copy) is not mistaken for a lost lift, and it is
// emitted in a task (`registry.deferEnd`), after the writes AND the re-render
// they schedule: a consumer `end` handler reads the new state on every target
// (React included, whose handler closure is the one from the latest render).
// If `to` has unmounted by then, `from` (the origin, which emitted `start`)
// emits it instead, `to` unchanged in the payload; an unmounted list never
// emits.
const keyboardStartEnd = (name: any, lift: any, from: any, to: any, oldIndex: any, newIndex: any, fallbackEl: HTMLElement | null = null) => {
  const fire = (host: any) => host.emit(name, {
    interaction: 'keyboard',
    item: lift ? lift.item : null,
    el: (lift && host === to ? rowByKey(host.el, lift.key) : null) ?? liveEl(fallbackEl),
    from: from.el,
    to: to.el,
    oldIndex,
    newIndex
  });
  if (name === 'end') registry.deferEnd(fire, to, from);else fire(from);
};
// Move the lifted row to `toIndex` (clamped) within the list holding it.
// Works through the registry entry, so it acts on the current holder. `dir`
// is the key's direction (-1 toward the start), for when the row can't move.
const moveLiftTo = (toIndex: any, dir: any) => {
  const lift = registry.lift;
  if (!lift) return;
  const h = lift.holder;
  const from = registry.indexOfLift();
  if (from < 0) {
    loseLift();
    return;
  }
  const items = h.items();
  const to = Math.max(0, Math.min(items.length - 1, toIndex));
  // The moved row's element, read before the write (an index key changes).
  const el = h.rowEl(from);
  if (to === from) {
    // Nowhere to go: say so (the row is already at that end).
    say(h, dir < 0 ? 'atStart' : 'atEnd', items[from], from, el ?? lift.liftedRowEl, items.length);
    return;
  }
  const next = [...items];
  const [moved] = next.splice(from, 1);
  next.splice(to, 0, moved);
  // Index keys (primitive items without itemKey) change with the position.
  // Update the lift BEFORE writing: a target whose watchers run synchronously
  // on the write must already see where the row is going.
  lift.key = h.keyOf(moved, to);
  lift.index = to;
  h.write(next);
  h.setLifted(to);
  // Name the row that MOVED from the local `moved` item: on React/Vue/Lit the
  // items prop still holds the pre-write array here. Labels come from the
  // holder's own `labelFor`.
  say(h, 'moved', moved, to, el, items.length);
  h.focusRow(moved, to);
  h.emit('reorder', {
    interaction: 'keyboard',
    item: moved,
    el,
    from: h.el,
    to: h.el,
    oldIndex: from,
    newIndex: to
  });
};
// Hop the lifted row to the next (`dir` 1) or previous (-1) list it could
// also reach by mouse, in composed-tree source order. One hand-off: the source
// writes its items without the row, the destination writes them with it, and
// the destination becomes the holder. As with the mouse, the destination
// emits `add` first, then the source emits `remove`. A forward hop lands
// first, a backward hop lands last.
const hop = (dir: any) => {
  const lift = registry.lift;
  if (!lift) return;
  const from = lift.holder;
  const i = registry.indexOfLift();
  if (i < 0) {
    loseLift();
    return;
  }
  const fromItems = from.items();
  const data = fromItems[i];
  const el = from.rowEl(i);
  // Keep the lifted row element current: lists nested inside it (a grid
  // widget's columns) are never hop targets. Before a target re-renders the
  // row may not exist yet, so keep the last known element then.
  lift.liftedRowEl = el ?? lift.liftedRowEl;
  const to = registry.findHopTarget(from, dir);
  if (to == null) {
    say(from, dir === 1 ? 'noListAfter' : 'noListBefore', data, i, el ?? lift.liftedRowEl);
    return;
  }
  const origin = lift.origin;
  const toItems = to.items();
  // A clone copy hopping back into the list it was cloned from merges with
  // its original there (that list never gave it up), rather than adding a
  // second row with the same key.
  if (lift.copy && to === origin.list) {
    let home = toItems.indexOf(data);
    if (home < 0) home = Math.max(0, Math.min(toItems.length - 1, origin.index));
    lift.holder = to;
    lift.copy = false;
    lift.key = to.keyOf(toItems[home], home);
    lift.item = toItems[home];
    lift.index = home;
    const rest = [...fromItems];
    rest.splice(i, 1);
    from.write(rest);
    from.emit('remove', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: i,
      newIndex: -1
    });
    from.setLifted(null);
    to.setLifted(home);
    say(to, 'movedToList', data, home, el, toItems.length, from);
    to.focusRow(toItems[home], home);
    return;
  }
  // The first hop out of a clone source (`pull: 'clone'`) leaves the source
  // untouched and carries a copy (the same item value the mouse path
  // inserts); from then on the copy moves like any row.
  const cloneOut = canHop(from.group(), to.group()).copy && from === origin.list && !lift.copy;
  const at = dir === 1 ? 0 : toItems.length;
  // Update the lift BEFORE writing, so a target whose watchers run
  // synchronously on a write already sees the new holder.
  lift.holder = to;
  lift.key = to.keyOf(data, at);
  lift.index = at;
  lift.hopped = true;
  if (cloneOut) {
    lift.copy = true;
  } else {
    const rest = [...fromItems];
    rest.splice(i, 1);
    from.write(rest);
  }
  const next = [...toItems];
  next.splice(at, 0, data);
  to.write(next);
  // The destination has not rendered its new row yet: `el` is the row the
  // move started from. `add` (destination) before `remove` (source), as by
  // mouse.
  to.emit('add', {
    interaction: 'keyboard',
    item: data,
    el,
    from: from.el,
    to: to.el,
    oldIndex: -1,
    newIndex: at
  });
  if (!cloneOut) from.emit('remove', {
    interaction: 'keyboard',
    item: data,
    el,
    from: from.el,
    to: to.el,
    oldIndex: i,
    newIndex: -1
  });
  from.setLifted(null);
  to.setLifted(at);
  say(to, 'movedToList', data, at, el, toItems.length + 1, from);
  to.focusRow(data, at);
};
// End the active keyboard lift. 'drop' leaves the row where it is ('off' too,
// announced as `Lift ended`: the holder's keyboard was turned off); 'cancel'
// returns it to the list and position it was lifted from (after hops, a
// reverse hand-off with its own `remove` / `add`; a clone copy is removed).
// Emits `end` once, from the list the row ends up in.
const endLift = (kind: any) => {
  const lift = registry.lift;
  if (!lift) return;
  const h = lift.holder;
  const origin = lift.origin;
  const at = registry.indexOfLift();
  if (at < 0) {
    loseLift();
    return;
  }
  const items = h.items();
  const item = items[at];
  // The lifted row's element, read before any write below. Right after a hop
  // the holder may not have rendered it yet: its label is read from the
  // lifted row element then.
  const el = h.rowEl(at);
  const row = el ?? lift.liftedRowEl;
  if (kind === 'drop' || kind === 'off') {
    // A row that hopped always names its list, even back in its origin. The
    // keyboard turned off mid-lift ('off') ends it where it is, too.
    if (kind === 'off') say(h, 'liftEnded', item, at, row);else say(h, lift.hopped ? 'droppedInList' : 'dropped', item, at, row, items.length);
    h.setLifted(null);
    registry.lift = null;
    keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
    return;
  }
  if (h !== origin.list && !registry.has(origin.list) && lift.copy) {
    // A clone copy is removed on cancel even when its source list has
    // unmounted (the source never gave its item up). Focus moves to the
    // neighbouring row, if any. The lift ends BEFORE the write: the copy is
    // leaving on purpose, and a target whose items watcher runs synchronously
    // on the write (Solid) must not take it for a lost lift (a second `end`).
    registry.lift = null;
    const rest = [...items];
    rest.splice(at, 1);
    h.write(rest);
    h.emit('remove', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: h.el,
      oldIndex: at,
      newIndex: -1
    });
    h.setLifted(null);
    say(h, 'cancelledRemoved', item, at, row);
    if (rest.length > 0) {
      const k = Math.min(at, rest.length - 1);
      h.focusRow(rest[k], k);
    }
    // The copy is gone, so there is no row: `el: null`.
    const fromEl = origin.list.el;
    registry.deferEnd((host: any) => host.emit('end', {
      interaction: 'keyboard',
      item,
      el: null,
      from: fromEl,
      to: h.el,
      oldIndex: origin.index,
      newIndex: -1
    }), h, origin.list);
    return;
  }
  if (h !== origin.list && (!registry.has(origin.list) || !isRenderable(origin.list.el) || !origin.list.keyboardEnabled())) {
    // The origin list has unmounted, is hidden, or has its keyboard off:
    // there is nowhere to return to (focus would be stranded), so the row
    // stays where it is (the lift ends as a drop at its position).
    say(h, 'cancelledStays', item, at, row, items.length);
    h.setLifted(null);
    registry.lift = null;
    keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
    return;
  }
  if (h === origin.list) {
    const to = Math.max(0, Math.min(items.length - 1, origin.index));
    if (to !== at) {
      const next = [...items];
      next.splice(at, 1);
      next.splice(to, 0, item);
      lift.key = h.keyOf(item, to);
      h.write(next);
      h.focusRow(item, to);
      h.emit('reorder', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: h.el,
        oldIndex: at,
        newIndex: to
      });
    }
    say(h, lift.hopped ? 'cancelledReturnedToList' : 'cancelledReturned', item, to, row, items.length);
    h.setLifted(null);
    registry.lift = null;
    keyboardStartEnd('end', lift, origin.list, h, origin.index, to, el);
    return;
  }
  // Reverse hand-off from the current holder back to the origin list.
  const home = origin.list;
  const homeItems = home.items();
  let back;
  if (lift.copy) {
    // The clone source never gave its item up: drop the copy, focus the
    // original.
    back = homeItems.indexOf(item);
    if (back < 0) back = Math.max(0, Math.min(homeItems.length - 1, origin.index));
  } else {
    back = Math.min(origin.index, homeItems.length);
  }
  lift.holder = home;
  lift.key = home.keyOf(item, back);
  const rest = [...items];
  rest.splice(at, 1);
  h.write(rest);
  if (!lift.copy) {
    const next = [...homeItems];
    next.splice(back, 0, item);
    home.write(next);
    // `add` (destination) before `remove` (source), as by mouse.
    home.emit('add', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: home.el,
      oldIndex: -1,
      newIndex: back
    });
  }
  h.emit('remove', {
    interaction: 'keyboard',
    item,
    el,
    from: h.el,
    to: home.el,
    oldIndex: at,
    newIndex: -1
  });
  h.setLifted(null);
  // `home` holds the lift during its write, so a target whose items watcher
  // runs synchronously on the write (Solid) highlighted the row there: clear it.
  home.setLifted(null);
  say(home, 'cancelledReturnedToList', item, back, row, homeItems.length + (lift.copy ? 0 : 1));
  home.focusRow(lift.copy ? homeItems[back] : item, back);
  registry.lift = null;
  keyboardStartEnd('end', lift, home, home, origin.index, back, lift.copy ? home.rowEl(back) : el);
};
// This list's keyboard was turned off (`disabled`, `disableKeyboard`, or
// `option('disabled', true)`): a lift it holds ends where the row is, with
// its `end`.
const endLiftIfHeld = () => {
  const lift = registry.lift;
  if (lift != null && lift.holder === entry) endLift('off');
};
// In row mode the rows leave the tab order when the keyboard turns off, and a
// focused element that stops being focusable drops focus to <body>. If one of
// this list's rows still has focus (a target whose watcher runs before its DOM
// update), move it to the list itself (out of the tab order), like an emptied
// list. Once the DOM update has run, the `focusout` listener added in $onMount
// does it instead.
const keepFocusOffBody = () => {
  const listEl = entry ? entry.el : null;
  if (!listEl) return;
  const root: any = listEl.getRootNode();
  const a: any = root != null ? root.activeElement : null;
  if (a == null || a.parentNode !== listEl || !a.classList.contains('rozie-sortable-item')) return;
  if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
  listEl.focus();
};
const keyboardTurnedOff = () => {
  endLiftIfHeld();
  keepFocusOffBody();
};
// Lift the row at `index` of this list.
const startLift = (index: any) => {
  if (!entry) return;
  // A previous drag's or lift's `end` that is still pending fires first, so
  // every `end` comes before the next `start`.
  registry.flushEnds();
  const item = items[index];
  registry.lift = {
    holder: entry,
    key: entry.keyOf(item, index),
    item,
    copy: false,
    hopped: false,
    origin: {
      list: entry,
      index
    },
    liftedRowEl: entry.rowEl(index),
    index
  };
  liftedIndex = index;
  say(entry, 'lifted', item, index, registry.lift.liftedRowEl, items.length);
  keyboardStartEnd('start', registry.lift, entry, entry, index, index);
};
const onRowKeyDown = ($event: any, index: any) => {
  // Origin guard — must run FIRST, before the keyboardEnabled() check.
  //  - handle mode (keyboardTrigger='handle'): reorder keys apply ONLY when the
  //    keydown came from inside this row's `handle` element. A missing `handle`
  //    selector means keyboard is OFF (warned in warnIfHandleMissing).
  //  - row mode (quick 260716-ggq): reorder keys apply ONLY when the row
  //    element ITSELF is focused. A slotted interactive child (an <input>,
  //    <button>, etc. rendered into the row's default slot) bubbles its own
  //    keydown up to this handler — without this guard, Space/Enter typed into
  //    that child would be hijacked for lift/drop instead of reaching the
  //    child.
  if (handleMode()) {
    if (handleSelector() == null || !isHandleKeyOrigin($event)) return;
  } else if ($event.target !== $event.currentTarget) {
    return;
  }
  // Defense-in-depth: when keyboard reordering is off the rows carry no
  // tabindex and can't receive focus, but a consumer-focused row (or a
  // programmatic .focus()) must still no-op here rather than reorder.
  if (!keyboardEnabled()) return;
  // While a lift exists, reorder keys in the list holding it act on it. A key
  // from ANOTHER list of the holder's group is routed to the holder only when
  // it comes from the lifted row element itself (its old row, still there
  // before the frameworks re-render after a hop; compared by element, so a
  // row of another list that shares the lifted row's key is not it) or while a refocus after a move is
  // outstanding (a fast burst). Any other row — and every row of an unrelated
  // list (another group, or none) — keeps single-list behaviour: Space/Enter
  // there drops the foreign lift and lifts its own row, other keys do nothing.
  const lift = registry.lift;
  const key = $event.key;
  if (lift != null) {
    const mine = groupNameOf(effectiveGroup());
    const sameGroup = mine != null && mine === groupNameOf(lift.holder.group());
    const fromLiftedRow = lift.liftedRowEl != null && $event.currentTarget === lift.liftedRowEl;
    if (lift.holder === entry || sameGroup && (fromLiftedRow || lift.focusPending === true)) {
      if (lift.holder.onKey(key, !!$event.shiftKey)) $event.preventDefault();
      return;
    }
  }
  // Space (' ' on browsers; KeyboardEvent.key === ' ') OR Enter — lift. A row
  // the mouse can't drag (it matches `filter`, or not `draggable`) can't be
  // lifted either: the key is left alone (not prevented).
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    const rules = {
      filter: liveOption('filter', filter),
      draggable: liveOption('draggable', undefined),
      sortable: instance
    };
    if (!rowLiftable($event.currentTarget as any, rules)) return;
    $event.preventDefault();
    if (lift != null) endLift('drop');
    startLift(index);
  }
};
// The group NAME of a SortableJS group option (string or object form).
const groupNameOf = (g: any) => g == null ? null : typeof g === 'string' ? g : g.name ?? null;
// A reorder key for the lift THIS list holds (routed here from any list via
// the registry entry's onKey). Returns true when the key was handled. Every
// key except Space/Enter acts only while lifted, so it never steals keys from
// fields inside a row.
const holderKey = (key: any, shift: any) => {
  const lift = registry.lift;
  if (lift == null || lift.holder !== entry) return false;
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    endLift('drop');
    return true;
  }
  if (key === 'Escape') {
    endLift('cancel');
    return true;
  }
  const horizontal = orientation === 'horizontal';
  const prevKey = horizontal ? 'ArrowLeft' : 'ArrowUp';
  const nextKey = horizontal ? 'ArrowRight' : 'ArrowDown';
  if (shift && (key === nextKey || key === prevKey)) {
    // Hopping is on wherever a group is set; an ungrouped list ignores it.
    if (effectiveGroup() == null) return false;
    hop(key === nextKey ? 1 : -1);
    return true;
  }
  const from = registry.indexOfLift();
  if (from < 0) {
    loseLift();
    return false;
  }
  // pageStep below 1 (or not a number) still moves by at least one position.
  const step = Math.max(1, Math.floor(Number(pageStep) || 1));
  let to: any = null;
  if (key === nextKey) to = from + 1;else if (key === prevKey) to = from - 1;else if (key === 'Home') to = 0;else if (key === 'End') to = entry.items().length - 1;else if (key === 'PageDown') to = from + step;else if (key === 'PageUp') to = from - step;
  if (to === null) return false;
  // `sort: false`: no moves within the list (as by mouse). The key is still
  // taken, so it does not scroll the page while a row is lifted, and says why
  // nothing moved.
  if (liveOption('sort', true) === false) {
    say(entry, 'notSortable', entry.items()[from], from, entry.rowEl(from) ?? lift.liftedRowEl);
    return true;
  }
  moveLiftTo(to, key === prevKey || key === 'Home' || key === 'PageUp' ? -1 : 1);
  return true;
};
// A key pressed while focus has fallen to <body> during a lift. A hop removes
// the focused row from one list and the destination may render (and take
// focus) only after the handler returns (Angular), so the next key of a fast
// burst can reach <body>. The list holding the lift handles it as if it had
// landed on the lifted row, then puts focus back on that row.
//
// Only while a refocus of ours is outstanding (`focusPending`): focus that left
// the lifted row for any other reason (the user clicked elsewhere or tabbed
// away) keeps today's behaviour, and those keys are not ours. Modified keys
// and keys someone already handled are never taken.
const onStrayKey = (ev: any) => {
  const lift = registry.lift;
  if (lift == null || lift.holder !== entry || !lift.focusPending) return;
  if (ev.defaultPrevented || ev.ctrlKey || ev.metaKey || ev.altKey) return;
  const t = ev.target;
  if (t !== document.body && t !== document.documentElement) return;
  const item = lift.item;
  const at = registry.indexOfLift();
  if (!holderKey(ev.key, !!ev.shiftKey)) return;
  ev.preventDefault();
  const now = registry.lift;
  if (now != null) now.holder.focusRow(now.item, registry.indexOfLift());else if (at >= 0) entry.focusRow(item, at);
};

// SortableJS wiring lives in `useSortableJS()` (./internal/useSortableJS).
// The helper owns the SortableJS-vs-reconciler dance — DOM-restore hardening
// against fragile-event paths, identity-based item lookup over fragile
// `e.oldIndex`, and the single-onEnd disambiguation that collapses
// onUpdate / onAdd / onRemove into one handler.
//
// What stays here is purely declarative: which array to read, what to write
// back, what to emit, and how to bridge `afterCommit` to the Lit-only
// `$reconcileAfterDomMutation()` sigil.
// `options.group` wins over `group` / `cloneable` (see effectiveGroup), for
// the mouse as for the keyboard.
// A group change can change which lists can take each other's rows: every
// list rechecks its Shift instructions.
const applyGroup = () => {
  instance?.option('group', effectiveGroup());
  registry.notifyPeers();
};
// Imperative handle (Phase 21 $expose). The SortableJS imperative surface a
// consumer can't drive through props alone — exposed uniformly to all 6 targets.
// Each guards the pre-mount/destroyed `instance = null`. Collision-clear: none of
// the 4 verb names collide with the 16 props or the 5 events — `option` is a
// distinct identifier from the `options` prop, so ROZ121 is clear.
export function getInstance() {
  return instance;
}
// toArray()/sort() use the rows' data-id keys — every row carries
// :data-id="keyFor(item, index)", so toArray() returns the current key order
// (set itemKey for stable object-list keys).
export function toArray() {
  return instance ? instance.toArray() : [];
}
// sort(order) reorders the bound items by those keys and writes them back
// (the framework re-renders the rows; SortableJS never moves them behind the
// model). Listed keys come first, in order; the rest follow in their order. No
// event fires: it is the consumer's own call. With `useAnimation` (and a
// non-zero `animation`) the rows slide from where they were.
export function sort(order: any, useAnimation = true) {
  const list = items;
  const next = orderByKeys(list, order ?? [], keyFor);
  if (next.every((item: any, i: any) => item === list[i])) return;
  const animate = useAnimation && instance != null;
  if (animate) instance.captureAnimationState();
  items = next;
  if (animate) {
    const sortable = instance;
    afterFlush(() => sortable.animateAll());
  }
}
// option(name) reads a live SortableJS option; option(name, value) sets one — the
// runtime escape hatch for any SortableJS option beyond the curated props.
// Setting `disabled`, `filter`, `draggable` or `sort` also applies to the
// keyboard; `option('disabled', true)` mid-lift ends the lift this list holds.
// A runtime `animation` is kept over later `animation` prop changes.
export function option(name: any, value: any) {
  if (!instance) return undefined;
  if (value === undefined) return instance.option(name);
  instance.option(name, value);
  if (TRACKED_OPTIONS.includes(name)) setOverride(name, value);
  if (name === 'disabled' && value) keyboardTurnedOff();
  // After the re-render, so every list reads the new group (React reads
  // state as of its last render).
  if (name === 'group') afterFlush(() => registry.notifyPeers());
  return value;
}

let __rozieWatchInitial_0 = true;
$effect(() => { const __watchVal = (() => disabled)(); untrack(() => { if (__rozieWatchInitial_0) { __rozieWatchInitial_0 = false; return; } ((v: any) => {
  instance?.option('disabled', v);
  setOverride('disabled', v);
})(__watchVal); }); });
let __rozieWatchInitial_1 = true;
$effect(() => { const __watchVal = (() => animation)(); untrack(() => { if (__rozieWatchInitial_1) { __rozieWatchInitial_1 = false; return; } ((v: any) => instance?.option('animation', liveOption('animation', v)))(__watchVal); }); });
let __rozieWatchInitial_2 = true;
$effect(() => { (() => options)(); untrack(() => { if (__rozieWatchInitial_2) { __rozieWatchInitial_2 = false; return; } (() => {
  if (!instance) return;
  const next = options;
  const base = {
    animation: animation,
    disabled: disabled,
    group: resolveGroup() ?? null,
    handle: handle,
    ghostClass: ghostClass,
    chosenClass: chosenClass,
    dragClass: dragClass,
    filter: filter,
    swapThreshold: swapThreshold,
    easing: easing,
    sort: true,
    draggable: ROW_DRAGGABLE
  };
  // A fresh inline function with the same content (React re-renders) is
  // applied so SortableJS runs the newest closure, but it is no change: a
  // runtime `option(name, v)` still in force keeps winning over it.
  const applied = reapplyOptions(instance, appliedOptions, next, base, {
    keep: (key: any, prev: any) => {
      const ov: any = optionOverrides;
      return ov != null && Object.prototype.hasOwnProperty.call(ov, key) && ov[key] !== prev;
    },
    refreshed: (key: any) => {
      if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key));
    }
  });
  appliedOptions = next;
  for (const key of applied as any) {
    // The keyboard reads the value SortableJS now runs with. A remembered
    // runtime `animation` / `handle` / `group` is superseded by the newer
    // `options` value.
    if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key));else if (TRACKED_OPTIONS.includes(key)) clearOverride(key);
  }
  if (applied.includes('group')) registry.notifyPeers();
})(); }); });
let __rozieWatchInitial_3 = true;
$effect(() => { (() => [disabled, disableKeyboard, options, optionOverrides])(); untrack(() => { if (__rozieWatchInitial_3) { __rozieWatchInitial_3 = false; return; } (() => {
  if (!keyboardEnabled()) keyboardTurnedOff();
})(); }); });
let __rozieWatchInitial_4 = true;
$effect(() => { (() => group)(); untrack(() => { if (__rozieWatchInitial_4) { __rozieWatchInitial_4 = false; return; } (() => applyGroup())(); }); });
let __rozieWatchInitial_5 = true;
$effect(() => { (() => cloneable)(); untrack(() => { if (__rozieWatchInitial_5) { __rozieWatchInitial_5 = false; return; } (() => applyGroup())(); }); });
let __rozieWatchInitial_6 = true;
$effect(() => { const __watchVal = (() => swapThreshold)(); untrack(() => { if (__rozieWatchInitial_6) { __rozieWatchInitial_6 = false; return; } ((v: any) => instance?.option('swapThreshold', v))(__watchVal); }); });
let __rozieWatchInitial_7 = true;
$effect(() => { const __watchVal = (() => handle)(); untrack(() => { if (__rozieWatchInitial_7) { __rozieWatchInitial_7 = false; return; } ((v: any) => {
  instance?.option('handle', liveOption('handle', v));
  warnIfHandleMissing();
})(__watchVal); }); });
let __rozieWatchInitial_8 = true;
$effect(() => { (() => keyboardTrigger)(); untrack(() => { if (__rozieWatchInitial_8) { __rozieWatchInitial_8 = false; return; } (() => warnIfHandleMissing())(); }); });
let __rozieWatchInitial_9 = true;
$effect(() => { const __watchVal = (() => ghostClass)(); untrack(() => { if (__rozieWatchInitial_9) { __rozieWatchInitial_9 = false; return; } ((v: any) => instance?.option('ghostClass', v))(__watchVal); }); });
let __rozieWatchInitial_10 = true;
$effect(() => { const __watchVal = (() => chosenClass)(); untrack(() => { if (__rozieWatchInitial_10) { __rozieWatchInitial_10 = false; return; } ((v: any) => instance?.option('chosenClass', v))(__watchVal); }); });
let __rozieWatchInitial_11 = true;
$effect(() => { const __watchVal = (() => dragClass)(); untrack(() => { if (__rozieWatchInitial_11) { __rozieWatchInitial_11 = false; return; } ((v: any) => instance?.option('dragClass', v))(__watchVal); }); });
let __rozieWatchInitial_12 = true;
$effect(() => { const __watchVal = (() => filter)(); untrack(() => { if (__rozieWatchInitial_12) { __rozieWatchInitial_12 = false; return; } ((v: any) => {
  instance?.option('filter', v);
  setOverride('filter', v);
})(__watchVal); }); });
let __rozieWatchInitial_13 = true;
$effect(() => { const __watchVal = (() => easing)(); untrack(() => { if (__rozieWatchInitial_13) { __rozieWatchInitial_13 = false; return; } ((v: any) => instance?.option('easing', v))(__watchVal); }); });
let __rozieWatchInitial_14 = true;
$effect(() => { (() => items)(); untrack(() => { if (__rozieWatchInitial_14) { __rozieWatchInitial_14 = false; return; } (() => {
  const lift = registry.lift;
  if (lift == null || lift.holder !== entry) return;
  const i = registry.indexOfLift();
  if (i < 0) {
    loseLift();
    return;
  }
  if (liftedIndex !== i) liftedIndex = i;
  // Once the holder has rendered the lifted row, that is the lifted row
  // element. After a hop this drops the source's old row, which the source
  // may reuse for another item (index keys).
  const row = entry.rowEl(i);
  if (row != null) lift.liftedRowEl = row;
  focusNearRow(i, lift.key);
})(); }); });

onMount(() => {
  // Kept across a Lit element's disconnect and reconnect (mount runs again).
  if (instructionsId == null) instructionsId = nextInstructionsId();
  warnIfHandleMissing();
  // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
  // when the options object below references it.
  const sortable = useSortableJS(listEl!, {
    items: () => items,
    onCommit: (next: any) => {
      items = next;
    },
    options: {
      animation: animation,
      disabled: disabled,
      group: resolveGroup(),
      handle: handle,
      ghostClass: ghostClass,
      chosenClass: chosenClass,
      dragClass: dragClass,
      filter: filter,
      forceFallback: forceFallback,
      swapThreshold: swapThreshold,
      easing: easing,
      ...options
    },
    // Lit lit-html `repeat` directive caches its part array by sentinel-
    // comment node identity; SortableJS's physical DOM mutation desyncs
    // that cache. The sigil lowers to `__rozieReconcileAfterDomMutation(this)`
    // on Lit (real call) and `void 0` on the other 5 targets (no-op).
    afterCommit: () => void 0,
    // Every pointer event carries the same payload as the keyboard ones, with
    // item-row indices and the raw SortableJS event as `originalEvent`.
    onChange: (c: any) => {
      const payload = {
        interaction: 'pointer' as const,
        item: c.item,
        el: c.el,
        from: c.from,
        to: c.to,
        oldIndex: c.oldIndex,
        newIndex: c.newIndex,
        originalEvent: c.event
      };
      if (c.kind === 'reorder') onreorder?.(payload);else if (c.kind === 'add') onadd?.(payload);else if (c.kind === 'remove') onremove?.(payload);
    },
    onStart: (d: any) => {
      // A pointer drag ends any active keyboard lift first.
      if (registry.lift != null) endLift('drop');
      // That lift's `end` (pending until a task) comes before this `start`.
      registry.flushEnds();
      onstart?.({
        interaction: 'pointer',
        item: d.item,
        el: d.el,
        from: d.from,
        to: d.to,
        oldIndex: d.oldIndex,
        newIndex: d.newIndex,
        originalEvent: d.event
      });
    },
    // `end` comes from the list the row ended up in: the destination when it
    // is a SortableList, else (dropped outside, or into a SortableJS list
    // that isn't one of ours) this source list. It goes through the
    // registry's `deferEnd`, like a keyboard `end`: it fires in a task after
    // every list involved has written its items and the re-render those
    // writes scheduled, and before the next drag's or lift's `start`. An
    // unmounted list never emits: if the destination has unmounted by then
    // (in its own `add` handler, say), this list (the origin, which emitted
    // `start`) emits it, `to` still the destination; if both are gone,
    // nothing is emitted.
    scheduleEnd: (d: any) => {
      const dest = registry.entryFor(d.to);
      const destGone = dest == null && d.to !== d.from && registry.wasList(d.to);
      registry.deferEnd((host: any) => {
        const row = d.item === undefined || host.el !== d.to ? null : rowByKey(d.to, host.keyOf(d.item, d.newIndex));
        host.emit('end', {
          interaction: 'pointer',
          item: d.item,
          el: row ?? liveEl(d.el),
          from: d.from,
          to: d.to,
          oldIndex: d.oldIndex,
          newIndex: d.newIndex,
          originalEvent: d.event
        });
      }, destGone ? null : dest ?? entry, entry);
    }
  });
  instance = sortable.instance;
  appliedOptions = options;
  // Runtime `option(name, v)` values this list remembers (Lit keeps them when
  // the element is moved in the DOM and mounts again) apply to the new
  // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
  // first mount.
  const remembered: any = optionOverrides;
  if (remembered != null) {
    for (const name of Object.keys(remembered) as any) instance.option(name, remembered[name]);
  }
  const listEl$local = listEl;
  const stopNative = (ev: any) => {
    if (ev.target === listEl$local) ev.stopPropagation();
  };
  for (const name of SORTABLE_DOM_EVENTS as any) listEl$local?.addEventListener(name, stopNative);
  // A focused row that stops being focusable (its tabindex goes when the
  // keyboard turns off) is blurred at once, during the framework's DOM
  // update, with focus going nowhere (`relatedTarget` null): it would land on
  // <body>. Move it to the list instead.
  const rowBlurred = (ev: any) => {
    if (listEl$local == null) return;
    const row: any = ev.target;
    if (ev.relatedTarget != null || row == null || row.parentNode !== listEl$local) return;
    if (!row.classList.contains('rozie-sortable-item') || row.hasAttribute('tabindex') || !row.isConnected) return;
    if (!listEl$local.hasAttribute('tabindex')) listEl$local.setAttribute('tabindex', '-1');
    listEl$local.focus();
  };
  listEl$local?.addEventListener('focusout', rowBlurred);
  unhookNativeEvents = () => {
    for (const name of SORTABLE_DOM_EVENTS as any) listEl$local?.removeEventListener(name, stopNative);
    listEl$local?.removeEventListener('focusout', rowBlurred);
  };

  // Register with the keyboard registry. Other instances call these methods
  // when a keyboard lift hands a row between lists.
  entry = {
    el: listEl$local,
    group: () => effectiveGroup(),
    label: () => listLabel,
    // A handle-mode list without a handle selector has its keyboard off.
    keyboardEnabled: () => keyboardEnabled() && !(handleMode() && handleSelector() == null),
    items: () => items,
    keyOf: (item: any, i: any) => String(keyFor(item, i)),
    labelOf: (item: any, i: any, row: HTMLElement | null = null) => String(labelOf(item, i, row)),
    message: (kind: any, ctx: any) => announcementText(announcements, kind, ctx),
    onKey: (key: any, shift: any) => holderKey(key, shift),
    write: (next: any) => {
      items = next;
    },
    setLifted: (i: any) => {
      liftedIndex = i;
    },
    // The same text twice in a row would not change the region, and a screen
    // reader would not read it again ("Apple is already first", twice): a
    // repeat alternates a trailing no-break space, which is not spoken.
    announce: (text: any) => {
      const next = text !== '' && text === lastSpoken ? text + '\u00A0' : text;
      lastSpoken = next;
      ariaLiveText = next;
    },
    focusRow: (item: any, i: any) => refocusRow(item, i),
    focusNear: (i: any) => focusNearRow(i),
    rowEl: (i: any) => {
      const list = items;
      if (i < 0 || i >= list.length) return null;
      return rowByKey(listEl$local, String(keyFor(list[i], i)));
    },
    // Always set (an equal value is a no-op on every target): a compare
    // against $data would read React's render-time ref, stale when two peer
    // changes land in one commit (one list unmounts, another mounts).
    peersChanged: (v: any) => {
      hasHopPeer = v;
    },
    emit: (name: any, payload: any) => {
      if (name === 'add') onadd?.(payload);else if (name === 'remove') onremove?.(payload);else if (name === 'reorder') onreorder?.(payload);else if (name === 'start') onstart?.(payload);else if (name === 'end') onend?.(payload);
    }
  };
  unregisterEntry = registry.register(entry);
  const strayKey = (ev: any) => onStrayKey(ev);
  // A pointer press means the user moved on: keys lost to <body> after it
  // are not routed to the lift.
  const pointerPress = () => {
    if (registry.lift != null) registry.lift.focusPending = false;
  };
  document.addEventListener('keydown', strayKey);
  document.addEventListener('pointerdown', pointerPress, true);
  unhookStrayKeys = () => {
    document.removeEventListener('keydown', strayKey);
    document.removeEventListener('pointerdown', pointerPress, true);
  };
  // $onMount's cleanup-return: closing over a setup-local (`sortable`) does
  // not survive the Solid emitter's setup/cleanup split — it scopes cleanup
  // outside the setup IIFE. Closing over `instance` / `unregisterEntry`
  // (module-scope `let`s) works on every target.
  return () => {
    instance?.destroy();
    // Unmounting while holding a keyboard lift ends it (its `end` comes from
    // the origin list, if that one is still mounted).
    if (registry.lift != null && registry.lift.holder === entry) loseLift(true);
    unregisterEntry?.();
    unregisterEntry = null;
    unhookNativeEvents?.();
    unhookNativeEvents = null;
    unhookStrayKeys?.();
    unhookStrayKeys = null;
  };
});
</script>

<div {...__rozieAttrs} class={["rozie-sortable-wrap", (__rozieAttrs)?.class]} use:applyListeners={__rozieAttrs} data-rozie-s-0af24eae><div class={rozieClass(['rozie-sortable-list', listClass])} bind:this={listEl} part="list" role="list" aria-label={listLabel} data-rozie-s-0af24eae>{#if header}{#if header}{@render header()}{/if}{/if}{#each items as item, index (keyFor(item, index))}<div class={rozieClass(['rozie-sortable-item', itemClassFor(item, index), liftedIndex === index ? 'rozie-sortable-item-lifted' : ''])} style={rozieStyle(itemStyleFor(item, index))} data-id={rozieAttr(keyFor(item, index))} role="listitem" tabindex={rozieAttr(rowTabbable() ? 0 : null)} aria-describedby={rozieAttr(rowTabbable() ? instructionsId : null)} onkeydown={($event) => { onRowKeyDown($event, index); }} data-rozie-s-0af24eae>{@render children?.({ item, index, instructionsId })}</div>{/each}{#if footer}{#if footer}{@render footer()}{/if}{/if}</div><div class="rozie-sortable-aria-live" data-rozie-sortable-aria-live="" aria-live="polite" aria-atomic="true" data-rozie-s-0af24eae>{ariaLiveText}</div><span hidden id={rozieAttr(instructionsId)} data-rozie-s-0af24eae>{rozieDisplay(instructionsText())}</span></div>

<style>
:global {
  .rozie-sortable-wrap[data-rozie-s-0af24eae] { display: block; }
  .rozie-sortable-list[data-rozie-s-0af24eae] { display: block; }
  .rozie-sortable-item[data-rozie-s-0af24eae] { display: block; outline: none; }
  .rozie-sortable-item[data-rozie-s-0af24eae]:focus-visible { outline: 2px solid var(--rozie-sortable-list-ring, #1a73e8); outline-offset: -2px; }
  .rozie-sortable-item-lifted[data-rozie-s-0af24eae] {
    background: rgba(26, 115, 232, 0.1);
    box-shadow: 0 0 0 3px var(--rozie-sortable-list-ring, #1a73e8) inset;
  }
  .rozie-sortable-aria-live[data-rozie-s-0af24eae] {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
  }
}
</style>
ts
import { Component, ContentChild, DestroyRef, ElementRef, Renderer2, TemplateRef, ViewEncapsulation, afterRenderEffect, computed, contentChildren, effect, forwardRef, inject, input, output, signal, untracked, viewChild } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { RozieSlot, createRozieAttrApplier, createRozieHostAttrsReader, rozieAttr as __rozieAttr, rozieClass as __rozieClass, rozieDisplay as __rozieDisplay, rozieModel } from '@rozie/runtime-angular';

import { ROW_DRAGGABLE, orderByKeys, reapplyOptions, useSortableJS } from './internal/useSortableJS';
import { afterFlush, canHop, getKeyboardRegistry, isRenderable, nextInstructionsId, rowLiftable } from './internal/keyboardRegistry';
import { announcementText, defaultInstructions, fallbackLabel } from './internal/announcements';

/** The kind of message the list speaks during keyboard reordering (a key of the `announcements` prop). */
export type AnnouncementKind = 'lifted' | 'moved' | 'movedToList' | 'dropped' | 'droppedInList' | 'atStart' | 'atEnd' | 'notSortable' | 'noListBefore' | 'noListAfter' | 'cancelledReturnedToList' | 'cancelledReturned' | 'cancelledStays' | 'cancelledRemoved' | 'liftEnded';
/** What an `announcements` function receives. */
export interface AnnouncementContext {
  /** The row's screen-reader label (`labelFor`, else `item.label`, else the row's text). */
  label: string;
  /** The item value. */
  item: unknown;
  /** The name of the list the message is about (`listLabel`, or `list 2 of 3`). */
  list: string;
  /** 1-based position of the row in `list` (kinds that have a position). */
  position?: number;
  /** How many rows `list` holds (kinds that have a position). */
  total?: number;
  /** The list the row came from (`movedToList` only). */
  fromList?: string;
}
/** The `announcements` prop: one optional function per message kind; `null` or `''` says nothing. */
export type Announcements = Partial<Record<AnnouncementKind, (ctx: AnnouncementContext) => string | null | undefined>>;
/** The payload every `start` / `end` / `reorder` / `add` / `remove` event carries, for pointer and keyboard alike. */
export interface SortablePayload {
  /** Which input made the change. */
  interaction: 'pointer' | 'keyboard';
  /** The item's data value (never an element). */
  item: unknown;
  /** The row element; null when there is none (a lost lift, a removed clone copy). */
  el: HTMLElement | null;
  /** The list element the row came from. */
  from: HTMLElement;
  /** The list element the row went to. */
  to: HTMLElement;
  /** Item-row index in `from`; -1 for `add`. */
  oldIndex: number;
  /** Item-row index in `to`; -1 for `remove` and a lost lift. */
  newIndex: number;
  /** Pointer only: the raw SortableJS event. */
  originalEvent?: unknown;
}
/** Which element drives keyboard reordering (the `keyboardTrigger` prop). */
export type SortableKeyboardTrigger = 'row' | 'handle';
/** Which arrow keys move a lifted row within the list (the `orientation` prop). */
export type SortableOrientation = 'vertical' | 'horizontal';

interface HeaderCtx {}

interface DefaultCtx {
  $implicit: { item: any; index: any; instructionsId: any };
  item: any;
  index: any;
  instructionsId: any;
}

interface FooterCtx {}

@Component({
  selector: 'rozie-sortable-list',
  standalone: true,
  imports: [NgTemplateOutlet],
  template: `

    <div class="rozie-sortable-wrap" #rozieSpread_0 #rozieListenersTarget_1>
      <div [class]="rozieClass(['rozie-sortable-list', listClass()])" #listEl part="list" role="list" [attr.aria-label]="rozieAttr(listLabel())">
        
        @if ((headerTpl ?? __rozieFillMap()['header'] ?? templates()?.['header'])) {
    @if ((headerTpl ?? __rozieFillMap()['header'] ?? templates()?.['header'])) {
    <ng-container *ngTemplateOutlet="(headerTpl ?? __rozieFillMap()['header'] ?? templates()?.['header'])" />
    }
    }@for (item of items(); track keyFor(item, index); let index = $index) {
    <div [class]="rozieClass(['rozie-sortable-item', itemClassFor(item, index), liftedIndex() === index ? 'rozie-sortable-item-lifted' : ''])" [style]="itemStyleFor(item, index)" [attr.data-id]="rozieAttr(keyFor(item, index))" role="listitem" [attr.tabindex]="rozieAttr(rowTabbable() ? 0 : null)" [attr.aria-describedby]="rozieAttr(rowTabbable() ? instructionsId() : null)" (keydown)="onRowKeyDown($event, index)">
          <ng-container *ngTemplateOutlet="(defaultTpl ?? __rozieFillMap()['defaultSlot'] ?? templates()?.['defaultSlot']); context: { $implicit: { item: item, index: index, instructionsId: instructionsId() }, item: item, index: index, instructionsId: instructionsId() }" />
        </div>
    }
        @if ((footerTpl ?? __rozieFillMap()['footer'] ?? templates()?.['footer'])) {
    @if ((footerTpl ?? __rozieFillMap()['footer'] ?? templates()?.['footer'])) {
    <ng-container *ngTemplateOutlet="(footerTpl ?? __rozieFillMap()['footer'] ?? templates()?.['footer'])" />
    }
    }</div>
      <div class="rozie-sortable-aria-live" data-rozie-sortable-aria-live="" aria-live="polite" aria-atomic="true">{{ ariaLiveText() }}</div>
      <span hidden="" [attr.id]="rozieAttr(instructionsId())">{{ rozieDisplay(instructionsText()) }}</span>
    </div>

  `,
  styles: [`
    :host(rozie-sortable-list) { display: contents; }
    .rozie-sortable-wrap { display: block; }
    .rozie-sortable-list { display: block; }
    .rozie-sortable-item { display: block; outline: none; }
    .rozie-sortable-item:focus-visible { outline: 2px solid var(--rozie-sortable-list-ring, #1a73e8); outline-offset: -2px; }
    .rozie-sortable-item-lifted {
      background: rgba(26, 115, 232, 0.1);
      box-shadow: 0 0 0 3px var(--rozie-sortable-list-ring, #1a73e8) inset;
    }
    .rozie-sortable-aria-live {
      position: absolute;
      width: 1px;
      height: 1px;
      padding: 0;
      margin: -1px;
      overflow: hidden;
      clip: rect(0, 0, 0, 0);
      white-space: nowrap;
      border: 0;
    }
  `],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SortableList),
      multi: true,
    },
  ],
  host: { '(focusout)': '__rozieCvaOnTouched()' },
})
export class SortableList {
  /**
   * The bound items array. The sole `model: true` prop — two-way bind it (`r-model:items` / `v-model:items` / `bind:items` / `[(items)]`) and SortableList writes the re-ordered array back whenever a drag, cross-list move, or keyboard reorder commits, with no manual `onChange → setState` wiring.
   * @example
   * <rozie-sortable-list [(items)]="todos" itemKey="id" />
   */
  readonly __rozieModelIn_items = input<any[] | undefined>(undefined, { alias: 'items' });
  itemsChange = output<any[]>();
  items = rozieModel<any[], import('@angular/core').ModelSignal<any[]>>(this.__rozieModelIn_items, this.itemsChange, (() => [])(), { signal, computed, untracked });
  /**
   * The per-row key the framework reconciler tracks each item by across a reorder — either a property name (e.g. `itemKey="id"` reads `item.id`) or an `(item, index) => key` function. With neither, id-less object items get a stable synthetic key via an internal `WeakMap` (survives reorder by object identity); primitive items fall back to index — pass a function for reorderable duplicate primitives.
   */
  itemKey = input<(string | ((...args: any[]) => any)) | null>(null);
  /**
   * CSS selector identifying the per-row drag handle, so a drag starts only from that element rather than anywhere in the row. Authored class names render literally on every target (React included), so a plain `.grip` works; `$classSelector('grip')` is an optional, typo-checked way to author it. `options.handle` and `option('handle', v)` win over this prop, for the keyboard (`keyboardTrigger: 'handle'`) as for the mouse.
   */
  handle = input<(string) | null>(null);
  /**
   * SortableJS group name enabling cross-list drag — two lists sharing a `group` accept items between each other (the source fires `remove`, the destination fires `add`). Set `cloneable: true` to flip a string group into clone-mode. Lists that share a `group` also exchange rows by keyboard: Shift+arrow while a row is lifted hops it to the previous or next list of the same group (in source order), subject to the same pull/put rules as a mouse drag. `options.group` takes precedence over this prop, for keyboard hops as for drags. Function-valued `pull`/`put` cannot be evaluated without a drag, so those lists are unreachable by keyboard. Set `itemKey` on grouped lists.
   */
  group = input<(string) | null>(null);
  /**
   * Reorder animation duration in milliseconds. `0` disables the animation. Reapplied live via `instance.option('animation', v)` (no remount). `options.animation`, and a runtime `option('animation', v)`, win over this prop.
   */
  animation = input<number>(150);
  /**
   * Temporarily disable dragging without unmounting — reapplied live via `instance.option('disabled', v)` (no remount). Also suppresses keyboard reordering: a disabled list is not sortable by any input, so rows lose their `tabindex` and the keydown handler no-ops. Turning it on while a row is lifted ends the lift where the row is (`Lift ended`, and `end` fires); `options.disabled` and `option('disabled', v)` do the same.
   */
  disabled = input<boolean>(false);
  /**
   * Opt out of keyboard reordering (Space lift / Arrow move / Shift+Arrow hop between lists / Esc cancel / Enter drop) while leaving pointer drag enabled. Rows drop out of the tab order (no `tabindex`) and the keydown handler no-ops. Keyboard access is gated on `!disabled && !disableKeyboard`. Turning it on while a row is lifted ends the lift where the row is.
   */
  disableKeyboard = input<boolean>(false);
  /**
   * Which element drives keyboard reordering. `'row'` (default): rows are tab stops and the keys on the focused row drive reordering. `'handle'`: rows are NOT tab stops, and only keys pressed inside the element matched by `handle` (inside that row) drive the same Space/Enter lift-drop, Arrow move, Shift+Arrow hop and Escape cancel flow; handled keys call preventDefault so a handle `<button>`'s click does not fire. The consumer owns the handle markup (recommended: a `<button>` with its own aria-label such as "Reorder Hero banner") and the component adds no tabindex or role to slot content. `'handle'` without `handle` turns keyboard reordering off and logs a console warning. `disabled`/`disableKeyboard` still apply. Typed as `SortableKeyboardTrigger` (`'row' | 'handle'`); at runtime any value other than `'handle'` behaves as `'row'`.
   */
  keyboardTrigger = input<SortableKeyboardTrigger>('row');
  /**
   * Verbatim SortableJS options pass-through for anything not covered by the named props. The named props win on key conflict but `options` lands AFTER them in the merge so consumers can override defaults; handler keys (`onStart`, `onEnd`, `onUpdate`, `onAdd`, `onRemove`, `onClone`) are stripped — the helper owns those paths. Runtime-updatable: when `options` changes, each key whose value changed is reapplied via `instance.option(key, v)` (no remount), so mouse and keyboard obey the same values; a key you drop goes back to its named prop (or, for `sort` and `draggable`, the component default), and any other dropped key keeps its last value until you set it. `forceFallback` is still read only at construction.
   */
  options = input<Record<string, any>>((() => ({}))());
  /**
   * Optional `(item, idx) => string` returning the screen-reader label for the aria-live announcer during keyboard drag. Defaults to `item.label`; without a `label` field, the row's text (whitespace collapsed, without nested lists or hidden content), else `String(item)` for a primitive, else `item {position}`.
   */
  labelFor = input<((...args: any[]) => any) | null>(null);
  /**
   * Class name applied to the drop-placeholder (ghost) element while dragging. Forwarded live via `instance.option`, so toggling it at runtime takes effect without a remount.
   */
  ghostClass = input<(string) | null>(null);
  /**
   * Class name applied to the currently-chosen item while dragging. Forwarded live via `instance.option` (no remount needed to change it).
   */
  chosenClass = input<(string) | null>(null);
  /**
   * Class name applied to the dragging element. Only takes effect in fallback mode (`forceFallback: true`). Forwarded live via `instance.option`.
   */
  dragClass = input<(string) | null>(null);
  /**
   * CSS selector that prevents drag initiation on matching rows (locked items). SortableJS checks it at `mousedown`/`touchstart` and aborts the drag if it matches. The keyboard honours it too: a row that matches (the row element, or its slot root: the row template's single element when nothing else sits beside it) cannot be lifted with Space/Enter; any other matching control (a `.js-remove` button, an `input`) blocks only presses on itself. `options.filter` (which may also be a SortableJS filter function) takes precedence. A `data-*` attribute selector (e.g. `[data-locked]`) is the most robust choice across all targets.
   */
  filter = input<(string) | null>(null);
  /**
   * CSS easing function for the reorder animation (e.g. `'ease-in'`, `'cubic-bezier(0.4, 0, 0.2, 1)'`). Runtime-updatable.
   */
  easing = input<(string) | null>(null);
  /**
   * Force SortableJS's mouse-event drag path over HTML5 DnD — useful for touch devices, consistent cross-browser behavior, and synthetic test drivers (and `dragClass` only applies in this mode). **Construction-time only**: SortableJS reads it once at construction, so re-key the `<SortableList>` to toggle it at runtime.
   */
  forceFallback = input<boolean>(false);
  /**
   * SortableJS swap threshold (0..1) — a lower value makes rows swap earlier as the dragged item overlaps a neighbor. Reapplied live via `instance.option('swapThreshold', v)` — SortableJS reads it on every dragover, so no remount is needed.
   */
  swapThreshold = input<number>(1);
  /**
   * High-level prop that REPLACES a string `group` with SortableJS's `{ name, pull: 'clone', put: false }` clone-mode object form — the source deposits a COPY onto the destination and keeps its own array unchanged, and takes nothing back: no row can be dropped or keyboard-hopped into it (the palette → canvas pattern). With `group: null` it is a no-op (a clone-mode list with no group name has no peer to clone into). Reapplied live — toggling `cloneable` (or changing `group`) recomputes the clone-mode shape and reapplies it via `instance.option('group', …)`, no remount.
   */
  cloneable = input<boolean>(false);
  /**
   * Extra class(es) merged onto the list container (the SortableJS root) alongside the base `rozie-sortable-list` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding), normalized identically across all six targets — the hook for bridging a CSS framework (`.list-group`) or a flex/grid parent onto the component.
   */
  listClass = input<string | any[] | Record<string, any>>('');
  /**
   * Extra class(es) merged onto every item row alongside the base `rozie-sortable-item` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding) applied uniformly, OR an `(item, index) => class` function for per-row classes evaluated at render time. Normalized identically across all six targets.
   */
  itemClass = input<string | any[] | Record<string, any> | ((...args: any[]) => any)>('');
  /**
   * The list's human name, such as `"Top sidebar"`. Sets `aria-label` on the list container (`role="list"`) and names the list in keyboard announcements when a row moves between lists (`Moved Hero banner to Top sidebar, position 1 of 4`, `Dropped Hero banner in Top sidebar at position 3 of 4`, `No list after Top sidebar`). Pass the same words as the zone's visible heading. With no label, announcements fall back to a neutral `list 2 of 3`, counting the mounted lists of the same group in hop (source) order.
   */
  listLabel = input<(string) | null>(null);
  /**
   * Which arrow keys move a lifted row within the list: `'vertical'` (default) uses ↑/↓, `'horizontal'` uses ←/→. A horizontal list's default spoken instructions say "Use the left and right arrow keys to move" (`role="list"` has no `aria-orientation`). Typed as `SortableOrientation` (`'vertical' | 'horizontal'`).
   */
  orientation = input<SortableOrientation>('vertical');
  /**
   * How many positions Page Up / Page Down move a lifted row. The move stops at the first or last position when fewer rows remain.
   */
  pageStep = input<number>(5);
  /**
   * Replaces the spoken keyboard instructions. The text sits in a hidden element referenced by `aria-describedby` from each tabbable row (row mode) or from the consumer's handle via the `instructionsId` slot prop (handle mode). Default: "Press Space or Enter to pick up, and again to drop. Use the up and down arrow keys to move, Home and End to jump to the start or end, Page Up and Page Down to move several places, and Escape to cancel." (with `orientation: 'horizontal'`, "the left and right arrow keys"; a `sort: false` list says only "Press Space or Enter to pick up, and again to drop. Press Escape to cancel."). When another mounted list could take this list's rows (by the group rules of `group`, `options.group` or `option('group', v)`), the default adds "Hold Shift with an arrow key to move to another list." (updated as lists mount, unmount or change group).
   */
  keyboardInstructions = input<(string) | null>(null);
  /**
   * Rewords or translates what the list says during keyboard reordering. An object of optional functions keyed by message kind (`lifted`, `moved`, `movedToList`, `dropped`, `droppedInList`, `atStart`, `atEnd`, `notSortable`, `noListBefore`, `noListAfter`, `cancelledReturnedToList`, `cancelledReturned`, `cancelledStays`, `cancelledRemoved`, `liftEnded`). Each receives a context (`label`, `item`, `list`, and for kinds with a position `position` (1-based) and `total`; `movedToList` also `fromList`) and returns the text to speak; `null` or `''` says nothing. Kinds without a function keep the default English text (see "Announcements"). Define the object in your script and bind it (Angular templates reject inline arrow functions), e.g. `const announcements = { moved: ({ label, position, total }) => label + ' → ' + position + '/' + total }`. Typed as `Announcements`, exported with `AnnouncementKind` and `AnnouncementContext`.
   * @example
   * <rozie-sortable-list [(items)]="todos" [announcements]="announcements" />
   */
  announcements = input<(Announcements) | null>(null);
  /**
   * Per-row inline style applied to the `.rozie-sortable-item` wrapper. Accepts a CSS `String`, a flat style object (`Record<string, string | number>`), or an `(item, index) => string | object` function for per-row styling. Because it lands on the wrapper — the direct child of the list container — it can drive CSS-grid placement (`grid-column` / `grid-row` / `align-self`) when `listClass` sets `display: grid`. Normalized per target; `null` / empty drops the attribute.
   */
  itemStyle = input<(string | Record<string, any> | ((...args: any[]) => any)) | null>(null);
  liftedIndex = signal<any>(null);
  ariaLiveText = signal('');
  instructionsId = signal<any>(null);
  optionOverrides = signal({});
  hasHopPeer = signal(false);
  listEl = viewChild<ElementRef<HTMLDivElement>>('listEl');
  reorder = output<SortablePayload>();
  add = output<SortablePayload>();
  remove = output<SortablePayload>();
  start = output<SortablePayload>();
  end = output<SortablePayload>();
  @ContentChild('header', { read: TemplateRef }) headerTpl?: TemplateRef<HeaderCtx>;
  @ContentChild('defaultSlot', { read: TemplateRef }) defaultTpl?: TemplateRef<DefaultCtx>;
  @ContentChild('footer', { read: TemplateRef }) footerTpl?: TemplateRef<FooterCtx>;
  templates = input<Record<string, TemplateRef<unknown>> | undefined>(undefined);
  __rozieFills = contentChildren(RozieSlot, { descendants: true });
  __rozieFillMap = computed(() => {
    const map = Object.create(null) as Record<string, TemplateRef<unknown>>;
    for (const f of this.__rozieFills()) {
      const k = f.rozieSlot();
      if (k == null) continue;
      if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
      map[k === '' ? 'defaultSlot' : k] = f.templateRef;
    }
    return map;
  });
  private __rozieDestroyRef = inject(DestroyRef);
  private __rozieWatchInitial_0 = true;
  private __rozieWatchInitial_1 = true;
  private __rozieWatchInitial_2 = true;
  private __rozieWatchInitial_3 = true;
  private __rozieWatchInitial_4 = true;
  private __rozieWatchInitial_5 = true;
  private __rozieWatchInitial_6 = true;
  private __rozieWatchInitial_7 = true;
  private __rozieWatchInitial_8 = true;
  private __rozieWatchInitial_9 = true;
  private __rozieWatchInitial_10 = true;
  private __rozieWatchInitial_11 = true;
  private __rozieWatchInitial_12 = true;
  private __rozieWatchInitial_13 = true;
  private __rozieWatchInitial_14 = true;

  constructor() {
    effect(() => { const __watchVal = (() => (this.disabled() || this.__rozieCvaDisabled()))(); untracked(() => { if (this.__rozieWatchInitial_0) { this.__rozieWatchInitial_0 = false; return; } ((v: any) => {
      this.instance?.option('disabled', v);
      this.setOverride('disabled', v);
    })(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.animation())(); untracked(() => { if (this.__rozieWatchInitial_1) { this.__rozieWatchInitial_1 = false; return; } ((v: any) => this.instance?.option('animation', this.liveOption('animation', v)))(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.options())(); untracked(() => { if (this.__rozieWatchInitial_2) { this.__rozieWatchInitial_2 = false; return; } (() => {
      if (!this.instance) return;
      const next = this.options();
      const base = {
        animation: this.animation(),
        disabled: (this.disabled() || this.__rozieCvaDisabled()),
        group: this.resolveGroup() ?? null,
        handle: this.handle(),
        ghostClass: this.ghostClass(),
        chosenClass: this.chosenClass(),
        dragClass: this.dragClass(),
        filter: this.filter(),
        swapThreshold: this.swapThreshold(),
        easing: this.easing(),
        sort: true,
        draggable: ROW_DRAGGABLE
      };
      // A fresh inline function with the same content (React re-renders) is
      // applied so SortableJS runs the newest closure, but it is no change: a
      // runtime `option(name, v)` still in force keeps winning over it.
      const applied = reapplyOptions(this.instance, this.appliedOptions, next, base, {
        keep: (key: any, prev: any) => {
          const ov: any = this.optionOverrides();
          return ov != null && Object.prototype.hasOwnProperty.call(ov, key) && ov[key] !== prev;
        },
        refreshed: (key: any) => {
          if (this.KEYBOARD_OPTIONS.includes(key)) this.setOverride(key, this.instance.option(key));
        }
      });
      this.appliedOptions = next;
      for (const key of applied as any) {
        // The keyboard reads the value SortableJS now runs with. A remembered
        // runtime `animation` / `handle` / `group` is superseded by the newer
        // `options` value.
        if (this.KEYBOARD_OPTIONS.includes(key)) this.setOverride(key, this.instance.option(key));else if (this.TRACKED_OPTIONS.includes(key)) this.clearOverride(key);
      }
      if (applied.includes('group')) this.registry.notifyPeers();
    })(); }); });
    effect(() => { const __watchVal = (() => [(this.disabled() || this.__rozieCvaDisabled()), this.disableKeyboard(), this.options(), this.optionOverrides()])(); untracked(() => { if (this.__rozieWatchInitial_3) { this.__rozieWatchInitial_3 = false; return; } (() => {
      if (!this.keyboardEnabled()) this.keyboardTurnedOff();
    })(); }); });
    effect(() => { const __watchVal = (() => this.group())(); untracked(() => { if (this.__rozieWatchInitial_4) { this.__rozieWatchInitial_4 = false; return; } (() => this.applyGroup())(); }); });
    effect(() => { const __watchVal = (() => this.cloneable())(); untracked(() => { if (this.__rozieWatchInitial_5) { this.__rozieWatchInitial_5 = false; return; } (() => this.applyGroup())(); }); });
    effect(() => { const __watchVal = (() => this.swapThreshold())(); untracked(() => { if (this.__rozieWatchInitial_6) { this.__rozieWatchInitial_6 = false; return; } ((v: any) => this.instance?.option('swapThreshold', v))(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.handle())(); untracked(() => { if (this.__rozieWatchInitial_7) { this.__rozieWatchInitial_7 = false; return; } ((v: any) => {
      this.instance?.option('handle', this.liveOption('handle', v));
      this.warnIfHandleMissing();
    })(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.keyboardTrigger())(); untracked(() => { if (this.__rozieWatchInitial_8) { this.__rozieWatchInitial_8 = false; return; } (() => this.warnIfHandleMissing())(); }); });
    effect(() => { const __watchVal = (() => this.ghostClass())(); untracked(() => { if (this.__rozieWatchInitial_9) { this.__rozieWatchInitial_9 = false; return; } ((v: any) => this.instance?.option('ghostClass', v))(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.chosenClass())(); untracked(() => { if (this.__rozieWatchInitial_10) { this.__rozieWatchInitial_10 = false; return; } ((v: any) => this.instance?.option('chosenClass', v))(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.dragClass())(); untracked(() => { if (this.__rozieWatchInitial_11) { this.__rozieWatchInitial_11 = false; return; } ((v: any) => this.instance?.option('dragClass', v))(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.filter())(); untracked(() => { if (this.__rozieWatchInitial_12) { this.__rozieWatchInitial_12 = false; return; } ((v: any) => {
      this.instance?.option('filter', v);
      this.setOverride('filter', v);
    })(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.easing())(); untracked(() => { if (this.__rozieWatchInitial_13) { this.__rozieWatchInitial_13 = false; return; } ((v: any) => this.instance?.option('easing', v))(__watchVal); }); });
    effect(() => { const __watchVal = (() => this.items())(); untracked(() => { if (this.__rozieWatchInitial_14) { this.__rozieWatchInitial_14 = false; return; } (() => {
      const lift = this.registry.lift;
      if (lift == null || lift.holder !== this.entry) return;
      const i = this.registry.indexOfLift();
      if (i < 0) {
        this.loseLift();
        return;
      }
      if (this.liftedIndex() !== i) this.liftedIndex.set(i);
      // Once the holder has rendered the lifted row, that is the lifted row
      // element. After a hop this drops the source's old row, which the source
      // may reuse for another item (index keys).
      const row = this.entry.rowEl(i);
      if (row != null) lift.liftedRowEl = row;
      this.focusNearRow(i, lift.key);
    })(); }); });
  }

  ngAfterViewInit() {
    const __options = this.options();
    // Kept across a Lit element's disconnect and reconnect (mount runs again).
    if (this.instructionsId() == null) this.instructionsId.set(nextInstructionsId());
    this.warnIfHandleMissing();
    // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
    // when the options object below references it.
    // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
    // when the options object below references it.
    const sortable = useSortableJS(this.listEl()!.nativeElement, {
      items: () => this.items(),
      onCommit: (next: any) => {
        this.items.set(next), this.__rozieCvaOnChange(next);
      },
      options: {
        animation: this.animation(),
        disabled: (this.disabled() || this.__rozieCvaDisabled()),
        group: this.resolveGroup(),
        handle: this.handle(),
        ghostClass: this.ghostClass(),
        chosenClass: this.chosenClass(),
        dragClass: this.dragClass(),
        filter: this.filter(),
        forceFallback: this.forceFallback(),
        swapThreshold: this.swapThreshold(),
        easing: this.easing(),
        ...__options
      },
      // Lit lit-html `repeat` directive caches its part array by sentinel-
      // comment node identity; SortableJS's physical DOM mutation desyncs
      // that cache. The sigil lowers to `__rozieReconcileAfterDomMutation(this)`
      // on Lit (real call) and `void 0` on the other 5 targets (no-op).
      afterCommit: () => void 0,
      // Every pointer event carries the same payload as the keyboard ones, with
      // item-row indices and the raw SortableJS event as `originalEvent`.
      onChange: (c: any) => {
        const payload = {
          interaction: 'pointer' as const,
          item: c.item,
          el: c.el,
          from: c.from,
          to: c.to,
          oldIndex: c.oldIndex,
          newIndex: c.newIndex,
          originalEvent: c.event
        };
        if (c.kind === 'reorder') this.reorder.emit(payload);else if (c.kind === 'add') this.add.emit(payload);else if (c.kind === 'remove') this.remove.emit(payload);
      },
      onStart: (d: any) => {
        // A pointer drag ends any active keyboard lift first.
        if (this.registry.lift != null) this.endLift('drop');
        // That lift's `end` (pending until a task) comes before this `start`.
        this.registry.flushEnds();
        this.start.emit({
          interaction: 'pointer',
          item: d.item,
          el: d.el,
          from: d.from,
          to: d.to,
          oldIndex: d.oldIndex,
          newIndex: d.newIndex,
          originalEvent: d.event
        });
      },
      // `end` comes from the list the row ended up in: the destination when it
      // is a SortableList, else (dropped outside, or into a SortableJS list
      // that isn't one of ours) this source list. It goes through the
      // registry's `deferEnd`, like a keyboard `end`: it fires in a task after
      // every list involved has written its items and the re-render those
      // writes scheduled, and before the next drag's or lift's `start`. An
      // unmounted list never emits: if the destination has unmounted by then
      // (in its own `add` handler, say), this list (the origin, which emitted
      // `start`) emits it, `to` still the destination; if both are gone,
      // nothing is emitted.
      scheduleEnd: (d: any) => {
        const dest = this.registry.entryFor(d.to);
        const destGone = dest == null && d.to !== d.from && this.registry.wasList(d.to);
        this.registry.deferEnd((host: any) => {
          const row = d.item === undefined || host.el !== d.to ? null : this.rowByKey(d.to, host.keyOf(d.item, d.newIndex));
          host.emit('end', {
            interaction: 'pointer',
            item: d.item,
            el: row ?? this.liveEl(d.el),
            from: d.from,
            to: d.to,
            oldIndex: d.oldIndex,
            newIndex: d.newIndex,
            originalEvent: d.event
          });
        }, destGone ? null : dest ?? this.entry, this.entry);
      }
    });
    this.instance = sortable.instance;
    this.appliedOptions = __options;
    // Runtime `option(name, v)` values this list remembers (Lit keeps them when
    // the element is moved in the DOM and mounts again) apply to the new
    // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
    // first mount.
    // Runtime `option(name, v)` values this list remembers (Lit keeps them when
    // the element is moved in the DOM and mounts again) apply to the new
    // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
    // first mount.
    const remembered: any = this.optionOverrides();
    if (remembered != null) {
      for (const name of Object.keys(remembered) as any) this.instance.option(name, remembered[name]);
    }
    const listEl = this.listEl()?.nativeElement;
    const stopNative = (ev: any) => {
      if (ev.target === listEl) ev.stopPropagation();
    };
    for (const name of this.SORTABLE_DOM_EVENTS as any) listEl?.addEventListener(name, stopNative);
    // A focused row that stops being focusable (its tabindex goes when the
    // keyboard turns off) is blurred at once, during the framework's DOM
    // update, with focus going nowhere (`relatedTarget` null): it would land on
    // <body>. Move it to the list instead.
    // A focused row that stops being focusable (its tabindex goes when the
    // keyboard turns off) is blurred at once, during the framework's DOM
    // update, with focus going nowhere (`relatedTarget` null): it would land on
    // <body>. Move it to the list instead.
    const rowBlurred = (ev: any) => {
      if (listEl == null) return;
      const row: any = ev.target;
      if (ev.relatedTarget != null || row == null || row.parentNode !== listEl) return;
      if (!row.classList.contains('rozie-sortable-item') || row.hasAttribute('tabindex') || !row.isConnected) return;
      if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
      listEl.focus();
    };
    listEl?.addEventListener('focusout', rowBlurred);
    this.unhookNativeEvents = () => {
      for (const name of this.SORTABLE_DOM_EVENTS as any) listEl?.removeEventListener(name, stopNative);
      listEl?.removeEventListener('focusout', rowBlurred);
    };

    // Register with the keyboard registry. Other instances call these methods
    // when a keyboard lift hands a row between lists.
    // Register with the keyboard registry. Other instances call these methods
    // when a keyboard lift hands a row between lists.
    this.entry = {
      el: listEl,
      group: () => this.effectiveGroup(),
      label: () => this.listLabel(),
      // A handle-mode list without a handle selector has its keyboard off.
      keyboardEnabled: () => this.keyboardEnabled() && !(this.handleMode() && this.handleSelector() == null),
      items: () => this.items(),
      keyOf: (item: any, i: any) => String(this.keyFor(item, i)),
      labelOf: (item: any, i: any, row: HTMLElement | null = null) => String(this.labelOf(item, i, row)),
      message: (kind: any, ctx: any) => announcementText(this.announcements(), kind, ctx),
      onKey: (key: any, shift: any) => this.holderKey(key, shift),
      write: (next: any) => {
        this.items.set(next), this.__rozieCvaOnChange(next);
      },
      setLifted: (i: any) => {
        this.liftedIndex.set(i);
      },
      // The same text twice in a row would not change the region, and a screen
      // reader would not read it again ("Apple is already first", twice): a
      // repeat alternates a trailing no-break space, which is not spoken.
      announce: (text: any) => {
        const next = text !== '' && text === this.lastSpoken ? text + '\u00A0' : text;
        this.lastSpoken = next;
        this.ariaLiveText.set(next);
      },
      focusRow: (item: any, i: any) => this.refocusRow(item, i),
      focusNear: (i: any) => this.focusNearRow(i),
      rowEl: (i: any) => {
        const list = this.items();
        if (i < 0 || i >= list.length) return null;
        return this.rowByKey(listEl, String(this.keyFor(list[i], i)));
      },
      // Always set (an equal value is a no-op on every target): a compare
      // against $data would read React's render-time ref, stale when two peer
      // changes land in one commit (one list unmounts, another mounts).
      peersChanged: (v: any) => {
        this.hasHopPeer.set(v);
      },
      emit: (name: any, payload: any) => {
        if (name === 'add') this.add.emit(payload);else if (name === 'remove') this.remove.emit(payload);else if (name === 'reorder') this.reorder.emit(payload);else if (name === 'start') this.start.emit(payload);else if (name === 'end') this.end.emit(payload);
      }
    };
    this.unregisterEntry = this.registry.register(this.entry);
    const strayKey = (ev: any) => this.onStrayKey(ev);
    // A pointer press means the user moved on: keys lost to <body> after it
    // are not routed to the lift.
    // A pointer press means the user moved on: keys lost to <body> after it
    // are not routed to the lift.
    const pointerPress = () => {
      if (this.registry.lift != null) this.registry.lift.focusPending = false;
    };
    document.addEventListener('keydown', strayKey);
    document.addEventListener('pointerdown', pointerPress, true);
    this.unhookStrayKeys = () => {
      document.removeEventListener('keydown', strayKey);
      document.removeEventListener('pointerdown', pointerPress, true);
    };
    // $onMount's cleanup-return: closing over a setup-local (`sortable`) does
    // not survive the Solid emitter's setup/cleanup split — it scopes cleanup
    // outside the setup IIFE. Closing over `instance` / `unregisterEntry`
    // (module-scope `let`s) works on every target.
    this.__rozieDestroyRef.onDestroy(() => {
      this.instance?.destroy();
      // Unmounting while holding a keyboard lift ends it (its `end` comes from
      // the origin list, if that one is still mounted).
      if (this.registry.lift != null && this.registry.lift.holder === this.entry) this.loseLift(true);
      this.unregisterEntry?.();
      this.unregisterEntry = null;
      this.unhookNativeEvents?.();
      this.unhookNativeEvents = null;
      this.unhookStrayKeys?.();
      this.unhookStrayKeys = null;
    });
  }

  instance: any = null;
  // The `options` object SortableJS was last given (see the `options` watcher).
  appliedOptions: any = null;
  // Keyboard lift state lives in the shared registry (one active keyboard lift
  // per page, so a later task can hand a lifted row between lists).
  // `$data.liftedIndex` is only its mirror, for the lifted-row styling.
  registry = getKeyboardRegistry();
  // This list's registry entry (a ListEntry), built and registered in $onMount.
  entry: any = null;
  unregisterEntry: any = null;
  // Removes the listeners that keep SortableJS's own DOM events inside the list.
  unhookNativeEvents: any = null;
  // Removes the document keydown listener that catches keys lost to <body>.
  unhookStrayKeys: any = null;
  // SortableJS also dispatches its events as BUBBLING native DOM events
  // (`start`, `end`, `add`, `remove`, `change`, …) on the list element, before
  // it calls the option callbacks. An output binding on the component host
  // (Angular's `(start)` / `(end)` / `(add)` / `(remove)`, a Lit listener) also
  // catches a native DOM event of the same name, so a consumer would get the raw
  // SortableJS event as an extra event. The component re-emits the committed
  // events itself, so stop the raw ones at the list element (only events
  // dispatched ON the list — an `<input>`'s own `change` is untouched).
  SORTABLE_DOM_EVENTS = ['choose', 'unchoose', 'start', 'end', 'add', 'update', 'sort', 'remove', 'filter', 'clone', 'change', 'select', 'deselect'];
  // role="list" takes no aria-orientation, so a horizontal list says which
  // arrow keys move in its instructions instead. A `sort: false` list leaves out
  // the move sentence, and a list whose rows another mounted list could take
  // (by the group SortableJS runs with, `options.group` included) says how to
  // hop.
  instructionsText = () => {
    const __keyboardInstructions = this.keyboardInstructions();
    if (__keyboardInstructions != null) return __keyboardInstructions;
    return defaultInstructions({
      horizontal: this.orientation() === 'horizontal',
      sortable: this.liveOption('sort', true) !== false,
      grouped: this.effectiveGroup() != null && this.hasHopPeer()
    });
  };
  // Instance-scoped synthetic-id store for id-less object items. Keyed by object
  // IDENTITY, so the same object keeps its synthetic id across a reorder (the
  // framework reconciler then rebinds the row component instance to its ORIGINAL
  // item, not its slot position — the data-corruption fix).
  //
  // Phase 73 item #11-b removed the former "fold the WeakMap + counter into ONE
  // member-mutated object const" workaround: `hoistModuleLet`'s reachability
  // walk now also roots at helpers called ONLY from a template expression
  // (`keyFor` is called from `:key`/`:data-id`, never from a hook), so the bare
  // `let __rowKeySeq = 0` below hoists to a `useRef` on React exactly like the
  // hook-reached case — no more per-render reset. Verified in codegen.
  __rowKeyMap = new WeakMap();
  __rowKeySeq = 0;
  // 4-tier per-row key precedence. Its return feeds BOTH :key and :data-id.
  keyFor = (item: any, index: any) => {
    const __itemKey = this.itemKey();
    // (a) function itemKey: consumer-supplied (item, index) => key.
    if (typeof __itemKey === 'function') {
      return __itemKey(item, index);
    }
    // (b) string itemKey: a property name on a non-null object item.
    if (typeof __itemKey === 'string' && item !== null && typeof item === 'object' && item[__itemKey] != null) {
      return item[__itemKey];
    }
    // (c) id-less object (or function) item: assign-on-first-sight WeakMap
    //     synthetic id. Survives reorder because it is keyed by object identity.
    if (item !== null && typeof item === 'object' || typeof item === 'function') {
      if (!this.__rowKeyMap.has(item)) {
        this.__rowKeyMap.set(item, '__rk' + this.__rowKeySeq++);
      }
      return this.__rowKeyMap.get(item);
    }
    // (d) primitive item: fall back to index. NOTE: duplicate primitives are
    //     unsafe to reorder this way — pass a function itemKey for those.
    return index;
  };
  // Resolve the SortableJS `group` option: `cloneable` is a high-level Rozie
  // prop that REPLACES a string `group` with SortableJS's
  // `{ name, pull: 'clone', put: false }` clone-mode object form (a palette
  // takes nothing back, by mouse or keyboard). When
  // `cloneable:false`, pass `$props.group` through verbatim. When
  // `cloneable:true` AND `$props.group` is null, leave it null — a clone-mode
  // list without a group name is not meaningful (no peer list can join the
  // cross-list flow). Shared by $onMount construction AND the group/cloneable
  // $watch reconcile below — single source of truth, no duplicated ternary.
  resolveGroup = () => this.cloneable() && typeof this.group() === 'string' ? {
    name: this.group(),
    pull: 'clone' as const,
    put: false as const
  } : this.group() ?? undefined;
  // The group SortableJS actually runs with: a runtime `option('group', v)`,
  // else `options.group` (it lands after the named props in the merge), else
  // the `group` / `cloneable` props. Keyboard hops follow the same rules as the
  // mouse, so they read this one.
  effectiveGroup = () => {
    const ov: any = this.optionOverrides();
    if (ov != null && Object.prototype.hasOwnProperty.call(ov, 'group')) return ov.group;
    const o: any = this.options();
    return o != null && o.group != null ? o.group : this.resolveGroup();
  };
  // Resolve itemClass for a row: a static value (string | array | object) OR a
  // per-row (item, index) => class function. The result is fed into the :class
  // array and normalized by each target's class path (rozieClass / clsx / native).
  itemClassFor = (item: any, index: any) => {
    const v = this.itemClass();
    return typeof v === 'function' ? v(item, index) : v;
  };
  // Resolve itemStyle for a row: a static value (string | object) OR a per-row
  // (item, index) => style function. Returns string | object | null; the dynamic
  // :style binding normalizes it per target. null / empty → attribute dropped.
  itemStyleFor = (item: any, index: any) => {
    const __itemStyle = this.itemStyle();
    const s = typeof __itemStyle === 'function' ? __itemStyle(item, index) : __itemStyle;
    return s == null || s === '' ? null : s;
  };
  // Read the display label for an item — used by the aria-live announcer.
  // Phase 16 R7 / D-08: $props.labelFor reads as `null` on all 6 targets when
  // the consumer omits it (Plan 16-01 prop-default coercion fix); the check is
  // a plain null compare — NO runtime callable-type coercion. Without
  // `labelFor` or a `label` field, the row's text (`row`), else `String(item)`
  // for a primitive, else `item {position}`.
  labelOf = (item: any, idx: any, row: HTMLElement | null = null) => {
    const __labelFor = this.labelFor();
    if (__labelFor !== null) return __labelFor(item, idx);
    if (item !== null && typeof item === 'object' && item.label != null) return item.label;
    return fallbackLabel(item, idx, row);
  };
  // The text this list's live region showed last (see the registry entry's
  // `announce`).
  lastSpoken = '';
  // Keyboard handler (Phase 16 R7): Space/Enter lift and drop; while lifted,
  // ArrowUp/ArrowDown (ArrowLeft/ArrowRight when horizontal), Home/End and
  // PageUp/PageDown move the row, and Escape returns it to where it was lifted
  // from. The lift itself lives in the shared keyboard registry. After
  // any array-reorder write, refocusRow() keeps focus on the moved row (or its
  // handle) on all six targets.
  //
  // Note: `index` is passed directly as a number. Plan 16-02 (Solid call-arg
  // accessor unwrap) ensures Solid's <For> alias unwraps to `index()` at the
  // call site — no runtime callable-type coercion needed in user source.
  // Keyboard reordering is available only when the list is not disabled AND the
  // `disableKeyboard` opt-out is off. Drives BOTH the row tabindex (rows are
  // focusable only when reorderable) and the onRowKeyDown guard below. Reads
  // straight off $props so the tabindex binding re-evaluates reactively when
  // `disabled`/`disableKeyboard` toggle at runtime.
  //
  // The keyboard follows the SortableJS options the mouse obeys: `disabled`
  // (the prop, `options.disabled`, or `option('disabled', v)`), `filter` and
  // `draggable` (which rows lift, see rowLiftable) and `sort: false` (no moves
  // within the list). `liveOption` reads the value SortableJS runs with: one set
  // at runtime, else `options`, else the named prop.
  KEYBOARD_OPTIONS = ['disabled', 'filter', 'draggable', 'sort'];
  liveOption = (name: any, fallback: any) => {
    const ov: any = this.optionOverrides();
    if (ov != null && Object.prototype.hasOwnProperty.call(ov, name)) return ov[name];
    const o: any = this.options();
    if (o != null && o[name] !== undefined) return o[name];
    return fallback;
  };
  setOverride = (name: any, value: any) => {
    this.optionOverrides.set({
      ...this.optionOverrides(),
      [name]: value
    });
  };
  clearOverride = (name: any) => {
    const ov: any = this.optionOverrides();
    if (ov == null || !Object.prototype.hasOwnProperty.call(ov, name)) return;
    const next = {
      ...ov
    };
    delete next[name];
    this.optionOverrides.set(next);
  };
  // Options whose runtime value (`option(name, v)`) is remembered, so a later
  // change of the matching prop doesn't overwrite it: the keyboard ones, plus
  // `animation`, `handle` and `group` (runtime override → `options` → prop).
  TRACKED_OPTIONS = [...this.KEYBOARD_OPTIONS, 'animation', 'handle', 'group'];
  keyboardEnabled = () => !this.disableKeyboard() && !this.liveOption('disabled', (this.disabled() || this.__rozieCvaDisabled()));
  // The handle selector SortableJS runs with (`option('handle', v)`, else
  // `options.handle`, else the `handle` prop): the keyboard reads the same one.
  handleSelector = () => this.liveOption('handle', this.handle());
  // keyboardTrigger='handle' mode: rows are not tab stops and the keys are read
  // from the consumer's handle element instead. Any other value is 'row' mode.
  handleMode = () => this.keyboardTrigger() === 'handle';
  // Rows are tab stops only in row mode (and only while keyboard is enabled).
  rowTabbable = () => this.keyboardEnabled() && !this.handleMode();
  // One-time-per-change dev warning: handle mode needs a handle selector. Without
  // one the keyboard is OFF (see the onRowKeyDown gate) — never a silent fallback
  // to row mode, which would re-introduce the tab stops the consumer opted out of.
  warnIfHandleMissing = () => {
    if (this.handleMode() && this.handleSelector() == null) {
      console.warn('[rozie-sortable-list] keyboardTrigger is "handle" but no handle selector is set, so keyboard reordering is off. Pass a handle selector (e.g. handle=".grip") or use keyboardTrigger "row".');
    }
  };
  // True only when a keydown originated inside a `handle` element that belongs to
  // THIS row. Walks the COMPOSED ancestor chain from the event target up to (but
  // excluding) the row (currentTarget): assignedSlot -> parentNode -> shadow host.
  // Plain closest()/contains() stop at a shadow boundary, and Lit renders a Rozie
  // consumer's slot content inside the SortableList shadow root while plain-HTML
  // consumers project light-DOM nodes through a <slot>. composedPath() is not
  // used because React's synthetic event does not expose it. Another
  // .rozie-sortable-item met first means the key came from a NESTED list's row,
  // which must not reorder this (outer) list.
  isHandleKeyOrigin = ($event: any) => {
    const sel = this.handleSelector();
    if (sel == null) return false;
    const row = $event.currentTarget;
    let n: any = $event.target;
    while (n && n !== row) {
      if (n.nodeType === 1) {
        if (n.matches(sel)) {
          // Matched a handle: it counts only if this row is reachable from here
          // without crossing a different sortable item.
          let m: any = n.assignedSlot ?? n.parentNode ?? n.host;
          while (m && m !== row) {
            if (m.nodeType === 1 && m.classList.contains('rozie-sortable-item')) return false;
            m = m.assignedSlot ?? m.parentNode ?? m.host;
          }
          return m === row;
        }
        if (n.classList.contains('rozie-sortable-item')) return false;
      }
      n = n.assignedSlot ?? n.parentNode ?? n.host;
    }
    return false;
  };
  // Put focus back on the MOVED row (row mode) or its handle (handle mode) after
  // a reorder write. Looks the row up by KEY (data-id), not by index, so it finds
  // the moved row whether this runs before the framework commit (the row element
  // is the same one) or after it (Svelte/Solid/Lit re-create the DOM) — and it is
  // correct for index-keyed primitive lists too. Direct children of the list
  // container only: that skips nested-list rows and the header/footer slot
  // content.
  //
  // Two passes. (1) A microtask covers targets that commit synchronously or in an
  // earlier microtask (Vue's scheduler flush is queued by the model write, before
  // this one). (2) A timer + rAF "heal" pass covers targets whose DOM commit is
  // scheduled AFTER the key handler returns (Angular): the commit can MOVE the
  // focused row, and moving a focused node blurs it, so a Home/End/Escape jump or
  // a rapid Space/Arrow/Arrow/Space burst would otherwise end with focus on
  // <body>. The heal pass never steals: it acts only when focus has been lost to
  // <body>. (`$restoreFocus(selector, index)` is not enough here: it is a no-op on
  // Vue/Angular, where a long jump moves the focused row itself, and it looks the
  // row up by index, which can land on a neighbour on Lit.) The $refs read
  // happens here, synchronously, inside an event handler — which is safe.
  refocusRow = (item: any, idx: any) => {
    const listEl = this.listEl()?.nativeElement;
    const sel = this.handleSelector();
    const useHandle = this.handleMode();
    const key = String(this.keyFor(item, idx));
    // While this refocus is outstanding, a key that falls to <body> belongs to
    // the lift (see onStrayKey). Cleared once the row has focus again, or by a
    // pointer press anywhere.
    const pending = this.registry.lift;
    if (pending != null) pending.focusPending = true;
    const focusIt = (onlyIfLost: any) => {
      if (!listEl) return;
      if (useHandle && sel == null) return;
      if (onlyIfLost && document.activeElement && document.activeElement !== document.body) return;
      for (const row of Array.from(listEl.children) as any[]) {
        if (row.getAttribute('data-id') === key) {
          const target = useHandle ? row.querySelector(sel) : row;
          if (target && typeof target.focus === 'function') {
            target.focus();
            const l = this.registry.lift;
            if (l != null && l === pending && l.key === key) {
              l.focusPending = false;
              // This row is the lifted row element now (see the items watcher).
              l.liftedRowEl = row;
            }
          }
          return;
        }
      }
    };
    queueMicrotask(() => focusIt(false));
    setTimeout(() => focusIt(true), 0);
    if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => focusIt(true));
  };
  // `el` in an event payload: the row element while it is in the page, else
  // null (a row that left with an unmounted list is no row of any list).
  liveEl = (el: any) => el != null && el.isConnected ? el : null;
  // The row element carrying `data-id === key` among a list element's direct
  // children (skips nested-list rows and header/footer slot content).
  rowByKey = (listEl: any, key: any) => {
    if (!listEl || key == null) return null;
    for (const row of Array.from(listEl.children) as any[]) {
      if (row.getAttribute('data-id') === key) return row;
    }
    return null;
  };
  // After the consumer changed the items of the list holding a lift, put focus
  // on the row (or its handle) whose key is `key`, else the row nearest `index`
  // (or the list itself when it has no rows left) — but only once focus has fallen to <body> (the focused row's element went
  // away: the lift was lost, or a framework that keys rows by object identity
  // re-created the lifted row). Never steals focus from anywhere else. Same
  // three passes as refocusRow, for targets that commit late.
  focusNearRow = (index: number, key: string | null = null) => {
    const listEl = this.listEl()?.nativeElement;
    const sel = this.handleSelector();
    const useHandle = this.handleMode();
    const focusIt = () => {
      if (!listEl) return;
      if (useHandle && sel == null) return;
      if (document.activeElement && document.activeElement !== document.body) return;
      const rows = Array.from(listEl.children).filter((r: any) => r.hasAttribute('data-id') && r.classList.contains('rozie-sortable-item')) as any[];
      if (rows.length === 0) {
        // The list is now empty: focus the list itself (out of the tab order)
        // so keyboard and screen-reader users stay where they were.
        if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
        listEl.focus();
        return;
      }
      const row = rows.find((r: any) => key != null && r.getAttribute('data-id') === key) ?? rows[Math.max(0, Math.min(rows.length - 1, index))];
      const target = useHandle ? row.querySelector(sel) : row;
      if (target && typeof target.focus === 'function') target.focus();
    };
    queueMicrotask(focusIt);
    setTimeout(focusIt, 0);
    if (typeof requestAnimationFrame === 'function') requestAnimationFrame(focusIt);
  };
  // Speak `text` from `target`'s aria-live region. The region that spoke last
  // is cleared when it belongs to another list, so a message is heard once, from
  // the list the row is in now, and never from a list that just lost it.
  speak = (target: any, text: any) => {
    const prev = this.registry.speaker;
    if (prev != null && prev !== target && this.registry.has(prev)) prev.announce('');
    this.registry.speaker = target;
    target.announce(text);
  };
  // Say announcement `kind` from `target`, in `target`'s words: its
  // `announcements` function for that kind, else the default text (see
  // ./internal/announcements). `index` is the row's 0-based position in
  // `target`, `row` the row element its label is read from (when there is no
  // `labelFor` or `label` field), and `total` how many rows `target` holds after
  // the change (null for the kinds without a position). A function returning
  // null or '' clears the region, so nothing is said.
  say = (target: any, kind: AnnouncementKind, item: unknown, index: number, row: HTMLElement | null, total: number | null = null, fromList: any = null) => {
    const ctx: any = {
      item,
      list: this.registry.listName(target)
    };
    // The label is read only when the text needs it (a default with `{label}`,
    // or an override that reads `label`), so `labelFor` is not called for a
    // message that doesn't name the row (`Lift ended`: the item has left).
    let label: string | null = null;
    Object.defineProperty(ctx, 'label', {
      enumerable: true,
      get: () => {
        if (label === null) label = target.labelOf(item, index, row);
        return label;
      }
    });
    if (total != null) {
      ctx.position = index + 1;
      ctx.total = total;
    }
    if (fromList != null) ctx.fromList = this.registry.listName(fromList);
    this.speak(target, target.message(kind, ctx));
  };
  // The lifted item is no longer in the list holding it: the consumer changed
  // that list's items (or re-keyed the item), or the list is unmounting. End the
  // lift without writing anything (the item is wherever the consumer's data put
  // it). `end` still fires once, with `item` = the lifted value and `el: null`
  // (there is no row), so keyboard `start` / `end` pair (unless the holder and the origin have both unmounted). Lost to a consumer change (not an
  // unmount), the holder says `Lift ended` and, if focus fell to <body> with the
  // row, focuses its row nearest where the lifted row was.
  loseLift = (unmounting: any = false) => {
    const lift = this.registry.lift;
    if (!lift) return;
    const h = lift.holder;
    this.registry.lift = null;
    h.setLifted(null);
    if (!unmounting) {
      this.say(h, 'liftEnded', lift.item, lift.index ?? lift.origin.index, lift.liftedRowEl);
      h.focusNear(lift.index ?? lift.origin.index);
    }
    const payload = {
      interaction: 'keyboard' as const,
      item: lift.item,
      el: null,
      from: lift.origin.list.el,
      to: h.el,
      oldIndex: lift.origin.index,
      newIndex: -1
    };
    // Like every `end`, in a task after the writes, from the holder. An
    // unmounted list never emits (Angular rejects an emit from a destroyed
    // component): when the holder is unmounting, the origin list (which emitted
    // `start`) ends the lift if it is still mounted, so `start` and `end` pair;
    // if it is gone too, nothing is emitted.
    this.registry.deferEnd((host: any) => host.emit('end', payload), h, lift.origin.list);
  };
  // Keyboard `start` / `end` (the same payload as every other event): `item` is
  // the item value, `el` its row element. `start` fires from the origin list
  // (`from`), `end` from the list the row ends up in (`to`). `el` is the row in
  // that list when it is rendered, else `fallbackEl` (the row element the move
  // started from, before a target re-rendered). `end` is called after
  // `registry.lift` is cleared, so a consumer `end` handler that writes the
  // items (re-keying a clone copy) is not mistaken for a lost lift, and it is
  // emitted in a task (`registry.deferEnd`), after the writes AND the re-render
  // they schedule: a consumer `end` handler reads the new state on every target
  // (React included, whose handler closure is the one from the latest render).
  // If `to` has unmounted by then, `from` (the origin, which emitted `start`)
  // emits it instead, `to` unchanged in the payload; an unmounted list never
  // emits.
  keyboardStartEnd = (name: any, lift: any, from: any, to: any, oldIndex: any, newIndex: any, fallbackEl: HTMLElement | null = null) => {
    const fire = (host: any) => host.emit(name, {
      interaction: 'keyboard',
      item: lift ? lift.item : null,
      el: (lift && host === to ? this.rowByKey(host.el, lift.key) : null) ?? this.liveEl(fallbackEl),
      from: from.el,
      to: to.el,
      oldIndex,
      newIndex
    });
    if (name === 'end') this.registry.deferEnd(fire, to, from);else fire(from);
  };
  // Move the lifted row to `toIndex` (clamped) within the list holding it.
  // Works through the registry entry, so it acts on the current holder. `dir`
  // is the key's direction (-1 toward the start), for when the row can't move.
  moveLiftTo = (toIndex: any, dir: any) => {
    const lift = this.registry.lift;
    if (!lift) return;
    const h = lift.holder;
    const from = this.registry.indexOfLift();
    if (from < 0) {
      this.loseLift();
      return;
    }
    const items = h.items();
    const to = Math.max(0, Math.min(items.length - 1, toIndex));
    // The moved row's element, read before the write (an index key changes).
    const el = h.rowEl(from);
    if (to === from) {
      // Nowhere to go: say so (the row is already at that end).
      this.say(h, dir < 0 ? 'atStart' : 'atEnd', items[from], from, el ?? lift.liftedRowEl, items.length);
      return;
    }
    const next = [...items];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    // Index keys (primitive items without itemKey) change with the position.
    // Update the lift BEFORE writing: a target whose watchers run synchronously
    // on the write must already see where the row is going.
    lift.key = h.keyOf(moved, to);
    lift.index = to;
    h.write(next);
    h.setLifted(to);
    // Name the row that MOVED from the local `moved` item: on React/Vue/Lit the
    // items prop still holds the pre-write array here. Labels come from the
    // holder's own `labelFor`.
    this.say(h, 'moved', moved, to, el, items.length);
    h.focusRow(moved, to);
    h.emit('reorder', {
      interaction: 'keyboard',
      item: moved,
      el,
      from: h.el,
      to: h.el,
      oldIndex: from,
      newIndex: to
    });
  };
  // Hop the lifted row to the next (`dir` 1) or previous (-1) list it could
  // also reach by mouse, in composed-tree source order. One hand-off: the source
  // writes its items without the row, the destination writes them with it, and
  // the destination becomes the holder. As with the mouse, the destination
  // emits `add` first, then the source emits `remove`. A forward hop lands
  // first, a backward hop lands last.
  hop = (dir: any) => {
    const lift = this.registry.lift;
    if (!lift) return;
    const from = lift.holder;
    const i = this.registry.indexOfLift();
    if (i < 0) {
      this.loseLift();
      return;
    }
    const fromItems = from.items();
    const data = fromItems[i];
    const el = from.rowEl(i);
    // Keep the lifted row element current: lists nested inside it (a grid
    // widget's columns) are never hop targets. Before a target re-renders the
    // row may not exist yet, so keep the last known element then.
    lift.liftedRowEl = el ?? lift.liftedRowEl;
    const to = this.registry.findHopTarget(from, dir);
    if (to == null) {
      this.say(from, dir === 1 ? 'noListAfter' : 'noListBefore', data, i, el ?? lift.liftedRowEl);
      return;
    }
    const origin = lift.origin;
    const toItems = to.items();
    // A clone copy hopping back into the list it was cloned from merges with
    // its original there (that list never gave it up), rather than adding a
    // second row with the same key.
    if (lift.copy && to === origin.list) {
      let home = toItems.indexOf(data);
      if (home < 0) home = Math.max(0, Math.min(toItems.length - 1, origin.index));
      lift.holder = to;
      lift.copy = false;
      lift.key = to.keyOf(toItems[home], home);
      lift.item = toItems[home];
      lift.index = home;
      const rest = [...fromItems];
      rest.splice(i, 1);
      from.write(rest);
      from.emit('remove', {
        interaction: 'keyboard',
        item: data,
        el,
        from: from.el,
        to: to.el,
        oldIndex: i,
        newIndex: -1
      });
      from.setLifted(null);
      to.setLifted(home);
      this.say(to, 'movedToList', data, home, el, toItems.length, from);
      to.focusRow(toItems[home], home);
      return;
    }
    // The first hop out of a clone source (`pull: 'clone'`) leaves the source
    // untouched and carries a copy (the same item value the mouse path
    // inserts); from then on the copy moves like any row.
    const cloneOut = canHop(from.group(), to.group()).copy && from === origin.list && !lift.copy;
    const at = dir === 1 ? 0 : toItems.length;
    // Update the lift BEFORE writing, so a target whose watchers run
    // synchronously on a write already sees the new holder.
    lift.holder = to;
    lift.key = to.keyOf(data, at);
    lift.index = at;
    lift.hopped = true;
    if (cloneOut) {
      lift.copy = true;
    } else {
      const rest = [...fromItems];
      rest.splice(i, 1);
      from.write(rest);
    }
    const next = [...toItems];
    next.splice(at, 0, data);
    to.write(next);
    // The destination has not rendered its new row yet: `el` is the row the
    // move started from. `add` (destination) before `remove` (source), as by
    // mouse.
    to.emit('add', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: -1,
      newIndex: at
    });
    if (!cloneOut) from.emit('remove', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: i,
      newIndex: -1
    });
    from.setLifted(null);
    to.setLifted(at);
    this.say(to, 'movedToList', data, at, el, toItems.length + 1, from);
    to.focusRow(data, at);
  };
  // End the active keyboard lift. 'drop' leaves the row where it is ('off' too,
  // announced as `Lift ended`: the holder's keyboard was turned off); 'cancel'
  // returns it to the list and position it was lifted from (after hops, a
  // reverse hand-off with its own `remove` / `add`; a clone copy is removed).
  // Emits `end` once, from the list the row ends up in.
  endLift = (kind: any) => {
    const lift = this.registry.lift;
    if (!lift) return;
    const h = lift.holder;
    const origin = lift.origin;
    const at = this.registry.indexOfLift();
    if (at < 0) {
      this.loseLift();
      return;
    }
    const items = h.items();
    const item = items[at];
    // The lifted row's element, read before any write below. Right after a hop
    // the holder may not have rendered it yet: its label is read from the
    // lifted row element then.
    const el = h.rowEl(at);
    const row = el ?? lift.liftedRowEl;
    if (kind === 'drop' || kind === 'off') {
      // A row that hopped always names its list, even back in its origin. The
      // keyboard turned off mid-lift ('off') ends it where it is, too.
      if (kind === 'off') this.say(h, 'liftEnded', item, at, row);else this.say(h, lift.hopped ? 'droppedInList' : 'dropped', item, at, row, items.length);
      h.setLifted(null);
      this.registry.lift = null;
      this.keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
      return;
    }
    if (h !== origin.list && !this.registry.has(origin.list) && lift.copy) {
      // A clone copy is removed on cancel even when its source list has
      // unmounted (the source never gave its item up). Focus moves to the
      // neighbouring row, if any. The lift ends BEFORE the write: the copy is
      // leaving on purpose, and a target whose items watcher runs synchronously
      // on the write (Solid) must not take it for a lost lift (a second `end`).
      this.registry.lift = null;
      const rest = [...items];
      rest.splice(at, 1);
      h.write(rest);
      h.emit('remove', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: h.el,
        oldIndex: at,
        newIndex: -1
      });
      h.setLifted(null);
      this.say(h, 'cancelledRemoved', item, at, row);
      if (rest.length > 0) {
        const k = Math.min(at, rest.length - 1);
        h.focusRow(rest[k], k);
      }
      // The copy is gone, so there is no row: `el: null`.
      const fromEl = origin.list.el;
      this.registry.deferEnd((host: any) => host.emit('end', {
        interaction: 'keyboard',
        item,
        el: null,
        from: fromEl,
        to: h.el,
        oldIndex: origin.index,
        newIndex: -1
      }), h, origin.list);
      return;
    }
    if (h !== origin.list && (!this.registry.has(origin.list) || !isRenderable(origin.list.el) || !origin.list.keyboardEnabled())) {
      // The origin list has unmounted, is hidden, or has its keyboard off:
      // there is nowhere to return to (focus would be stranded), so the row
      // stays where it is (the lift ends as a drop at its position).
      this.say(h, 'cancelledStays', item, at, row, items.length);
      h.setLifted(null);
      this.registry.lift = null;
      this.keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
      return;
    }
    if (h === origin.list) {
      const to = Math.max(0, Math.min(items.length - 1, origin.index));
      if (to !== at) {
        const next = [...items];
        next.splice(at, 1);
        next.splice(to, 0, item);
        lift.key = h.keyOf(item, to);
        h.write(next);
        h.focusRow(item, to);
        h.emit('reorder', {
          interaction: 'keyboard',
          item,
          el,
          from: h.el,
          to: h.el,
          oldIndex: at,
          newIndex: to
        });
      }
      this.say(h, lift.hopped ? 'cancelledReturnedToList' : 'cancelledReturned', item, to, row, items.length);
      h.setLifted(null);
      this.registry.lift = null;
      this.keyboardStartEnd('end', lift, origin.list, h, origin.index, to, el);
      return;
    }
    // Reverse hand-off from the current holder back to the origin list.
    const home = origin.list;
    const homeItems = home.items();
    let back;
    if (lift.copy) {
      // The clone source never gave its item up: drop the copy, focus the
      // original.
      back = homeItems.indexOf(item);
      if (back < 0) back = Math.max(0, Math.min(homeItems.length - 1, origin.index));
    } else {
      back = Math.min(origin.index, homeItems.length);
    }
    lift.holder = home;
    lift.key = home.keyOf(item, back);
    const rest = [...items];
    rest.splice(at, 1);
    h.write(rest);
    if (!lift.copy) {
      const next = [...homeItems];
      next.splice(back, 0, item);
      home.write(next);
      // `add` (destination) before `remove` (source), as by mouse.
      home.emit('add', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: home.el,
        oldIndex: -1,
        newIndex: back
      });
    }
    h.emit('remove', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: home.el,
      oldIndex: at,
      newIndex: -1
    });
    h.setLifted(null);
    // `home` holds the lift during its write, so a target whose items watcher
    // runs synchronously on the write (Solid) highlighted the row there: clear it.
    home.setLifted(null);
    this.say(home, 'cancelledReturnedToList', item, back, row, homeItems.length + (lift.copy ? 0 : 1));
    home.focusRow(lift.copy ? homeItems[back] : item, back);
    this.registry.lift = null;
    this.keyboardStartEnd('end', lift, home, home, origin.index, back, lift.copy ? home.rowEl(back) : el);
  };
  // This list's keyboard was turned off (`disabled`, `disableKeyboard`, or
  // `option('disabled', true)`): a lift it holds ends where the row is, with
  // its `end`.
  endLiftIfHeld = () => {
    const lift = this.registry.lift;
    if (lift != null && lift.holder === this.entry) this.endLift('off');
  };
  // In row mode the rows leave the tab order when the keyboard turns off, and a
  // focused element that stops being focusable drops focus to <body>. If one of
  // this list's rows still has focus (a target whose watcher runs before its DOM
  // update), move it to the list itself (out of the tab order), like an emptied
  // list. Once the DOM update has run, the `focusout` listener added in $onMount
  // does it instead.
  keepFocusOffBody = () => {
    const listEl = this.entry ? this.entry.el : null;
    if (!listEl) return;
    const root: any = listEl.getRootNode();
    const a: any = root != null ? root.activeElement : null;
    if (a == null || a.parentNode !== listEl || !a.classList.contains('rozie-sortable-item')) return;
    if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
    listEl.focus();
  };
  keyboardTurnedOff = () => {
    this.endLiftIfHeld();
    this.keepFocusOffBody();
  };
  // Lift the row at `index` of this list.
  startLift = (index: any) => {
    const __items = this.items();
    if (!this.entry) return;
    // A previous drag's or lift's `end` that is still pending fires first, so
    // every `end` comes before the next `start`.
    this.registry.flushEnds();
    const item = __items[index];
    this.registry.lift = {
      holder: this.entry,
      key: this.entry.keyOf(item, index),
      item,
      copy: false,
      hopped: false,
      origin: {
        list: this.entry,
        index
      },
      liftedRowEl: this.entry.rowEl(index),
      index
    };
    this.liftedIndex.set(index);
    this.say(this.entry, 'lifted', item, index, this.registry.lift.liftedRowEl, __items.length);
    this.keyboardStartEnd('start', this.registry.lift, this.entry, this.entry, index, index);
  };
  onRowKeyDown = ($event: any, index: any) => {
    // Origin guard — must run FIRST, before the keyboardEnabled() check.
    //  - handle mode (keyboardTrigger='handle'): reorder keys apply ONLY when the
    //    keydown came from inside this row's `handle` element. A missing `handle`
    //    selector means keyboard is OFF (warned in warnIfHandleMissing).
    //  - row mode (quick 260716-ggq): reorder keys apply ONLY when the row
    //    element ITSELF is focused. A slotted interactive child (an <input>,
    //    <button>, etc. rendered into the row's default slot) bubbles its own
    //    keydown up to this handler — without this guard, Space/Enter typed into
    //    that child would be hijacked for lift/drop instead of reaching the
    //    child.
    if (this.handleMode()) {
      if (this.handleSelector() == null || !this.isHandleKeyOrigin($event)) return;
    } else if ($event.target !== $event.currentTarget) {
      return;
    }
    // Defense-in-depth: when keyboard reordering is off the rows carry no
    // tabindex and can't receive focus, but a consumer-focused row (or a
    // programmatic .focus()) must still no-op here rather than reorder.
    if (!this.keyboardEnabled()) return;
    // While a lift exists, reorder keys in the list holding it act on it. A key
    // from ANOTHER list of the holder's group is routed to the holder only when
    // it comes from the lifted row element itself (its old row, still there
    // before the frameworks re-render after a hop; compared by element, so a
    // row of another list that shares the lifted row's key is not it) or while a refocus after a move is
    // outstanding (a fast burst). Any other row — and every row of an unrelated
    // list (another group, or none) — keeps single-list behaviour: Space/Enter
    // there drops the foreign lift and lifts its own row, other keys do nothing.
    const lift = this.registry.lift;
    const key = $event.key;
    if (lift != null) {
      const mine = this.groupNameOf(this.effectiveGroup());
      const sameGroup = mine != null && mine === this.groupNameOf(lift.holder.group());
      const fromLiftedRow = lift.liftedRowEl != null && $event.currentTarget === lift.liftedRowEl;
      if (lift.holder === this.entry || sameGroup && (fromLiftedRow || lift.focusPending === true)) {
        if (lift.holder.onKey(key, !!$event.shiftKey)) $event.preventDefault();
        return;
      }
    }
    // Space (' ' on browsers; KeyboardEvent.key === ' ') OR Enter — lift. A row
    // the mouse can't drag (it matches `filter`, or not `draggable`) can't be
    // lifted either: the key is left alone (not prevented).
    if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
      const rules = {
        filter: this.liveOption('filter', this.filter()),
        draggable: this.liveOption('draggable', undefined),
        sortable: this.instance
      };
      if (!rowLiftable($event.currentTarget as any, rules)) return;
      $event.preventDefault();
      if (lift != null) this.endLift('drop');
      this.startLift(index);
    }
  };
  // The group NAME of a SortableJS group option (string or object form).
  groupNameOf = (g: any) => g == null ? null : typeof g === 'string' ? g : g.name ?? null;
  // A reorder key for the lift THIS list holds (routed here from any list via
  // the registry entry's onKey). Returns true when the key was handled. Every
  // key except Space/Enter acts only while lifted, so it never steals keys from
  // fields inside a row.
  holderKey = (key: any, shift: any) => {
    const lift = this.registry.lift;
    if (lift == null || lift.holder !== this.entry) return false;
    if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
      this.endLift('drop');
      return true;
    }
    if (key === 'Escape') {
      this.endLift('cancel');
      return true;
    }
    const horizontal = this.orientation() === 'horizontal';
    const prevKey = horizontal ? 'ArrowLeft' : 'ArrowUp';
    const nextKey = horizontal ? 'ArrowRight' : 'ArrowDown';
    if (shift && (key === nextKey || key === prevKey)) {
      // Hopping is on wherever a group is set; an ungrouped list ignores it.
      if (this.effectiveGroup() == null) return false;
      this.hop(key === nextKey ? 1 : -1);
      return true;
    }
    const from = this.registry.indexOfLift();
    if (from < 0) {
      this.loseLift();
      return false;
    }
    // pageStep below 1 (or not a number) still moves by at least one position.
    const step = Math.max(1, Math.floor(Number(this.pageStep()) || 1));
    let to: any = null;
    if (key === nextKey) to = from + 1;else if (key === prevKey) to = from - 1;else if (key === 'Home') to = 0;else if (key === 'End') to = this.entry.items().length - 1;else if (key === 'PageDown') to = from + step;else if (key === 'PageUp') to = from - step;
    if (to === null) return false;
    // `sort: false`: no moves within the list (as by mouse). The key is still
    // taken, so it does not scroll the page while a row is lifted, and says why
    // nothing moved.
    if (this.liveOption('sort', true) === false) {
      this.say(this.entry, 'notSortable', this.entry.items()[from], from, this.entry.rowEl(from) ?? lift.liftedRowEl);
      return true;
    }
    this.moveLiftTo(to, key === prevKey || key === 'Home' || key === 'PageUp' ? -1 : 1);
    return true;
  };
  // A key pressed while focus has fallen to <body> during a lift. A hop removes
  // the focused row from one list and the destination may render (and take
  // focus) only after the handler returns (Angular), so the next key of a fast
  // burst can reach <body>. The list holding the lift handles it as if it had
  // landed on the lifted row, then puts focus back on that row.
  //
  // Only while a refocus of ours is outstanding (`focusPending`): focus that left
  // the lifted row for any other reason (the user clicked elsewhere or tabbed
  // away) keeps today's behaviour, and those keys are not ours. Modified keys
  // and keys someone already handled are never taken.
  onStrayKey = (ev: any) => {
    const lift = this.registry.lift;
    if (lift == null || lift.holder !== this.entry || !lift.focusPending) return;
    if (ev.defaultPrevented || ev.ctrlKey || ev.metaKey || ev.altKey) return;
    const t = ev.target;
    if (t !== document.body && t !== document.documentElement) return;
    const item = lift.item;
    const at = this.registry.indexOfLift();
    if (!this.holderKey(ev.key, !!ev.shiftKey)) return;
    ev.preventDefault();
    const now = this.registry.lift;
    if (now != null) now.holder.focusRow(now.item, this.registry.indexOfLift());else if (at >= 0) this.entry.focusRow(item, at);
  };
  // SortableJS wiring lives in `useSortableJS()` (./internal/useSortableJS).
  // The helper owns the SortableJS-vs-reconciler dance — DOM-restore hardening
  // against fragile-event paths, identity-based item lookup over fragile
  // `e.oldIndex`, and the single-onEnd disambiguation that collapses
  // onUpdate / onAdd / onRemove into one handler.
  //
  // What stays here is purely declarative: which array to read, what to write
  // back, what to emit, and how to bridge `afterCommit` to the Lit-only
  // `$reconcileAfterDomMutation()` sigil.
  // `options.group` wins over `group` / `cloneable` (see effectiveGroup), for
  // the mouse as for the keyboard.
  // A group change can change which lists can take each other's rows: every
  // list rechecks its Shift instructions.
  applyGroup = () => {
    this.instance?.option('group', this.effectiveGroup());
    this.registry.notifyPeers();
  };
  // Imperative handle (Phase 21 $expose). The SortableJS imperative surface a
  // consumer can't drive through props alone — exposed uniformly to all 6 targets.
  // Each guards the pre-mount/destroyed `instance = null`. Collision-clear: none of
  // the 4 verb names collide with the 16 props or the 5 events — `option` is a
  // distinct identifier from the `options` prop, so ROZ121 is clear.
  getInstance = () => {
    return this.instance;
  };
  // toArray()/sort() use the rows' data-id keys — every row carries
  // :data-id="keyFor(item, index)", so toArray() returns the current key order
  // (set itemKey for stable object-list keys).
  toArray = () => {
    return this.instance ? this.instance.toArray() : [];
  };
  // sort(order) reorders the bound items by those keys and writes them back
  // (the framework re-renders the rows; SortableJS never moves them behind the
  // model). Listed keys come first, in order; the rest follow in their order. No
  // event fires: it is the consumer's own call. With `useAnimation` (and a
  // non-zero `animation`) the rows slide from where they were.
  sort = (order: any, useAnimation: any = true) => {
    const list = this.items();
    const next = orderByKeys(list, order ?? [], this.keyFor);
    if (next.every((item: any, i: any) => item === list[i])) return;
    const animate = useAnimation && this.instance != null;
    if (animate) this.instance.captureAnimationState();
    this.items.set(next), this.__rozieCvaOnChange(next);
    if (animate) {
      const sortable = this.instance;
      afterFlush(() => sortable.animateAll());
    }
  };
  // option(name) reads a live SortableJS option; option(name, value) sets one — the
  // runtime escape hatch for any SortableJS option beyond the curated props.
  // Setting `disabled`, `filter`, `draggable` or `sort` also applies to the
  // keyboard; `option('disabled', true)` mid-lift ends the lift this list holds.
  // A runtime `animation` is kept over later `animation` prop changes.
  option = (name: any, value: any) => {
    if (!this.instance) return undefined;
    if (value === undefined) return this.instance.option(name);
    this.instance.option(name, value);
    if (this.TRACKED_OPTIONS.includes(name)) this.setOverride(name, value);
    if (name === 'disabled' && value) this.keyboardTurnedOff();
    // After the re-render, so every list reads the new group (React reads
    // state as of its last render).
    if (name === 'group') afterFlush(() => this.registry.notifyPeers());
    return value;
  };

  private __rozieCvaOnChange: (v: any[]) => void = () => {};
  private __rozieCvaOnTouchedFn: () => void = () => {};
  protected __rozieCvaDisabled = signal(false);

  writeValue(v: any[] | null): void {
    this.items.set(v ?? (() => [])());
  }
  registerOnChange(fn: (v: any[]) => void): void {
    this.__rozieCvaOnChange = fn;
  }
  registerOnTouched(fn: () => void): void {
    this.__rozieCvaOnTouchedFn = fn;
  }
  setDisabledState(isDisabled: boolean): void {
    this.__rozieCvaDisabled.set(isDisabled);
  }
  __rozieCvaOnTouched(): void {
    this.__rozieCvaOnTouchedFn();
  }

  static ngTemplateContextGuard(
    _dir: SortableList,
    _ctx: unknown,
  ): _ctx is HeaderCtx | DefaultCtx | FooterCtx {
    return true;
  }

  private rozieSpread_0 = viewChild<ElementRef>('rozieSpread_0');

  private __rozieApplyAttrs = createRozieAttrApplier(inject(Renderer2));

  private __rozieGetHostAttrs = createRozieHostAttrsReader(inject(ElementRef));

  private __rozieSpread_0_effect = afterRenderEffect(() => {
    const el = this.rozieSpread_0()?.nativeElement;
    if (!el) return;
    this.__rozieApplyAttrs(el, this.__rozieGetHostAttrs());
  });

  private rozieListenersTarget_1 = viewChild<ElementRef>('rozieListenersTarget_1');

  private __rozieListenersRenderer = inject(Renderer2);

  private __rozieListenersDisposers_1: Array<() => void> = [];

  private __rozieListenersDestroyRegistered_1 = false;

  private __rozieListenersEffect_1 = effect(() => {
    const el = this.rozieListenersTarget_1()?.nativeElement;
    if (!el) return;
    for (const off of this.__rozieListenersDisposers_1) off();
    this.__rozieListenersDisposers_1 = [];
    const obj: Record<string, unknown> = {};
    for (const [k, v] of Object.entries(obj)) {
      if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
      if (typeof v !== 'function') continue;
      const norm = k.startsWith('on') ? k.slice(2).toLowerCase() : k;
      const dispose = this.__rozieListenersRenderer.listen(el, norm, v as EventListener);
      this.__rozieListenersDisposers_1.push(dispose);
    }
    if (!this.__rozieListenersDestroyRegistered_1) {
      this.__rozieListenersDestroyRegistered_1 = true;
      this.__rozieDestroyRef.onDestroy(() => {
        for (const off of this.__rozieListenersDisposers_1) off();
        this.__rozieListenersDisposers_1 = [];
      });
    }
  });

  rozieDisplay(v: unknown): string { return __rozieDisplay(v); }

  rozieAttr(v: unknown): string | null { return __rozieAttr(v); }

  rozieClass(...args: unknown[]): string { return __rozieClass(...args); }
}

export default SortableList;
tsx
import type { JSX } from 'solid-js';
import { For, Show, children, createEffect, createSignal, mergeProps, on, onCleanup, onMount, splitProps, untrack } from 'solid-js';
import { __rozieInjectStyle, createControllableSignal, parseInlineStyle, rozieAttr, rozieClass, rozieDisplay } from '@rozie/runtime-solid';
import { ROW_DRAGGABLE, orderByKeys, reapplyOptions, useSortableJS } from './internal/useSortableJS';
import { afterFlush, canHop, getKeyboardRegistry, isRenderable, nextInstructionsId, rowLiftable } from './internal/keyboardRegistry';
import { announcementText, defaultInstructions, fallbackLabel } from './internal/announcements';

/** The kind of message the list speaks during keyboard reordering (a key of the `announcements` prop). */
export type AnnouncementKind = 'lifted' | 'moved' | 'movedToList' | 'dropped' | 'droppedInList' | 'atStart' | 'atEnd' | 'notSortable' | 'noListBefore' | 'noListAfter' | 'cancelledReturnedToList' | 'cancelledReturned' | 'cancelledStays' | 'cancelledRemoved' | 'liftEnded';
/** What an `announcements` function receives. */
export interface AnnouncementContext {
  /** The row's screen-reader label (`labelFor`, else `item.label`, else the row's text). */
  label: string;
  /** The item value. */
  item: unknown;
  /** The name of the list the message is about (`listLabel`, or `list 2 of 3`). */
  list: string;
  /** 1-based position of the row in `list` (kinds that have a position). */
  position?: number;
  /** How many rows `list` holds (kinds that have a position). */
  total?: number;
  /** The list the row came from (`movedToList` only). */
  fromList?: string;
}
/** The `announcements` prop: one optional function per message kind; `null` or `''` says nothing. */
export type Announcements = Partial<Record<AnnouncementKind, (ctx: AnnouncementContext) => string | null | undefined>>;
/** The payload every `start` / `end` / `reorder` / `add` / `remove` event carries, for pointer and keyboard alike. */
export interface SortablePayload {
  /** Which input made the change. */
  interaction: 'pointer' | 'keyboard';
  /** The item's data value (never an element). */
  item: unknown;
  /** The row element; null when there is none (a lost lift, a removed clone copy). */
  el: HTMLElement | null;
  /** The list element the row came from. */
  from: HTMLElement;
  /** The list element the row went to. */
  to: HTMLElement;
  /** Item-row index in `from`; -1 for `add`. */
  oldIndex: number;
  /** Item-row index in `to`; -1 for `remove` and a lost lift. */
  newIndex: number;
  /** Pointer only: the raw SortableJS event. */
  originalEvent?: unknown;
}
/** Which element drives keyboard reordering (the `keyboardTrigger` prop). */
export type SortableKeyboardTrigger = 'row' | 'handle';
/** Which arrow keys move a lifted row within the list (the `orientation` prop). */
export type SortableOrientation = 'vertical' | 'horizontal';

__rozieInjectStyle('SortableList-0af24eae', `.rozie-sortable-wrap[data-rozie-s-0af24eae] { display: block; }
.rozie-sortable-list[data-rozie-s-0af24eae] { display: block; }
.rozie-sortable-item[data-rozie-s-0af24eae] { display: block; outline: none; }
.rozie-sortable-item[data-rozie-s-0af24eae]:focus-visible { outline: 2px solid var(--rozie-sortable-list-ring, #1a73e8); outline-offset: -2px; }
.rozie-sortable-item-lifted[data-rozie-s-0af24eae] {
  background: rgba(26, 115, 232, 0.1);
  box-shadow: 0 0 0 3px var(--rozie-sortable-list-ring, #1a73e8) inset;
}
.rozie-sortable-aria-live[data-rozie-s-0af24eae] {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}`);

interface DefaultSlotCtx { item: any; index: any; instructionsId: any; }

interface SortableListProps extends Omit<import('solid-js').ComponentProps<'div'>, 'items' | 'defaultItems' | 'onItemsChange' | 'itemKey' | 'handle' | 'group' | 'animation' | 'disabled' | 'disableKeyboard' | 'keyboardTrigger' | 'options' | 'labelFor' | 'ghostClass' | 'chosenClass' | 'dragClass' | 'filter' | 'easing' | 'forceFallback' | 'swapThreshold' | 'cloneable' | 'listClass' | 'itemClass' | 'listLabel' | 'orientation' | 'pageStep' | 'keyboardInstructions' | 'announcements' | 'itemStyle' | 'onReorder' | 'onAdd' | 'onRemove' | 'onStart' | 'onEnd' | 'headerSlot' | 'children' | 'footerSlot' | 'slots' | 'ref' | 'innerHTML' | 'innerText' | 'textContent'> {
  /**
   * The bound items array. The sole `model: true` prop — two-way bind it (`r-model:items` / `v-model:items` / `bind:items` / `[(items)]`) and SortableList writes the re-ordered array back whenever a drag, cross-list move, or keyboard reorder commits, with no manual `onChange → setState` wiring.
   * @example
   * <SortableList items={todos()} onItemsChange={setTodos} itemKey="id" />
   */
  items?: any[];
  defaultItems?: any[];
  onItemsChange?: (items: any[]) => void;
  /**
   * The per-row key the framework reconciler tracks each item by across a reorder — either a property name (e.g. `itemKey="id"` reads `item.id`) or an `(item, index) => key` function. With neither, id-less object items get a stable synthetic key via an internal `WeakMap` (survives reorder by object identity); primitive items fall back to index — pass a function for reorderable duplicate primitives.
   */
  itemKey?: (string | ((...args: any[]) => any)) | null;
  /**
   * CSS selector identifying the per-row drag handle, so a drag starts only from that element rather than anywhere in the row. Authored class names render literally on every target (React included), so a plain `.grip` works; `$classSelector('grip')` is an optional, typo-checked way to author it. `options.handle` and `option('handle', v)` win over this prop, for the keyboard (`keyboardTrigger: 'handle'`) as for the mouse.
   */
  handle?: (string) | null;
  /**
   * SortableJS group name enabling cross-list drag — two lists sharing a `group` accept items between each other (the source fires `remove`, the destination fires `add`). Set `cloneable: true` to flip a string group into clone-mode. Lists that share a `group` also exchange rows by keyboard: Shift+arrow while a row is lifted hops it to the previous or next list of the same group (in source order), subject to the same pull/put rules as a mouse drag. `options.group` takes precedence over this prop, for keyboard hops as for drags. Function-valued `pull`/`put` cannot be evaluated without a drag, so those lists are unreachable by keyboard. Set `itemKey` on grouped lists.
   */
  group?: (string) | null;
  /**
   * Reorder animation duration in milliseconds. `0` disables the animation. Reapplied live via `instance.option('animation', v)` (no remount). `options.animation`, and a runtime `option('animation', v)`, win over this prop.
   */
  animation?: number;
  /**
   * Temporarily disable dragging without unmounting — reapplied live via `instance.option('disabled', v)` (no remount). Also suppresses keyboard reordering: a disabled list is not sortable by any input, so rows lose their `tabindex` and the keydown handler no-ops. Turning it on while a row is lifted ends the lift where the row is (`Lift ended`, and `end` fires); `options.disabled` and `option('disabled', v)` do the same.
   */
  disabled?: boolean;
  /**
   * Opt out of keyboard reordering (Space lift / Arrow move / Shift+Arrow hop between lists / Esc cancel / Enter drop) while leaving pointer drag enabled. Rows drop out of the tab order (no `tabindex`) and the keydown handler no-ops. Keyboard access is gated on `!disabled && !disableKeyboard`. Turning it on while a row is lifted ends the lift where the row is.
   */
  disableKeyboard?: boolean;
  /**
   * Which element drives keyboard reordering. `'row'` (default): rows are tab stops and the keys on the focused row drive reordering. `'handle'`: rows are NOT tab stops, and only keys pressed inside the element matched by `handle` (inside that row) drive the same Space/Enter lift-drop, Arrow move, Shift+Arrow hop and Escape cancel flow; handled keys call preventDefault so a handle `<button>`'s click does not fire. The consumer owns the handle markup (recommended: a `<button>` with its own aria-label such as "Reorder Hero banner") and the component adds no tabindex or role to slot content. `'handle'` without `handle` turns keyboard reordering off and logs a console warning. `disabled`/`disableKeyboard` still apply. Typed as `SortableKeyboardTrigger` (`'row' | 'handle'`); at runtime any value other than `'handle'` behaves as `'row'`.
   */
  keyboardTrigger?: SortableKeyboardTrigger;
  /**
   * Verbatim SortableJS options pass-through for anything not covered by the named props. The named props win on key conflict but `options` lands AFTER them in the merge so consumers can override defaults; handler keys (`onStart`, `onEnd`, `onUpdate`, `onAdd`, `onRemove`, `onClone`) are stripped — the helper owns those paths. Runtime-updatable: when `options` changes, each key whose value changed is reapplied via `instance.option(key, v)` (no remount), so mouse and keyboard obey the same values; a key you drop goes back to its named prop (or, for `sort` and `draggable`, the component default), and any other dropped key keeps its last value until you set it. `forceFallback` is still read only at construction.
   */
  options?: Record<string, any>;
  /**
   * Optional `(item, idx) => string` returning the screen-reader label for the aria-live announcer during keyboard drag. Defaults to `item.label`; without a `label` field, the row's text (whitespace collapsed, without nested lists or hidden content), else `String(item)` for a primitive, else `item {position}`.
   */
  labelFor?: ((...args: any[]) => any) | null;
  /**
   * Class name applied to the drop-placeholder (ghost) element while dragging. Forwarded live via `instance.option`, so toggling it at runtime takes effect without a remount.
   */
  ghostClass?: (string) | null;
  /**
   * Class name applied to the currently-chosen item while dragging. Forwarded live via `instance.option` (no remount needed to change it).
   */
  chosenClass?: (string) | null;
  /**
   * Class name applied to the dragging element. Only takes effect in fallback mode (`forceFallback: true`). Forwarded live via `instance.option`.
   */
  dragClass?: (string) | null;
  /**
   * CSS selector that prevents drag initiation on matching rows (locked items). SortableJS checks it at `mousedown`/`touchstart` and aborts the drag if it matches. The keyboard honours it too: a row that matches (the row element, or its slot root: the row template's single element when nothing else sits beside it) cannot be lifted with Space/Enter; any other matching control (a `.js-remove` button, an `input`) blocks only presses on itself. `options.filter` (which may also be a SortableJS filter function) takes precedence. A `data-*` attribute selector (e.g. `[data-locked]`) is the most robust choice across all targets.
   */
  filter?: (string) | null;
  /**
   * CSS easing function for the reorder animation (e.g. `'ease-in'`, `'cubic-bezier(0.4, 0, 0.2, 1)'`). Runtime-updatable.
   */
  easing?: (string) | null;
  /**
   * Force SortableJS's mouse-event drag path over HTML5 DnD — useful for touch devices, consistent cross-browser behavior, and synthetic test drivers (and `dragClass` only applies in this mode). **Construction-time only**: SortableJS reads it once at construction, so re-key the `<SortableList>` to toggle it at runtime.
   */
  forceFallback?: boolean;
  /**
   * SortableJS swap threshold (0..1) — a lower value makes rows swap earlier as the dragged item overlaps a neighbor. Reapplied live via `instance.option('swapThreshold', v)` — SortableJS reads it on every dragover, so no remount is needed.
   */
  swapThreshold?: number;
  /**
   * High-level prop that REPLACES a string `group` with SortableJS's `{ name, pull: 'clone', put: false }` clone-mode object form — the source deposits a COPY onto the destination and keeps its own array unchanged, and takes nothing back: no row can be dropped or keyboard-hopped into it (the palette → canvas pattern). With `group: null` it is a no-op (a clone-mode list with no group name has no peer to clone into). Reapplied live — toggling `cloneable` (or changing `group`) recomputes the clone-mode shape and reapplies it via `instance.option('group', …)`, no remount.
   */
  cloneable?: boolean;
  /**
   * Extra class(es) merged onto the list container (the SortableJS root) alongside the base `rozie-sortable-list` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding), normalized identically across all six targets — the hook for bridging a CSS framework (`.list-group`) or a flex/grid parent onto the component.
   */
  listClass?: string | any[] | Record<string, any>;
  /**
   * Extra class(es) merged onto every item row alongside the base `rozie-sortable-item` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding) applied uniformly, OR an `(item, index) => class` function for per-row classes evaluated at render time. Normalized identically across all six targets.
   */
  itemClass?: string | any[] | Record<string, any> | ((...args: any[]) => any);
  /**
   * The list's human name, such as `"Top sidebar"`. Sets `aria-label` on the list container (`role="list"`) and names the list in keyboard announcements when a row moves between lists (`Moved Hero banner to Top sidebar, position 1 of 4`, `Dropped Hero banner in Top sidebar at position 3 of 4`, `No list after Top sidebar`). Pass the same words as the zone's visible heading. With no label, announcements fall back to a neutral `list 2 of 3`, counting the mounted lists of the same group in hop (source) order.
   */
  listLabel?: (string) | null;
  /**
   * Which arrow keys move a lifted row within the list: `'vertical'` (default) uses ↑/↓, `'horizontal'` uses ←/→. A horizontal list's default spoken instructions say "Use the left and right arrow keys to move" (`role="list"` has no `aria-orientation`). Typed as `SortableOrientation` (`'vertical' | 'horizontal'`).
   */
  orientation?: SortableOrientation;
  /**
   * How many positions Page Up / Page Down move a lifted row. The move stops at the first or last position when fewer rows remain.
   */
  pageStep?: number;
  /**
   * Replaces the spoken keyboard instructions. The text sits in a hidden element referenced by `aria-describedby` from each tabbable row (row mode) or from the consumer's handle via the `instructionsId` slot prop (handle mode). Default: "Press Space or Enter to pick up, and again to drop. Use the up and down arrow keys to move, Home and End to jump to the start or end, Page Up and Page Down to move several places, and Escape to cancel." (with `orientation: 'horizontal'`, "the left and right arrow keys"; a `sort: false` list says only "Press Space or Enter to pick up, and again to drop. Press Escape to cancel."). When another mounted list could take this list's rows (by the group rules of `group`, `options.group` or `option('group', v)`), the default adds "Hold Shift with an arrow key to move to another list." (updated as lists mount, unmount or change group).
   */
  keyboardInstructions?: (string) | null;
  /**
   * Rewords or translates what the list says during keyboard reordering. An object of optional functions keyed by message kind (`lifted`, `moved`, `movedToList`, `dropped`, `droppedInList`, `atStart`, `atEnd`, `notSortable`, `noListBefore`, `noListAfter`, `cancelledReturnedToList`, `cancelledReturned`, `cancelledStays`, `cancelledRemoved`, `liftEnded`). Each receives a context (`label`, `item`, `list`, and for kinds with a position `position` (1-based) and `total`; `movedToList` also `fromList`) and returns the text to speak; `null` or `''` says nothing. Kinds without a function keep the default English text (see "Announcements"). Define the object in your script and bind it (Angular templates reject inline arrow functions), e.g. `const announcements = { moved: ({ label, position, total }) => label + ' → ' + position + '/' + total }`. Typed as `Announcements`, exported with `AnnouncementKind` and `AnnouncementContext`.
   * @example
   * <SortableList items={todos()} onItemsChange={setTodos} announcements={announcements} />
   */
  announcements?: (Announcements) | null;
  /**
   * Per-row inline style applied to the `.rozie-sortable-item` wrapper. Accepts a CSS `String`, a flat style object (`Record<string, string | number>`), or an `(item, index) => string | object` function for per-row styling. Because it lands on the wrapper — the direct child of the list container — it can drive CSS-grid placement (`grid-column` / `grid-row` / `align-self`) when `listClass` sets `display: grid`. Normalized per target; `null` / empty drops the attribute.
   */
  itemStyle?: (string | Record<string, any> | ((...args: any[]) => any)) | null;
  onReorder?: (payload: SortablePayload) => void;
  onAdd?: (payload: SortablePayload) => void;
  onRemove?: (payload: SortablePayload) => void;
  onStart?: (payload: SortablePayload) => void;
  onEnd?: (payload: SortablePayload) => void;
  headerSlot?: JSX.Element;
  // D-131: default slot resolved via children() at body top
  children?: JSX.Element | ((ctx: DefaultSlotCtx) => JSX.Element);
  footerSlot?: JSX.Element;
  slots?: Record<string, (ctx: any) => JSX.Element>;
  ref?: (h: SortableListHandle) => void;
}

export interface SortableListHandle {
  getInstance: (...args: any[]) => any;
  toArray: (...args: any[]) => any;
  sort: (...args: any[]) => any;
  option: (...args: any[]) => any;
}

export default function SortableList(_props: SortableListProps): JSX.Element {
  const _merged = mergeProps({ itemKey: null, handle: null, group: null, animation: 150, disabled: false, disableKeyboard: false, keyboardTrigger: 'row', options: (() => ({}))() as Record<string, any>, labelFor: null, ghostClass: null, chosenClass: null, dragClass: null, filter: null, easing: null, forceFallback: false, swapThreshold: 1, cloneable: false, listClass: '', itemClass: '', listLabel: null, orientation: 'vertical', pageStep: 5, keyboardInstructions: null, announcements: null, itemStyle: null }, _props);
  const [local, attrs] = splitProps(_merged, ['items', 'itemKey', 'handle', 'group', 'animation', 'disabled', 'disableKeyboard', 'keyboardTrigger', 'options', 'labelFor', 'ghostClass', 'chosenClass', 'dragClass', 'filter', 'easing', 'forceFallback', 'swapThreshold', 'cloneable', 'listClass', 'itemClass', 'listLabel', 'orientation', 'pageStep', 'keyboardInstructions', 'announcements', 'itemStyle', 'children', 'ref', 'onReorder', 'onAdd', 'onRemove', 'onStart', 'onEnd', 'headerSlot', 'footerSlot', 'slots']);
  const resolved = children(() => local.children as JSX.Element);
  onMount(() => { local.ref?.({ getInstance, toArray, sort, option }); });

  const [items, setItems] = createControllableSignal<any[]>(_props as unknown as Record<string, unknown>, 'items', (() => [])());
  const [liftedIndex, setLiftedIndex] = createSignal<any>(null);
  const [ariaLiveText, setAriaLiveText] = createSignal('');
  const [instructionsId, setInstructionsId] = createSignal<any>(null);
  const [optionOverrides, setOptionOverrides] = createSignal<Record<string, any>>({});
  const [hasHopPeer, setHasHopPeer] = createSignal(false);
  createEffect(on(() => (() => local.disabled)(), (v) => untrack(() => ((v: any) => {
    instance?.option('disabled', v);
    setOverride('disabled', v);
  })(v)), { defer: true }));
  createEffect(on(() => (() => local.animation)(), (v) => untrack(() => ((v: any) => instance?.option('animation', liveOption('animation', v)))(v)), { defer: true }));
  createEffect(on(() => (() => local.options)(), (v) => untrack(() => (() => {
    if (!instance) return;
    const next = local.options;
    const base = {
      animation: local.animation,
      disabled: local.disabled,
      group: resolveGroup() ?? null,
      handle: local.handle,
      ghostClass: local.ghostClass,
      chosenClass: local.chosenClass,
      dragClass: local.dragClass,
      filter: local.filter,
      swapThreshold: local.swapThreshold,
      easing: local.easing,
      sort: true,
      draggable: ROW_DRAGGABLE
    };
    // A fresh inline function with the same content (React re-renders) is
    // applied so SortableJS runs the newest closure, but it is no change: a
    // runtime `option(name, v)` still in force keeps winning over it.
    const applied = reapplyOptions(instance, appliedOptions, next, base, {
      keep: (key: any, prev: any) => {
        const ov: any = optionOverrides();
        return ov != null && Object.prototype.hasOwnProperty.call(ov, key) && ov[key] !== prev;
      },
      refreshed: (key: any) => {
        if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key));
      }
    });
    appliedOptions = next;
    for (const key of applied as any) {
      // The keyboard reads the value SortableJS now runs with. A remembered
      // runtime `animation` / `handle` / `group` is superseded by the newer
      // `options` value.
      if (KEYBOARD_OPTIONS.includes(key)) setOverride(key, instance.option(key));else if (TRACKED_OPTIONS.includes(key)) clearOverride(key);
    }
    if (applied.includes('group')) registry.notifyPeers();
  })()), { defer: true }));
  createEffect(on(() => (() => [local.disabled, local.disableKeyboard, local.options, optionOverrides()])(), (v) => untrack(() => (() => {
    if (!keyboardEnabled()) keyboardTurnedOff();
  })()), { defer: true }));
  createEffect(on(() => (() => local.group)(), (v) => untrack(() => (() => applyGroup())()), { defer: true }));
  createEffect(on(() => (() => local.cloneable)(), (v) => untrack(() => (() => applyGroup())()), { defer: true }));
  createEffect(on(() => (() => local.swapThreshold)(), (v) => untrack(() => ((v: any) => instance?.option('swapThreshold', v))(v)), { defer: true }));
  createEffect(on(() => (() => local.handle)(), (v) => untrack(() => ((v: any) => {
    instance?.option('handle', liveOption('handle', v));
    warnIfHandleMissing();
  })(v)), { defer: true }));
  createEffect(on(() => (() => local.keyboardTrigger)(), (v) => untrack(() => (() => warnIfHandleMissing())()), { defer: true }));
  createEffect(on(() => (() => local.ghostClass)(), (v) => untrack(() => ((v: any) => instance?.option('ghostClass', v))(v)), { defer: true }));
  createEffect(on(() => (() => local.chosenClass)(), (v) => untrack(() => ((v: any) => instance?.option('chosenClass', v))(v)), { defer: true }));
  createEffect(on(() => (() => local.dragClass)(), (v) => untrack(() => ((v: any) => instance?.option('dragClass', v))(v)), { defer: true }));
  createEffect(on(() => (() => local.filter)(), (v) => untrack(() => ((v: any) => {
    instance?.option('filter', v);
    setOverride('filter', v);
  })(v)), { defer: true }));
  createEffect(on(() => (() => local.easing)(), (v) => untrack(() => ((v: any) => instance?.option('easing', v))(v)), { defer: true }));
  createEffect(on(() => (() => items())(), (v) => untrack(() => (() => {
    const lift = registry.lift;
    if (lift == null || lift.holder !== entry) return;
    const i = registry.indexOfLift();
    if (i < 0) {
      loseLift();
      return;
    }
    if (liftedIndex() !== i) setLiftedIndex(i);
    // Once the holder has rendered the lifted row, that is the lifted row
    // element. After a hop this drops the source's old row, which the source
    // may reuse for another item (index keys).
    const row = entry.rowEl(i);
    if (row != null) lift.liftedRowEl = row;
    focusNearRow(i, lift.key);
  })()), { defer: true }));
  onMount(() => {
    const _cleanup = (() => {
    // Kept across a Lit element's disconnect and reconnect (mount runs again).
    if (instructionsId() == null) setInstructionsId(nextInstructionsId());
    warnIfHandleMissing();
    // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
    // when the options object below references it.
    const sortable = useSortableJS(listElRef!, {
      items: () => items(),
      onCommit: (next: any) => {
        setItems(next);
      },
      options: {
        animation: local.animation,
        disabled: local.disabled,
        group: resolveGroup(),
        handle: local.handle ?? undefined,
        ghostClass: local.ghostClass ?? undefined,
        chosenClass: local.chosenClass ?? undefined,
        dragClass: local.dragClass ?? undefined,
        filter: local.filter ?? undefined,
        forceFallback: local.forceFallback,
        swapThreshold: local.swapThreshold,
        easing: local.easing ?? undefined,
        ...local.options
      },
      // Lit lit-html `repeat` directive caches its part array by sentinel-
      // comment node identity; SortableJS's physical DOM mutation desyncs
      // that cache. The sigil lowers to `__rozieReconcileAfterDomMutation(this)`
      // on Lit (real call) and `void 0` on the other 5 targets (no-op).
      afterCommit: () => void 0,
      // Every pointer event carries the same payload as the keyboard ones, with
      // item-row indices and the raw SortableJS event as `originalEvent`.
      onChange: (c: any) => {
        const payload = {
          interaction: 'pointer' as const,
          item: c.item,
          el: c.el,
          from: c.from,
          to: c.to,
          oldIndex: c.oldIndex,
          newIndex: c.newIndex,
          originalEvent: c.event
        };
        if (c.kind === 'reorder') _props.onReorder?.(payload);else if (c.kind === 'add') _props.onAdd?.(payload);else if (c.kind === 'remove') _props.onRemove?.(payload);
      },
      onStart: (d: any) => {
        // A pointer drag ends any active keyboard lift first.
        if (registry.lift != null) endLift('drop');
        // That lift's `end` (pending until a task) comes before this `start`.
        registry.flushEnds();
        _props.onStart?.({
          interaction: 'pointer',
          item: d.item,
          el: d.el,
          from: d.from,
          to: d.to,
          oldIndex: d.oldIndex,
          newIndex: d.newIndex,
          originalEvent: d.event
        });
      },
      // `end` comes from the list the row ended up in: the destination when it
      // is a SortableList, else (dropped outside, or into a SortableJS list
      // that isn't one of ours) this source list. It goes through the
      // registry's `deferEnd`, like a keyboard `end`: it fires in a task after
      // every list involved has written its items and the re-render those
      // writes scheduled, and before the next drag's or lift's `start`. An
      // unmounted list never emits: if the destination has unmounted by then
      // (in its own `add` handler, say), this list (the origin, which emitted
      // `start`) emits it, `to` still the destination; if both are gone,
      // nothing is emitted.
      scheduleEnd: (d: any) => {
        const dest = registry.entryFor(d.to);
        const destGone = dest == null && d.to !== d.from && registry.wasList(d.to);
        registry.deferEnd((host: any) => {
          const row = d.item === undefined || host.el !== d.to ? null : rowByKey(d.to, host.keyOf(d.item, d.newIndex));
          host.emit('end', {
            interaction: 'pointer',
            item: d.item,
            el: row ?? liveEl(d.el),
            from: d.from,
            to: d.to,
            oldIndex: d.oldIndex,
            newIndex: d.newIndex,
            originalEvent: d.event
          });
        }, destGone ? null : dest ?? entry, entry);
      }
    });
    instance = sortable.instance;
    appliedOptions = local.options;
    // Runtime `option(name, v)` values this list remembers (Lit keeps them when
    // the element is moved in the DOM and mounts again) apply to the new
    // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
    // first mount.
    const remembered: any = optionOverrides();
    if (remembered != null) {
      for (const name of Object.keys(remembered) as any) instance.option(name, remembered[name]);
    }
    const listEl = listElRef;
    const stopNative = (ev: any) => {
      if (ev.target === listEl) ev.stopPropagation();
    };
    for (const name of SORTABLE_DOM_EVENTS as any) listEl?.addEventListener(name, stopNative);
    // A focused row that stops being focusable (its tabindex goes when the
    // keyboard turns off) is blurred at once, during the framework's DOM
    // update, with focus going nowhere (`relatedTarget` null): it would land on
    // <body>. Move it to the list instead.
    const rowBlurred = (ev: any) => {
      if (listEl == null) return;
      const row: any = ev.target;
      if (ev.relatedTarget != null || row == null || row.parentNode !== listEl) return;
      if (!row.classList.contains('rozie-sortable-item') || row.hasAttribute('tabindex') || !row.isConnected) return;
      if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
      listEl.focus();
    };
    listEl?.addEventListener('focusout', rowBlurred);
    unhookNativeEvents = () => {
      for (const name of SORTABLE_DOM_EVENTS as any) listEl?.removeEventListener(name, stopNative);
      listEl?.removeEventListener('focusout', rowBlurred);
    };

    // Register with the keyboard registry. Other instances call these methods
    // when a keyboard lift hands a row between lists.
    entry = {
      el: listEl,
      group: () => effectiveGroup(),
      label: () => local.listLabel,
      // A handle-mode list without a handle selector has its keyboard off.
      keyboardEnabled: () => keyboardEnabled() && !(handleMode() && handleSelector() == null),
      items: () => items(),
      keyOf: (item: any, i: any) => String(keyFor(item, i)),
      labelOf: (item: any, i: any, row: HTMLElement | null = null) => String(labelOf(item, i, row)),
      message: (kind: any, ctx: any) => announcementText(local.announcements ?? undefined, kind, ctx),
      onKey: (key: any, shift: any) => holderKey(key, shift),
      write: (next: any) => {
        setItems(next);
      },
      setLifted: (i: any) => {
        setLiftedIndex(i);
      },
      // The same text twice in a row would not change the region, and a screen
      // reader would not read it again ("Apple is already first", twice): a
      // repeat alternates a trailing no-break space, which is not spoken.
      announce: (text: any) => {
        const next = text !== '' && text === lastSpoken ? text + '\u00A0' : text;
        lastSpoken = next;
        setAriaLiveText(next);
      },
      focusRow: (item: any, i: any) => refocusRow(item, i),
      focusNear: (i: any) => focusNearRow(i),
      rowEl: (i: any) => {
        const list = items();
        if (i < 0 || i >= list.length) return null;
        return rowByKey(listEl, String(keyFor(list[i], i)));
      },
      // Always set (an equal value is a no-op on every target): a compare
      // against $data would read React's render-time ref, stale when two peer
      // changes land in one commit (one list unmounts, another mounts).
      peersChanged: (v: any) => {
        setHasHopPeer(v);
      },
      emit: (name: any, payload: any) => {
        if (name === 'add') _props.onAdd?.(payload);else if (name === 'remove') _props.onRemove?.(payload);else if (name === 'reorder') _props.onReorder?.(payload);else if (name === 'start') _props.onStart?.(payload);else if (name === 'end') _props.onEnd?.(payload);
      }
    };
    unregisterEntry = registry.register(entry);
    const strayKey = (ev: any) => onStrayKey(ev);
    // A pointer press means the user moved on: keys lost to <body> after it
    // are not routed to the lift.
    const pointerPress = () => {
      if (registry.lift != null) registry.lift.focusPending = false;
    };
    document.addEventListener('keydown', strayKey);
    document.addEventListener('pointerdown', pointerPress, true);
    unhookStrayKeys = () => {
      document.removeEventListener('keydown', strayKey);
      document.removeEventListener('pointerdown', pointerPress, true);
    };
    // $onMount's cleanup-return: closing over a setup-local (`sortable`) does
    // not survive the Solid emitter's setup/cleanup split — it scopes cleanup
    // outside the setup IIFE. Closing over `instance` / `unregisterEntry`
    // (module-scope `let`s) works on every target.
  })() as unknown;
    if (_cleanup) onCleanup(_cleanup as () => void);
    onCleanup(() => {
    instance?.destroy();
    // Unmounting while holding a keyboard lift ends it (its `end` comes from
    // the origin list, if that one is still mounted).
    if (registry.lift != null && registry.lift.holder === entry) loseLift(true);
    unregisterEntry?.();
    unregisterEntry = null;
    unhookNativeEvents?.();
    unhookNativeEvents = null;
    unhookStrayKeys?.();
    unhookStrayKeys = null;
  });
  });
  let listElRef: HTMLElement | null = null;

  let instance: any = null;
  // The `options` object SortableJS was last given (see the `options` watcher).
  let appliedOptions: any = null;

  // Keyboard lift state lives in the shared registry (one active keyboard lift
  // per page, so a later task can hand a lifted row between lists).
  // `$data.liftedIndex` is only its mirror, for the lifted-row styling.
  const registry = getKeyboardRegistry();
  // This list's registry entry (a ListEntry), built and registered in $onMount.
  let entry: any = null;
  let unregisterEntry: any = null;
  // Removes the listeners that keep SortableJS's own DOM events inside the list.
  let unhookNativeEvents: any = null;
  // Removes the document keydown listener that catches keys lost to <body>.
  let unhookStrayKeys: any = null;

  // SortableJS also dispatches its events as BUBBLING native DOM events
  // (`start`, `end`, `add`, `remove`, `change`, …) on the list element, before
  // it calls the option callbacks. An output binding on the component host
  // (Angular's `(start)` / `(end)` / `(add)` / `(remove)`, a Lit listener) also
  // catches a native DOM event of the same name, so a consumer would get the raw
  // SortableJS event as an extra event. The component re-emits the committed
  // events itself, so stop the raw ones at the list element (only events
  // dispatched ON the list — an `<input>`'s own `change` is untouched).
  const SORTABLE_DOM_EVENTS = ['choose', 'unchoose', 'start', 'end', 'add', 'update', 'sort', 'remove', 'filter', 'clone', 'change', 'select', 'deselect'];

  // role="list" takes no aria-orientation, so a horizontal list says which
  // arrow keys move in its instructions instead. A `sort: false` list leaves out
  // the move sentence, and a list whose rows another mounted list could take
  // (by the group SortableJS runs with, `options.group` included) says how to
  // hop.
  function instructionsText() {
    if (local.keyboardInstructions != null) return local.keyboardInstructions;
    return defaultInstructions({
      horizontal: local.orientation === 'horizontal',
      sortable: liveOption('sort', true) !== false,
      grouped: effectiveGroup() != null && hasHopPeer()
    });
  }

  // Instance-scoped synthetic-id store for id-less object items. Keyed by object
  // IDENTITY, so the same object keeps its synthetic id across a reorder (the
  // framework reconciler then rebinds the row component instance to its ORIGINAL
  // item, not its slot position — the data-corruption fix).
  //
  // Phase 73 item #11-b removed the former "fold the WeakMap + counter into ONE
  // member-mutated object const" workaround: `hoistModuleLet`'s reachability
  // walk now also roots at helpers called ONLY from a template expression
  // (`keyFor` is called from `:key`/`:data-id`, never from a hook), so the bare
  // `let __rowKeySeq = 0` below hoists to a `useRef` on React exactly like the
  // hook-reached case — no more per-render reset. Verified in codegen.
  const __rowKeyMap = new WeakMap();
  let __rowKeySeq = 0;

  // 4-tier per-row key precedence. Its return feeds BOTH :key and :data-id.
  function keyFor(item: any, index: any) {
    // (a) function itemKey: consumer-supplied (item, index) => key.
    if (typeof local.itemKey === 'function') {
      return local.itemKey(item, index);
    }
    // (b) string itemKey: a property name on a non-null object item.
    if (typeof local.itemKey === 'string' && item !== null && typeof item === 'object' && item[local.itemKey] != null) {
      return item[local.itemKey];
    }
    // (c) id-less object (or function) item: assign-on-first-sight WeakMap
    //     synthetic id. Survives reorder because it is keyed by object identity.
    if (item !== null && typeof item === 'object' || typeof item === 'function') {
      if (!__rowKeyMap.has(item)) {
        __rowKeyMap.set(item, '__rk' + __rowKeySeq++);
      }
      return __rowKeyMap.get(item);
    }
    // (d) primitive item: fall back to index. NOTE: duplicate primitives are
    //     unsafe to reorder this way — pass a function itemKey for those.
    return index;
  }

  // Resolve the SortableJS `group` option: `cloneable` is a high-level Rozie
  // prop that REPLACES a string `group` with SortableJS's
  // `{ name, pull: 'clone', put: false }` clone-mode object form (a palette
  // takes nothing back, by mouse or keyboard). When
  // `cloneable:false`, pass `$props.group` through verbatim. When
  // `cloneable:true` AND `$props.group` is null, leave it null — a clone-mode
  // list without a group name is not meaningful (no peer list can join the
  // cross-list flow). Shared by $onMount construction AND the group/cloneable
  // $watch reconcile below — single source of truth, no duplicated ternary.
  function resolveGroup() {
    return local.cloneable && typeof local.group === 'string' ? {
      name: local.group,
      pull: 'clone' as const,
      put: false as const
    } : local.group ?? undefined;
  }

  // The group SortableJS actually runs with: a runtime `option('group', v)`,
  // else `options.group` (it lands after the named props in the merge), else
  // the `group` / `cloneable` props. Keyboard hops follow the same rules as the
  // mouse, so they read this one.
  function effectiveGroup() {
    const ov: any = optionOverrides();
    if (ov != null && Object.prototype.hasOwnProperty.call(ov, 'group')) return ov.group;
    const o: any = local.options;
    return o != null && o.group != null ? o.group : resolveGroup();
  }

  // Resolve itemClass for a row: a static value (string | array | object) OR a
  // per-row (item, index) => class function. The result is fed into the :class
  // array and normalized by each target's class path (rozieClass / clsx / native).
  function itemClassFor(item: any, index: any) {
    const v = local.itemClass;
    return typeof v === 'function' ? v(item, index) : v;
  }

  // Resolve itemStyle for a row: a static value (string | object) OR a per-row
  // (item, index) => style function. Returns string | object | null; the dynamic
  // :style binding normalizes it per target. null / empty → attribute dropped.
  function itemStyleFor(item: any, index: any) {
    const s = typeof local.itemStyle === 'function' ? local.itemStyle(item, index) : local.itemStyle;
    return s == null || s === '' ? null : s;
  }

  // Read the display label for an item — used by the aria-live announcer.
  // Phase 16 R7 / D-08: $props.labelFor reads as `null` on all 6 targets when
  // the consumer omits it (Plan 16-01 prop-default coercion fix); the check is
  // a plain null compare — NO runtime callable-type coercion. Without
  // `labelFor` or a `label` field, the row's text (`row`), else `String(item)`
  // for a primitive, else `item {position}`.
  function labelOf(item: any, idx: any, row: HTMLElement | null = null) {
    if (local.labelFor !== null) return local.labelFor(item, idx);
    if (item !== null && typeof item === 'object' && item.label != null) return item.label;
    return fallbackLabel(item, idx, row);
  }

  // The text this list's live region showed last (see the registry entry's
  // `announce`).
  let lastSpoken = '';

  // Keyboard handler (Phase 16 R7): Space/Enter lift and drop; while lifted,
  // ArrowUp/ArrowDown (ArrowLeft/ArrowRight when horizontal), Home/End and
  // PageUp/PageDown move the row, and Escape returns it to where it was lifted
  // from. The lift itself lives in the shared keyboard registry. After
  // any array-reorder write, refocusRow() keeps focus on the moved row (or its
  // handle) on all six targets.
  //
  // Note: `index` is passed directly as a number. Plan 16-02 (Solid call-arg
  // accessor unwrap) ensures Solid's <For> alias unwraps to `index()` at the
  // call site — no runtime callable-type coercion needed in user source.
  // Keyboard reordering is available only when the list is not disabled AND the
  // `disableKeyboard` opt-out is off. Drives BOTH the row tabindex (rows are
  // focusable only when reorderable) and the onRowKeyDown guard below. Reads
  // straight off $props so the tabindex binding re-evaluates reactively when
  // `disabled`/`disableKeyboard` toggle at runtime.
  //
  // The keyboard follows the SortableJS options the mouse obeys: `disabled`
  // (the prop, `options.disabled`, or `option('disabled', v)`), `filter` and
  // `draggable` (which rows lift, see rowLiftable) and `sort: false` (no moves
  // within the list). `liveOption` reads the value SortableJS runs with: one set
  // at runtime, else `options`, else the named prop.
  const KEYBOARD_OPTIONS = ['disabled', 'filter', 'draggable', 'sort'];
  function liveOption(name: any, fallback: any) {
    const ov: any = optionOverrides();
    if (ov != null && Object.prototype.hasOwnProperty.call(ov, name)) return ov[name];
    const o: any = local.options;
    if (o != null && o[name] !== undefined) return o[name];
    return fallback;
  }
  function setOverride(name: any, value: any) {
    setOptionOverrides({
      ...optionOverrides(),
      [name]: value
    });
  }
  function clearOverride(name: any) {
    const ov: any = optionOverrides();
    if (ov == null || !Object.prototype.hasOwnProperty.call(ov, name)) return;
    const next = {
      ...ov
    };
    delete next[name];
    setOptionOverrides(next);
  }
  // Options whose runtime value (`option(name, v)`) is remembered, so a later
  // change of the matching prop doesn't overwrite it: the keyboard ones, plus
  // `animation`, `handle` and `group` (runtime override → `options` → prop).
  const TRACKED_OPTIONS = [...KEYBOARD_OPTIONS, 'animation', 'handle', 'group'];
  function keyboardEnabled() {
    return !local.disableKeyboard && !liveOption('disabled', local.disabled);
  }
  // The handle selector SortableJS runs with (`option('handle', v)`, else
  // `options.handle`, else the `handle` prop): the keyboard reads the same one.
  function handleSelector() {
    return liveOption('handle', local.handle);
  }

  // keyboardTrigger='handle' mode: rows are not tab stops and the keys are read
  // from the consumer's handle element instead. Any other value is 'row' mode.
  function handleMode() {
    return local.keyboardTrigger === 'handle';
  }
  // Rows are tab stops only in row mode (and only while keyboard is enabled).
  function rowTabbable() {
    return keyboardEnabled() && !handleMode();
  }

  // One-time-per-change dev warning: handle mode needs a handle selector. Without
  // one the keyboard is OFF (see the onRowKeyDown gate) — never a silent fallback
  // to row mode, which would re-introduce the tab stops the consumer opted out of.
  function warnIfHandleMissing() {
    if (handleMode() && handleSelector() == null) {
      console.warn('[rozie-sortable-list] keyboardTrigger is "handle" but no handle selector is set, so keyboard reordering is off. Pass a handle selector (e.g. handle=".grip") or use keyboardTrigger "row".');
    }
  }

  // True only when a keydown originated inside a `handle` element that belongs to
  // THIS row. Walks the COMPOSED ancestor chain from the event target up to (but
  // excluding) the row (currentTarget): assignedSlot -> parentNode -> shadow host.
  // Plain closest()/contains() stop at a shadow boundary, and Lit renders a Rozie
  // consumer's slot content inside the SortableList shadow root while plain-HTML
  // consumers project light-DOM nodes through a <slot>. composedPath() is not
  // used because React's synthetic event does not expose it. Another
  // .rozie-sortable-item met first means the key came from a NESTED list's row,
  // which must not reorder this (outer) list.
  function isHandleKeyOrigin($event: any) {
    const sel = handleSelector();
    if (sel == null) return false;
    const row = $event.currentTarget;
    let n: any = $event.target;
    while (n && n !== row) {
      if (n.nodeType === 1) {
        if (n.matches(sel)) {
          // Matched a handle: it counts only if this row is reachable from here
          // without crossing a different sortable item.
          let m: any = n.assignedSlot ?? n.parentNode ?? n.host;
          while (m && m !== row) {
            if (m.nodeType === 1 && m.classList.contains('rozie-sortable-item')) return false;
            m = m.assignedSlot ?? m.parentNode ?? m.host;
          }
          return m === row;
        }
        if (n.classList.contains('rozie-sortable-item')) return false;
      }
      n = n.assignedSlot ?? n.parentNode ?? n.host;
    }
    return false;
  }

  // Put focus back on the MOVED row (row mode) or its handle (handle mode) after
  // a reorder write. Looks the row up by KEY (data-id), not by index, so it finds
  // the moved row whether this runs before the framework commit (the row element
  // is the same one) or after it (Svelte/Solid/Lit re-create the DOM) — and it is
  // correct for index-keyed primitive lists too. Direct children of the list
  // container only: that skips nested-list rows and the header/footer slot
  // content.
  //
  // Two passes. (1) A microtask covers targets that commit synchronously or in an
  // earlier microtask (Vue's scheduler flush is queued by the model write, before
  // this one). (2) A timer + rAF "heal" pass covers targets whose DOM commit is
  // scheduled AFTER the key handler returns (Angular): the commit can MOVE the
  // focused row, and moving a focused node blurs it, so a Home/End/Escape jump or
  // a rapid Space/Arrow/Arrow/Space burst would otherwise end with focus on
  // <body>. The heal pass never steals: it acts only when focus has been lost to
  // <body>. (`$restoreFocus(selector, index)` is not enough here: it is a no-op on
  // Vue/Angular, where a long jump moves the focused row itself, and it looks the
  // row up by index, which can land on a neighbour on Lit.) The $refs read
  // happens here, synchronously, inside an event handler — which is safe.
  function refocusRow(item: any, idx: any) {
    const listEl = listElRef;
    const sel = handleSelector();
    const useHandle = handleMode();
    const key = String(keyFor(item, idx));
    // While this refocus is outstanding, a key that falls to <body> belongs to
    // the lift (see onStrayKey). Cleared once the row has focus again, or by a
    // pointer press anywhere.
    const pending = registry.lift;
    if (pending != null) pending.focusPending = true;
    const focusIt = (onlyIfLost: any) => {
      if (!listEl) return;
      if (useHandle && sel == null) return;
      if (onlyIfLost && document.activeElement && document.activeElement !== document.body) return;
      for (const row of Array.from(listEl.children) as any[]) {
        if (row.getAttribute('data-id') === key) {
          const target = useHandle ? row.querySelector(sel) : row;
          if (target && typeof target.focus === 'function') {
            target.focus();
            const l = registry.lift;
            if (l != null && l === pending && l.key === key) {
              l.focusPending = false;
              // This row is the lifted row element now (see the items watcher).
              l.liftedRowEl = row;
            }
          }
          return;
        }
      }
    };
    queueMicrotask(() => focusIt(false));
    setTimeout(() => focusIt(true), 0);
    if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => focusIt(true));
  }

  // `el` in an event payload: the row element while it is in the page, else
  // null (a row that left with an unmounted list is no row of any list).
  function liveEl(el: any) {
    return el != null && el.isConnected ? el : null;
  }

  // The row element carrying `data-id === key` among a list element's direct
  // children (skips nested-list rows and header/footer slot content).
  function rowByKey(listEl: any, key: any) {
    if (!listEl || key == null) return null;
    for (const row of Array.from(listEl.children) as any[]) {
      if (row.getAttribute('data-id') === key) return row;
    }
    return null;
  }

  // After the consumer changed the items of the list holding a lift, put focus
  // on the row (or its handle) whose key is `key`, else the row nearest `index`
  // (or the list itself when it has no rows left) — but only once focus has fallen to <body> (the focused row's element went
  // away: the lift was lost, or a framework that keys rows by object identity
  // re-created the lifted row). Never steals focus from anywhere else. Same
  // three passes as refocusRow, for targets that commit late.
  function focusNearRow(index: number, key: string | null = null) {
    const listEl = listElRef;
    const sel = handleSelector();
    const useHandle = handleMode();
    const focusIt = () => {
      if (!listEl) return;
      if (useHandle && sel == null) return;
      if (document.activeElement && document.activeElement !== document.body) return;
      const rows = Array.from(listEl.children).filter((r: any) => r.hasAttribute('data-id') && r.classList.contains('rozie-sortable-item')) as any[];
      if (rows.length === 0) {
        // The list is now empty: focus the list itself (out of the tab order)
        // so keyboard and screen-reader users stay where they were.
        if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
        listEl.focus();
        return;
      }
      const row = rows.find((r: any) => key != null && r.getAttribute('data-id') === key) ?? rows[Math.max(0, Math.min(rows.length - 1, index))];
      const target = useHandle ? row.querySelector(sel) : row;
      if (target && typeof target.focus === 'function') target.focus();
    };
    queueMicrotask(focusIt);
    setTimeout(focusIt, 0);
    if (typeof requestAnimationFrame === 'function') requestAnimationFrame(focusIt);
  }

  // Speak `text` from `target`'s aria-live region. The region that spoke last
  // is cleared when it belongs to another list, so a message is heard once, from
  // the list the row is in now, and never from a list that just lost it.
  function speak(target: any, text: any) {
    const prev = registry.speaker;
    if (prev != null && prev !== target && registry.has(prev)) prev.announce('');
    registry.speaker = target;
    target.announce(text);
  }

  // Say announcement `kind` from `target`, in `target`'s words: its
  // `announcements` function for that kind, else the default text (see
  // ./internal/announcements). `index` is the row's 0-based position in
  // `target`, `row` the row element its label is read from (when there is no
  // `labelFor` or `label` field), and `total` how many rows `target` holds after
  // the change (null for the kinds without a position). A function returning
  // null or '' clears the region, so nothing is said.
  function say(target: any, kind: AnnouncementKind, item: unknown, index: number, row: HTMLElement | null, total: number | null = null, fromList: any = null) {
    const ctx: any = {
      item,
      list: registry.listName(target)
    };
    // The label is read only when the text needs it (a default with `{label}`,
    // or an override that reads `label`), so `labelFor` is not called for a
    // message that doesn't name the row (`Lift ended`: the item has left).
    let label: string | null = null;
    Object.defineProperty(ctx, 'label', {
      enumerable: true,
      get: () => {
        if (label === null) label = target.labelOf(item, index, row);
        return label;
      }
    });
    if (total != null) {
      ctx.position = index + 1;
      ctx.total = total;
    }
    if (fromList != null) ctx.fromList = registry.listName(fromList);
    speak(target, target.message(kind, ctx));
  }

  // The lifted item is no longer in the list holding it: the consumer changed
  // that list's items (or re-keyed the item), or the list is unmounting. End the
  // lift without writing anything (the item is wherever the consumer's data put
  // it). `end` still fires once, with `item` = the lifted value and `el: null`
  // (there is no row), so keyboard `start` / `end` pair (unless the holder and the origin have both unmounted). Lost to a consumer change (not an
  // unmount), the holder says `Lift ended` and, if focus fell to <body> with the
  // row, focuses its row nearest where the lifted row was.
  function loseLift(unmounting = false) {
    const lift = registry.lift;
    if (!lift) return;
    const h = lift.holder;
    registry.lift = null;
    h.setLifted(null);
    if (!unmounting) {
      say(h, 'liftEnded', lift.item, lift.index ?? lift.origin.index, lift.liftedRowEl);
      h.focusNear(lift.index ?? lift.origin.index);
    }
    const payload = {
      interaction: 'keyboard' as const,
      item: lift.item,
      el: null,
      from: lift.origin.list.el,
      to: h.el,
      oldIndex: lift.origin.index,
      newIndex: -1
    };
    // Like every `end`, in a task after the writes, from the holder. An
    // unmounted list never emits (Angular rejects an emit from a destroyed
    // component): when the holder is unmounting, the origin list (which emitted
    // `start`) ends the lift if it is still mounted, so `start` and `end` pair;
    // if it is gone too, nothing is emitted.
    registry.deferEnd((host: any) => host.emit('end', payload), h, lift.origin.list);
  }

  // Keyboard `start` / `end` (the same payload as every other event): `item` is
  // the item value, `el` its row element. `start` fires from the origin list
  // (`from`), `end` from the list the row ends up in (`to`). `el` is the row in
  // that list when it is rendered, else `fallbackEl` (the row element the move
  // started from, before a target re-rendered). `end` is called after
  // `registry.lift` is cleared, so a consumer `end` handler that writes the
  // items (re-keying a clone copy) is not mistaken for a lost lift, and it is
  // emitted in a task (`registry.deferEnd`), after the writes AND the re-render
  // they schedule: a consumer `end` handler reads the new state on every target
  // (React included, whose handler closure is the one from the latest render).
  // If `to` has unmounted by then, `from` (the origin, which emitted `start`)
  // emits it instead, `to` unchanged in the payload; an unmounted list never
  // emits.
  function keyboardStartEnd(name: any, lift: any, from: any, to: any, oldIndex: any, newIndex: any, fallbackEl: HTMLElement | null = null) {
    const fire = (host: any) => host.emit(name, {
      interaction: 'keyboard',
      item: lift ? lift.item : null,
      el: (lift && host === to ? rowByKey(host.el, lift.key) : null) ?? liveEl(fallbackEl),
      from: from.el,
      to: to.el,
      oldIndex,
      newIndex
    });
    if (name === 'end') registry.deferEnd(fire, to, from);else fire(from);
  }

  // Move the lifted row to `toIndex` (clamped) within the list holding it.
  // Works through the registry entry, so it acts on the current holder. `dir`
  // is the key's direction (-1 toward the start), for when the row can't move.
  function moveLiftTo(toIndex: any, dir: any) {
    const lift = registry.lift;
    if (!lift) return;
    const h = lift.holder;
    const from = registry.indexOfLift();
    if (from < 0) {
      loseLift();
      return;
    }
    const items = h.items();
    const to = Math.max(0, Math.min(items.length - 1, toIndex));
    // The moved row's element, read before the write (an index key changes).
    const el = h.rowEl(from);
    if (to === from) {
      // Nowhere to go: say so (the row is already at that end).
      say(h, dir < 0 ? 'atStart' : 'atEnd', items[from], from, el ?? lift.liftedRowEl, items.length);
      return;
    }
    const next = [...items];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    // Index keys (primitive items without itemKey) change with the position.
    // Update the lift BEFORE writing: a target whose watchers run synchronously
    // on the write must already see where the row is going.
    lift.key = h.keyOf(moved, to);
    lift.index = to;
    h.write(next);
    h.setLifted(to);
    // Name the row that MOVED from the local `moved` item: on React/Vue/Lit the
    // items prop still holds the pre-write array here. Labels come from the
    // holder's own `labelFor`.
    say(h, 'moved', moved, to, el, items.length);
    h.focusRow(moved, to);
    h.emit('reorder', {
      interaction: 'keyboard',
      item: moved,
      el,
      from: h.el,
      to: h.el,
      oldIndex: from,
      newIndex: to
    });
  }

  // Hop the lifted row to the next (`dir` 1) or previous (-1) list it could
  // also reach by mouse, in composed-tree source order. One hand-off: the source
  // writes its items without the row, the destination writes them with it, and
  // the destination becomes the holder. As with the mouse, the destination
  // emits `add` first, then the source emits `remove`. A forward hop lands
  // first, a backward hop lands last.
  function hop(dir: any) {
    const lift = registry.lift;
    if (!lift) return;
    const from = lift.holder;
    const i = registry.indexOfLift();
    if (i < 0) {
      loseLift();
      return;
    }
    const fromItems = from.items();
    const data = fromItems[i];
    const el = from.rowEl(i);
    // Keep the lifted row element current: lists nested inside it (a grid
    // widget's columns) are never hop targets. Before a target re-renders the
    // row may not exist yet, so keep the last known element then.
    lift.liftedRowEl = el ?? lift.liftedRowEl;
    const to = registry.findHopTarget(from, dir);
    if (to == null) {
      say(from, dir === 1 ? 'noListAfter' : 'noListBefore', data, i, el ?? lift.liftedRowEl);
      return;
    }
    const origin = lift.origin;
    const toItems = to.items();
    // A clone copy hopping back into the list it was cloned from merges with
    // its original there (that list never gave it up), rather than adding a
    // second row with the same key.
    if (lift.copy && to === origin.list) {
      let home = toItems.indexOf(data);
      if (home < 0) home = Math.max(0, Math.min(toItems.length - 1, origin.index));
      lift.holder = to;
      lift.copy = false;
      lift.key = to.keyOf(toItems[home], home);
      lift.item = toItems[home];
      lift.index = home;
      const rest = [...fromItems];
      rest.splice(i, 1);
      from.write(rest);
      from.emit('remove', {
        interaction: 'keyboard',
        item: data,
        el,
        from: from.el,
        to: to.el,
        oldIndex: i,
        newIndex: -1
      });
      from.setLifted(null);
      to.setLifted(home);
      say(to, 'movedToList', data, home, el, toItems.length, from);
      to.focusRow(toItems[home], home);
      return;
    }
    // The first hop out of a clone source (`pull: 'clone'`) leaves the source
    // untouched and carries a copy (the same item value the mouse path
    // inserts); from then on the copy moves like any row.
    const cloneOut = canHop(from.group(), to.group()).copy && from === origin.list && !lift.copy;
    const at = dir === 1 ? 0 : toItems.length;
    // Update the lift BEFORE writing, so a target whose watchers run
    // synchronously on a write already sees the new holder.
    lift.holder = to;
    lift.key = to.keyOf(data, at);
    lift.index = at;
    lift.hopped = true;
    if (cloneOut) {
      lift.copy = true;
    } else {
      const rest = [...fromItems];
      rest.splice(i, 1);
      from.write(rest);
    }
    const next = [...toItems];
    next.splice(at, 0, data);
    to.write(next);
    // The destination has not rendered its new row yet: `el` is the row the
    // move started from. `add` (destination) before `remove` (source), as by
    // mouse.
    to.emit('add', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: -1,
      newIndex: at
    });
    if (!cloneOut) from.emit('remove', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: i,
      newIndex: -1
    });
    from.setLifted(null);
    to.setLifted(at);
    say(to, 'movedToList', data, at, el, toItems.length + 1, from);
    to.focusRow(data, at);
  }

  // End the active keyboard lift. 'drop' leaves the row where it is ('off' too,
  // announced as `Lift ended`: the holder's keyboard was turned off); 'cancel'
  // returns it to the list and position it was lifted from (after hops, a
  // reverse hand-off with its own `remove` / `add`; a clone copy is removed).
  // Emits `end` once, from the list the row ends up in.
  function endLift(kind: any) {
    const lift = registry.lift;
    if (!lift) return;
    const h = lift.holder;
    const origin = lift.origin;
    const at = registry.indexOfLift();
    if (at < 0) {
      loseLift();
      return;
    }
    const items = h.items();
    const item = items[at];
    // The lifted row's element, read before any write below. Right after a hop
    // the holder may not have rendered it yet: its label is read from the
    // lifted row element then.
    const el = h.rowEl(at);
    const row = el ?? lift.liftedRowEl;
    if (kind === 'drop' || kind === 'off') {
      // A row that hopped always names its list, even back in its origin. The
      // keyboard turned off mid-lift ('off') ends it where it is, too.
      if (kind === 'off') say(h, 'liftEnded', item, at, row);else say(h, lift.hopped ? 'droppedInList' : 'dropped', item, at, row, items.length);
      h.setLifted(null);
      registry.lift = null;
      keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
      return;
    }
    if (h !== origin.list && !registry.has(origin.list) && lift.copy) {
      // A clone copy is removed on cancel even when its source list has
      // unmounted (the source never gave its item up). Focus moves to the
      // neighbouring row, if any. The lift ends BEFORE the write: the copy is
      // leaving on purpose, and a target whose items watcher runs synchronously
      // on the write (Solid) must not take it for a lost lift (a second `end`).
      registry.lift = null;
      const rest = [...items];
      rest.splice(at, 1);
      h.write(rest);
      h.emit('remove', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: h.el,
        oldIndex: at,
        newIndex: -1
      });
      h.setLifted(null);
      say(h, 'cancelledRemoved', item, at, row);
      if (rest.length > 0) {
        const k = Math.min(at, rest.length - 1);
        h.focusRow(rest[k], k);
      }
      // The copy is gone, so there is no row: `el: null`.
      const fromEl = origin.list.el;
      registry.deferEnd((host: any) => host.emit('end', {
        interaction: 'keyboard',
        item,
        el: null,
        from: fromEl,
        to: h.el,
        oldIndex: origin.index,
        newIndex: -1
      }), h, origin.list);
      return;
    }
    if (h !== origin.list && (!registry.has(origin.list) || !isRenderable(origin.list.el) || !origin.list.keyboardEnabled())) {
      // The origin list has unmounted, is hidden, or has its keyboard off:
      // there is nowhere to return to (focus would be stranded), so the row
      // stays where it is (the lift ends as a drop at its position).
      say(h, 'cancelledStays', item, at, row, items.length);
      h.setLifted(null);
      registry.lift = null;
      keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
      return;
    }
    if (h === origin.list) {
      const to = Math.max(0, Math.min(items.length - 1, origin.index));
      if (to !== at) {
        const next = [...items];
        next.splice(at, 1);
        next.splice(to, 0, item);
        lift.key = h.keyOf(item, to);
        h.write(next);
        h.focusRow(item, to);
        h.emit('reorder', {
          interaction: 'keyboard',
          item,
          el,
          from: h.el,
          to: h.el,
          oldIndex: at,
          newIndex: to
        });
      }
      say(h, lift.hopped ? 'cancelledReturnedToList' : 'cancelledReturned', item, to, row, items.length);
      h.setLifted(null);
      registry.lift = null;
      keyboardStartEnd('end', lift, origin.list, h, origin.index, to, el);
      return;
    }
    // Reverse hand-off from the current holder back to the origin list.
    const home = origin.list;
    const homeItems = home.items();
    let back;
    if (lift.copy) {
      // The clone source never gave its item up: drop the copy, focus the
      // original.
      back = homeItems.indexOf(item);
      if (back < 0) back = Math.max(0, Math.min(homeItems.length - 1, origin.index));
    } else {
      back = Math.min(origin.index, homeItems.length);
    }
    lift.holder = home;
    lift.key = home.keyOf(item, back);
    const rest = [...items];
    rest.splice(at, 1);
    h.write(rest);
    if (!lift.copy) {
      const next = [...homeItems];
      next.splice(back, 0, item);
      home.write(next);
      // `add` (destination) before `remove` (source), as by mouse.
      home.emit('add', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: home.el,
        oldIndex: -1,
        newIndex: back
      });
    }
    h.emit('remove', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: home.el,
      oldIndex: at,
      newIndex: -1
    });
    h.setLifted(null);
    // `home` holds the lift during its write, so a target whose items watcher
    // runs synchronously on the write (Solid) highlighted the row there: clear it.
    home.setLifted(null);
    say(home, 'cancelledReturnedToList', item, back, row, homeItems.length + (lift.copy ? 0 : 1));
    home.focusRow(lift.copy ? homeItems[back] : item, back);
    registry.lift = null;
    keyboardStartEnd('end', lift, home, home, origin.index, back, lift.copy ? home.rowEl(back) : el);
  }

  // This list's keyboard was turned off (`disabled`, `disableKeyboard`, or
  // `option('disabled', true)`): a lift it holds ends where the row is, with
  // its `end`.
  function endLiftIfHeld() {
    const lift = registry.lift;
    if (lift != null && lift.holder === entry) endLift('off');
  }

  // In row mode the rows leave the tab order when the keyboard turns off, and a
  // focused element that stops being focusable drops focus to <body>. If one of
  // this list's rows still has focus (a target whose watcher runs before its DOM
  // update), move it to the list itself (out of the tab order), like an emptied
  // list. Once the DOM update has run, the `focusout` listener added in $onMount
  // does it instead.
  function keepFocusOffBody() {
    const listEl = entry ? entry.el : null;
    if (!listEl) return;
    const root: any = listEl.getRootNode();
    const a: any = root != null ? root.activeElement : null;
    if (a == null || a.parentNode !== listEl || !a.classList.contains('rozie-sortable-item')) return;
    if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
    listEl.focus();
  }
  function keyboardTurnedOff() {
    endLiftIfHeld();
    keepFocusOffBody();
  }

  // Lift the row at `index` of this list.
  function startLift(index: any) {
    if (!entry) return;
    // A previous drag's or lift's `end` that is still pending fires first, so
    // every `end` comes before the next `start`.
    registry.flushEnds();
    const item = items()[index];
    registry.lift = {
      holder: entry,
      key: entry.keyOf(item, index),
      item,
      copy: false,
      hopped: false,
      origin: {
        list: entry,
        index
      },
      liftedRowEl: entry.rowEl(index),
      index
    };
    setLiftedIndex(index);
    say(entry, 'lifted', item, index, registry.lift.liftedRowEl, items().length);
    keyboardStartEnd('start', registry.lift, entry, entry, index, index);
  }
  function onRowKeyDown($event: any, index: any) {
    // Origin guard — must run FIRST, before the keyboardEnabled() check.
    //  - handle mode (keyboardTrigger='handle'): reorder keys apply ONLY when the
    //    keydown came from inside this row's `handle` element. A missing `handle`
    //    selector means keyboard is OFF (warned in warnIfHandleMissing).
    //  - row mode (quick 260716-ggq): reorder keys apply ONLY when the row
    //    element ITSELF is focused. A slotted interactive child (an <input>,
    //    <button>, etc. rendered into the row's default slot) bubbles its own
    //    keydown up to this handler — without this guard, Space/Enter typed into
    //    that child would be hijacked for lift/drop instead of reaching the
    //    child.
    if (handleMode()) {
      if (handleSelector() == null || !isHandleKeyOrigin($event)) return;
    } else if ($event.target !== $event.currentTarget) {
      return;
    }
    // Defense-in-depth: when keyboard reordering is off the rows carry no
    // tabindex and can't receive focus, but a consumer-focused row (or a
    // programmatic .focus()) must still no-op here rather than reorder.
    if (!keyboardEnabled()) return;
    // While a lift exists, reorder keys in the list holding it act on it. A key
    // from ANOTHER list of the holder's group is routed to the holder only when
    // it comes from the lifted row element itself (its old row, still there
    // before the frameworks re-render after a hop; compared by element, so a
    // row of another list that shares the lifted row's key is not it) or while a refocus after a move is
    // outstanding (a fast burst). Any other row — and every row of an unrelated
    // list (another group, or none) — keeps single-list behaviour: Space/Enter
    // there drops the foreign lift and lifts its own row, other keys do nothing.
    const lift = registry.lift;
    const key = $event.key;
    if (lift != null) {
      const mine = groupNameOf(effectiveGroup());
      const sameGroup = mine != null && mine === groupNameOf(lift.holder.group());
      const fromLiftedRow = lift.liftedRowEl != null && $event.currentTarget === lift.liftedRowEl;
      if (lift.holder === entry || sameGroup && (fromLiftedRow || lift.focusPending === true)) {
        if (lift.holder.onKey(key, !!$event.shiftKey)) $event.preventDefault();
        return;
      }
    }
    // Space (' ' on browsers; KeyboardEvent.key === ' ') OR Enter — lift. A row
    // the mouse can't drag (it matches `filter`, or not `draggable`) can't be
    // lifted either: the key is left alone (not prevented).
    if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
      const rules = {
        filter: liveOption('filter', local.filter),
        draggable: liveOption('draggable', undefined),
        sortable: instance
      };
      if (!rowLiftable($event.currentTarget as any, rules)) return;
      $event.preventDefault();
      if (lift != null) endLift('drop');
      startLift(index);
    }
  }

  // The group NAME of a SortableJS group option (string or object form).
  function groupNameOf(g: any) {
    return g == null ? null : typeof g === 'string' ? g : g.name ?? null;
  }

  // A reorder key for the lift THIS list holds (routed here from any list via
  // the registry entry's onKey). Returns true when the key was handled. Every
  // key except Space/Enter acts only while lifted, so it never steals keys from
  // fields inside a row.
  function holderKey(key: any, shift: any) {
    const lift = registry.lift;
    if (lift == null || lift.holder !== entry) return false;
    if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
      endLift('drop');
      return true;
    }
    if (key === 'Escape') {
      endLift('cancel');
      return true;
    }
    const horizontal = local.orientation === 'horizontal';
    const prevKey = horizontal ? 'ArrowLeft' : 'ArrowUp';
    const nextKey = horizontal ? 'ArrowRight' : 'ArrowDown';
    if (shift && (key === nextKey || key === prevKey)) {
      // Hopping is on wherever a group is set; an ungrouped list ignores it.
      if (effectiveGroup() == null) return false;
      hop(key === nextKey ? 1 : -1);
      return true;
    }
    const from = registry.indexOfLift();
    if (from < 0) {
      loseLift();
      return false;
    }
    // pageStep below 1 (or not a number) still moves by at least one position.
    const step = Math.max(1, Math.floor(Number(local.pageStep) || 1));
    let to: any = null;
    if (key === nextKey) to = from + 1;else if (key === prevKey) to = from - 1;else if (key === 'Home') to = 0;else if (key === 'End') to = entry.items().length - 1;else if (key === 'PageDown') to = from + step;else if (key === 'PageUp') to = from - step;
    if (to === null) return false;
    // `sort: false`: no moves within the list (as by mouse). The key is still
    // taken, so it does not scroll the page while a row is lifted, and says why
    // nothing moved.
    if (liveOption('sort', true) === false) {
      say(entry, 'notSortable', entry.items()[from], from, entry.rowEl(from) ?? lift.liftedRowEl);
      return true;
    }
    moveLiftTo(to, key === prevKey || key === 'Home' || key === 'PageUp' ? -1 : 1);
    return true;
  }

  // A key pressed while focus has fallen to <body> during a lift. A hop removes
  // the focused row from one list and the destination may render (and take
  // focus) only after the handler returns (Angular), so the next key of a fast
  // burst can reach <body>. The list holding the lift handles it as if it had
  // landed on the lifted row, then puts focus back on that row.
  //
  // Only while a refocus of ours is outstanding (`focusPending`): focus that left
  // the lifted row for any other reason (the user clicked elsewhere or tabbed
  // away) keeps today's behaviour, and those keys are not ours. Modified keys
  // and keys someone already handled are never taken.
  function onStrayKey(ev: any) {
    const lift = registry.lift;
    if (lift == null || lift.holder !== entry || !lift.focusPending) return;
    if (ev.defaultPrevented || ev.ctrlKey || ev.metaKey || ev.altKey) return;
    const t = ev.target;
    if (t !== document.body && t !== document.documentElement) return;
    const item = lift.item;
    const at = registry.indexOfLift();
    if (!holderKey(ev.key, !!ev.shiftKey)) return;
    ev.preventDefault();
    const now = registry.lift;
    if (now != null) now.holder.focusRow(now.item, registry.indexOfLift());else if (at >= 0) entry.focusRow(item, at);
  }

  // SortableJS wiring lives in `useSortableJS()` (./internal/useSortableJS).
  // The helper owns the SortableJS-vs-reconciler dance — DOM-restore hardening
  // against fragile-event paths, identity-based item lookup over fragile
  // `e.oldIndex`, and the single-onEnd disambiguation that collapses
  // onUpdate / onAdd / onRemove into one handler.
  //
  // What stays here is purely declarative: which array to read, what to write
  // back, what to emit, and how to bridge `afterCommit` to the Lit-only
  // `$reconcileAfterDomMutation()` sigil.

  // `options.group` wins over `group` / `cloneable` (see effectiveGroup), for
  // the mouse as for the keyboard.
  // A group change can change which lists can take each other's rows: every
  // list rechecks its Shift instructions.
  function applyGroup() {
    instance?.option('group', effectiveGroup());
    registry.notifyPeers();
  }
  // Imperative handle (Phase 21 $expose). The SortableJS imperative surface a
  // consumer can't drive through props alone — exposed uniformly to all 6 targets.
  // Each guards the pre-mount/destroyed `instance = null`. Collision-clear: none of
  // the 4 verb names collide with the 16 props or the 5 events — `option` is a
  // distinct identifier from the `options` prop, so ROZ121 is clear.
  function getInstance() {
    return instance;
  }
  // toArray()/sort() use the rows' data-id keys — every row carries
  // :data-id="keyFor(item, index)", so toArray() returns the current key order
  // (set itemKey for stable object-list keys).
  function toArray() {
    return instance ? instance.toArray() : [];
  }
  // sort(order) reorders the bound items by those keys and writes them back
  // (the framework re-renders the rows; SortableJS never moves them behind the
  // model). Listed keys come first, in order; the rest follow in their order. No
  // event fires: it is the consumer's own call. With `useAnimation` (and a
  // non-zero `animation`) the rows slide from where they were.
  function sort(order: any, useAnimation = true) {
    const list = items();
    const next = orderByKeys(list, order ?? [], keyFor);
    if (next.every((item: any, i: any) => item === list[i])) return;
    const animate = useAnimation && instance != null;
    if (animate) instance.captureAnimationState();
    setItems(next);
    if (animate) {
      const sortable = instance;
      afterFlush(() => sortable.animateAll());
    }
  }
  // option(name) reads a live SortableJS option; option(name, value) sets one — the
  // runtime escape hatch for any SortableJS option beyond the curated props.
  // Setting `disabled`, `filter`, `draggable` or `sort` also applies to the
  // keyboard; `option('disabled', true)` mid-lift ends the lift this list holds.
  // A runtime `animation` is kept over later `animation` prop changes.
  function option(name: any, value: any) {
    if (!instance) return undefined;
    if (value === undefined) return instance.option(name);
    instance.option(name, value);
    if (TRACKED_OPTIONS.includes(name)) setOverride(name, value);
    if (name === 'disabled' && value) keyboardTurnedOff();
    // After the re-render, so every list reads the new group (React reads
    // state as of its last render).
    if (name === 'group') afterFlush(() => registry.notifyPeers());
    return value;
  }

  return (
    <>
    <div {...attrs} class={"rozie-sortable-wrap" + (((attrs as unknown as Record<string, unknown>).class as string | undefined) ? " " + ((attrs as unknown as Record<string, unknown>).class as string | undefined) : "")} data-rozie-s-0af24eae="">
      <div class={rozieClass(['rozie-sortable-list', local.listClass])} ref={(el) => { listElRef = el as HTMLElement; }} part="list" role="list" aria-label={rozieAttr(local.listLabel)} data-rozie-s-0af24eae="">
        
        {<Show when={(_props.headerSlot ?? _props.slots?.['header'])}>{(_props.headerSlot ?? _props.slots?.['header']?.({}))}</Show>}<For each={items()}>{(item, index) => <div data-id={rozieAttr(keyFor(item, index()))} role="listitem" aria-describedby={rozieAttr(rowTabbable() ? instructionsId() : null)} class={rozieClass(['rozie-sortable-item', itemClassFor(item, index()), liftedIndex() === index() ? 'rozie-sortable-item-lifted' : ''])} style={parseInlineStyle(itemStyleFor(item, index()))} tabIndex={rozieAttr(rowTabbable() ? 0 : null)} onKeyDown={($event: KeyboardEvent & { currentTarget: HTMLDivElement; target: Element }) => { onRowKeyDown($event, index()); }} data-rozie-s-0af24eae="">
          {typeof local.children === 'function' ? (local.children as (s: any) => any)({ item, get index() { return index(); }, get instructionsId() { return instructionsId(); } }) : resolved()}
        </div>}</For>
        {<Show when={(_props.footerSlot ?? _props.slots?.['footer'])}>{(_props.footerSlot ?? _props.slots?.['footer']?.({}))}</Show>}</div>
      <div class={"rozie-sortable-aria-live"} data-rozie-sortable-aria-live="" aria-live="polite" aria-atomic="true" data-rozie-s-0af24eae="">{ariaLiveText()}</div>
      <span hidden={true} id={rozieAttr(instructionsId())} data-rozie-s-0af24eae="">{rozieDisplay(instructionsText())}</span>
    </div>
    </>
  );
}
ts
import { LitElement, css, html, nothing } from 'lit';
import { customElement, property, query, queryAssignedElements, state } from 'lit/decorators.js';
import { SignalWatcher, effect, signal, untracked } from '@lit-labs/preact-signals';
import { RozieSlotDistributor, __rozieReconcileAfterDomMutation, createLitControllableProperty, rozieAttr, rozieClass, rozieDisplay, rozieListeners, rozieSpread, rozieStyle } from '@rozie/runtime-lit';
import { repeat } from 'lit/directives/repeat.js';
import { keyed } from 'lit/directives/keyed.js';
import { ROW_DRAGGABLE, orderByKeys, reapplyOptions, useSortableJS } from './internal/useSortableJS';
import { afterFlush, canHop, getKeyboardRegistry, isRenderable, nextInstructionsId, rowLiftable } from './internal/keyboardRegistry';
import { announcementText, defaultInstructions, fallbackLabel } from './internal/announcements';

/** The kind of message the list speaks during keyboard reordering (a key of the `announcements` prop). */
export type AnnouncementKind = 'lifted' | 'moved' | 'movedToList' | 'dropped' | 'droppedInList' | 'atStart' | 'atEnd' | 'notSortable' | 'noListBefore' | 'noListAfter' | 'cancelledReturnedToList' | 'cancelledReturned' | 'cancelledStays' | 'cancelledRemoved' | 'liftEnded';
/** What an `announcements` function receives. */
export interface AnnouncementContext {
  /** The row's screen-reader label (`labelFor`, else `item.label`, else the row's text). */
  label: string;
  /** The item value. */
  item: unknown;
  /** The name of the list the message is about (`listLabel`, or `list 2 of 3`). */
  list: string;
  /** 1-based position of the row in `list` (kinds that have a position). */
  position?: number;
  /** How many rows `list` holds (kinds that have a position). */
  total?: number;
  /** The list the row came from (`movedToList` only). */
  fromList?: string;
}
/** The `announcements` prop: one optional function per message kind; `null` or `''` says nothing. */
export type Announcements = Partial<Record<AnnouncementKind, (ctx: AnnouncementContext) => string | null | undefined>>;
/** The payload every `start` / `end` / `reorder` / `add` / `remove` event carries, for pointer and keyboard alike. */
export interface SortablePayload {
  /** Which input made the change. */
  interaction: 'pointer' | 'keyboard';
  /** The item's data value (never an element). */
  item: unknown;
  /** The row element; null when there is none (a lost lift, a removed clone copy). */
  el: HTMLElement | null;
  /** The list element the row came from. */
  from: HTMLElement;
  /** The list element the row went to. */
  to: HTMLElement;
  /** Item-row index in `from`; -1 for `add`. */
  oldIndex: number;
  /** Item-row index in `to`; -1 for `remove` and a lost lift. */
  newIndex: number;
  /** Pointer only: the raw SortableJS event. */
  originalEvent?: unknown;
}
/** Which element drives keyboard reordering (the `keyboardTrigger` prop). */
export type SortableKeyboardTrigger = 'row' | 'handle';
/** Which arrow keys move a lifted row within the list (the `orientation` prop). */
export type SortableOrientation = 'vertical' | 'horizontal';

export interface RozieSortableListEventMap extends Omit<HTMLElementEventMap, 'reorder' | 'add' | 'remove' | 'start' | 'end' | 'items-change'> {
  'reorder': CustomEvent<SortablePayload>;
  'add': CustomEvent<SortablePayload>;
  'remove': CustomEvent<SortablePayload>;
  'start': CustomEvent<SortablePayload>;
  'end': CustomEvent<SortablePayload>;
  'items-change': CustomEvent<any[]>;
}

interface RozieDefaultSlotCtx {
  item: any;
  index: any;
  instructionsId: any;
}

@customElement('rozie-sortable-list')
export default class SortableList extends SignalWatcher(LitElement) {
  static shadowRootOptions: ShadowRootInit = { ...LitElement.shadowRootOptions, slotAssignment: 'manual' };

  static styles = css`
:host{display:contents}
.rozie-sortable-wrap[data-rozie-s-0af24eae] { display: block; }
.rozie-sortable-list[data-rozie-s-0af24eae] { display: block; }
.rozie-sortable-item[data-rozie-s-0af24eae] { display: block; outline: none; }
.rozie-sortable-item[data-rozie-s-0af24eae]:focus-visible { outline: 2px solid var(--rozie-sortable-list-ring, #1a73e8); outline-offset: -2px; }
.rozie-sortable-item-lifted[data-rozie-s-0af24eae] {
  background: rgba(26, 115, 232, 0.1);
  box-shadow: 0 0 0 3px var(--rozie-sortable-list-ring, #1a73e8) inset;
}
.rozie-sortable-aria-live[data-rozie-s-0af24eae] {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
`;

  /**
   * The bound items array. The sole `model: true` prop — two-way bind it (`r-model:items` / `v-model:items` / `bind:items` / `[(items)]`) and SortableList writes the re-ordered array back whenever a drag, cross-list move, or keyboard reorder commits, with no manual `onChange → setState` wiring.
   * @example
   * <rozie-sortable-list .items=${todos} @items-change=${…} itemKey="id"></rozie-sortable-list>
   */
  @property({ type: Array, attribute: 'items' }) _items_attr: any[] = [];
  private _itemsControllable = createLitControllableProperty<any[]>({ host: this, eventName: 'items-change', defaultValue: [], initialControlledValue: undefined });
  /**
   * The per-row key the framework reconciler tracks each item by across a reorder — either a property name (e.g. `itemKey="id"` reads `item.id`) or an `(item, index) => key` function. With neither, id-less object items get a stable synthetic key via an internal `WeakMap` (survives reorder by object identity); primitive items fall back to index — pass a function for reorderable duplicate primitives.
   */
  @property({ type: String, attribute: 'item-key' }) itemKey: string | (((...args: any[]) => any) | null) = null;
  /**
   * CSS selector identifying the per-row drag handle, so a drag starts only from that element rather than anywhere in the row. Authored class names render literally on every target (React included), so a plain `.grip` works; `$classSelector('grip')` is an optional, typo-checked way to author it. `options.handle` and `option('handle', v)` win over this prop, for the keyboard (`keyboardTrigger: 'handle'`) as for the mouse.
   */
  @property({ type: String, reflect: true }) handle: string | null = null;
  /**
   * SortableJS group name enabling cross-list drag — two lists sharing a `group` accept items between each other (the source fires `remove`, the destination fires `add`). Set `cloneable: true` to flip a string group into clone-mode. Lists that share a `group` also exchange rows by keyboard: Shift+arrow while a row is lifted hops it to the previous or next list of the same group (in source order), subject to the same pull/put rules as a mouse drag. `options.group` takes precedence over this prop, for keyboard hops as for drags. Function-valued `pull`/`put` cannot be evaluated without a drag, so those lists are unreachable by keyboard. Set `itemKey` on grouped lists.
   */
  @property({ type: String, reflect: true }) group: string | null = null;
  /**
   * Reorder animation duration in milliseconds. `0` disables the animation. Reapplied live via `instance.option('animation', v)` (no remount). `options.animation`, and a runtime `option('animation', v)`, win over this prop.
   */
  @property({ type: Number, reflect: true }) animation: number = 150;
  /**
   * Temporarily disable dragging without unmounting — reapplied live via `instance.option('disabled', v)` (no remount). Also suppresses keyboard reordering: a disabled list is not sortable by any input, so rows lose their `tabindex` and the keydown handler no-ops. Turning it on while a row is lifted ends the lift where the row is (`Lift ended`, and `end` fires); `options.disabled` and `option('disabled', v)` do the same.
   */
  @property({ type: Boolean, reflect: true }) disabled: boolean = false;
  /**
   * Opt out of keyboard reordering (Space lift / Arrow move / Shift+Arrow hop between lists / Esc cancel / Enter drop) while leaving pointer drag enabled. Rows drop out of the tab order (no `tabindex`) and the keydown handler no-ops. Keyboard access is gated on `!disabled && !disableKeyboard`. Turning it on while a row is lifted ends the lift where the row is.
   */
  @property({ type: Boolean, reflect: true, attribute: 'disable-keyboard' }) disableKeyboard: boolean = false;
  /**
   * Which element drives keyboard reordering. `'row'` (default): rows are tab stops and the keys on the focused row drive reordering. `'handle'`: rows are NOT tab stops, and only keys pressed inside the element matched by `handle` (inside that row) drive the same Space/Enter lift-drop, Arrow move, Shift+Arrow hop and Escape cancel flow; handled keys call preventDefault so a handle `<button>`'s click does not fire. The consumer owns the handle markup (recommended: a `<button>` with its own aria-label such as "Reorder Hero banner") and the component adds no tabindex or role to slot content. `'handle'` without `handle` turns keyboard reordering off and logs a console warning. `disabled`/`disableKeyboard` still apply. Typed as `SortableKeyboardTrigger` (`'row' | 'handle'`); at runtime any value other than `'handle'` behaves as `'row'`.
   */
  @property({ type: String, reflect: true, attribute: 'keyboard-trigger' }) keyboardTrigger: SortableKeyboardTrigger = 'row';
  /**
   * Verbatim SortableJS options pass-through for anything not covered by the named props. The named props win on key conflict but `options` lands AFTER them in the merge so consumers can override defaults; handler keys (`onStart`, `onEnd`, `onUpdate`, `onAdd`, `onRemove`, `onClone`) are stripped — the helper owns those paths. Runtime-updatable: when `options` changes, each key whose value changed is reapplied via `instance.option(key, v)` (no remount), so mouse and keyboard obey the same values; a key you drop goes back to its named prop (or, for `sort` and `draggable`, the component default), and any other dropped key keeps its last value until you set it. `forceFallback` is still read only at construction.
   */
  @property({ type: Object }) options: any = {};
  /**
   * Optional `(item, idx) => string` returning the screen-reader label for the aria-live announcer during keyboard drag. Defaults to `item.label`; without a `label` field, the row's text (whitespace collapsed, without nested lists or hidden content), else `String(item)` for a primitive, else `item {position}`.
   */
  @property({ type: Function, attribute: 'label-for' }) labelFor: ((...args: any[]) => any) | null = null;
  /**
   * Class name applied to the drop-placeholder (ghost) element while dragging. Forwarded live via `instance.option`, so toggling it at runtime takes effect without a remount.
   */
  @property({ type: String, reflect: true, attribute: 'ghost-class' }) ghostClass: string | null = null;
  /**
   * Class name applied to the currently-chosen item while dragging. Forwarded live via `instance.option` (no remount needed to change it).
   */
  @property({ type: String, reflect: true, attribute: 'chosen-class' }) chosenClass: string | null = null;
  /**
   * Class name applied to the dragging element. Only takes effect in fallback mode (`forceFallback: true`). Forwarded live via `instance.option`.
   */
  @property({ type: String, reflect: true, attribute: 'drag-class' }) dragClass: string | null = null;
  /**
   * CSS selector that prevents drag initiation on matching rows (locked items). SortableJS checks it at `mousedown`/`touchstart` and aborts the drag if it matches. The keyboard honours it too: a row that matches (the row element, or its slot root: the row template's single element when nothing else sits beside it) cannot be lifted with Space/Enter; any other matching control (a `.js-remove` button, an `input`) blocks only presses on itself. `options.filter` (which may also be a SortableJS filter function) takes precedence. A `data-*` attribute selector (e.g. `[data-locked]`) is the most robust choice across all targets.
   */
  @property({ type: String, reflect: true }) filter: string | null = null;
  /**
   * CSS easing function for the reorder animation (e.g. `'ease-in'`, `'cubic-bezier(0.4, 0, 0.2, 1)'`). Runtime-updatable.
   */
  @property({ type: String, reflect: true }) easing: string | null = null;
  /**
   * Force SortableJS's mouse-event drag path over HTML5 DnD — useful for touch devices, consistent cross-browser behavior, and synthetic test drivers (and `dragClass` only applies in this mode). **Construction-time only**: SortableJS reads it once at construction, so re-key the `<SortableList>` to toggle it at runtime.
   */
  @property({ type: Boolean, reflect: true, attribute: 'force-fallback' }) forceFallback: boolean = false;
  /**
   * SortableJS swap threshold (0..1) — a lower value makes rows swap earlier as the dragged item overlaps a neighbor. Reapplied live via `instance.option('swapThreshold', v)` — SortableJS reads it on every dragover, so no remount is needed.
   */
  @property({ type: Number, reflect: true, attribute: 'swap-threshold' }) swapThreshold: number = 1;
  /**
   * High-level prop that REPLACES a string `group` with SortableJS's `{ name, pull: 'clone', put: false }` clone-mode object form — the source deposits a COPY onto the destination and keeps its own array unchanged, and takes nothing back: no row can be dropped or keyboard-hopped into it (the palette → canvas pattern). With `group: null` it is a no-op (a clone-mode list with no group name has no peer to clone into). Reapplied live — toggling `cloneable` (or changing `group`) recomputes the clone-mode shape and reapplies it via `instance.option('group', …)`, no remount.
   */
  @property({ type: Boolean, reflect: true }) cloneable: boolean = false;
  /**
   * Extra class(es) merged onto the list container (the SortableJS root) alongside the base `rozie-sortable-list` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding), normalized identically across all six targets — the hook for bridging a CSS framework (`.list-group`) or a flex/grid parent onto the component.
   */
  @property({ type: String, attribute: 'list-class' }) listClass: string | any[] | any = '';
  /**
   * Extra class(es) merged onto every item row alongside the base `rozie-sortable-item` class. Accepts a `String`, `Array`, or `Object` (Vue-style class binding) applied uniformly, OR an `(item, index) => class` function for per-row classes evaluated at render time. Normalized identically across all six targets.
   */
  @property({ type: String, attribute: 'item-class' }) itemClass: string | any[] | any | (((...args: any[]) => any) | null) = '';
  /**
   * The list's human name, such as `"Top sidebar"`. Sets `aria-label` on the list container (`role="list"`) and names the list in keyboard announcements when a row moves between lists (`Moved Hero banner to Top sidebar, position 1 of 4`, `Dropped Hero banner in Top sidebar at position 3 of 4`, `No list after Top sidebar`). Pass the same words as the zone's visible heading. With no label, announcements fall back to a neutral `list 2 of 3`, counting the mounted lists of the same group in hop (source) order.
   */
  @property({ type: String, reflect: true, attribute: 'list-label' }) listLabel: string | null = null;
  /**
   * Which arrow keys move a lifted row within the list: `'vertical'` (default) uses ↑/↓, `'horizontal'` uses ←/→. A horizontal list's default spoken instructions say "Use the left and right arrow keys to move" (`role="list"` has no `aria-orientation`). Typed as `SortableOrientation` (`'vertical' | 'horizontal'`).
   */
  @property({ type: String, reflect: true }) orientation: SortableOrientation = 'vertical';
  /**
   * How many positions Page Up / Page Down move a lifted row. The move stops at the first or last position when fewer rows remain.
   */
  @property({ type: Number, reflect: true, attribute: 'page-step' }) pageStep: number = 5;
  /**
   * Replaces the spoken keyboard instructions. The text sits in a hidden element referenced by `aria-describedby` from each tabbable row (row mode) or from the consumer's handle via the `instructionsId` slot prop (handle mode). Default: "Press Space or Enter to pick up, and again to drop. Use the up and down arrow keys to move, Home and End to jump to the start or end, Page Up and Page Down to move several places, and Escape to cancel." (with `orientation: 'horizontal'`, "the left and right arrow keys"; a `sort: false` list says only "Press Space or Enter to pick up, and again to drop. Press Escape to cancel."). When another mounted list could take this list's rows (by the group rules of `group`, `options.group` or `option('group', v)`), the default adds "Hold Shift with an arrow key to move to another list." (updated as lists mount, unmount or change group).
   */
  @property({ type: String, reflect: true, attribute: 'keyboard-instructions' }) keyboardInstructions: string | null = null;
  /**
   * Rewords or translates what the list says during keyboard reordering. An object of optional functions keyed by message kind (`lifted`, `moved`, `movedToList`, `dropped`, `droppedInList`, `atStart`, `atEnd`, `notSortable`, `noListBefore`, `noListAfter`, `cancelledReturnedToList`, `cancelledReturned`, `cancelledStays`, `cancelledRemoved`, `liftEnded`). Each receives a context (`label`, `item`, `list`, and for kinds with a position `position` (1-based) and `total`; `movedToList` also `fromList`) and returns the text to speak; `null` or `''` says nothing. Kinds without a function keep the default English text (see "Announcements"). Define the object in your script and bind it (Angular templates reject inline arrow functions), e.g. `const announcements = { moved: ({ label, position, total }) => label + ' → ' + position + '/' + total }`. Typed as `Announcements`, exported with `AnnouncementKind` and `AnnouncementContext`.
   * @example
   * <rozie-sortable-list .items=${todos} @items-change=${…} .announcements=${announcements}></rozie-sortable-list>
   */
  @property({ type: Object }) announcements: Announcements | null = null;
  /**
   * Per-row inline style applied to the `.rozie-sortable-item` wrapper. Accepts a CSS `String`, a flat style object (`Record<string, string | number>`), or an `(item, index) => string | object` function for per-row styling. Because it lands on the wrapper — the direct child of the list container — it can drive CSS-grid placement (`grid-column` / `grid-row` / `align-self`) when `listClass` sets `display: grid`. Normalized per target; `null` / empty drops the attribute.
   */
  @property({ type: String, attribute: 'item-style' }) itemStyle: string | any | (((...args: any[]) => any) | null) = null;
  private _liftedIndex = signal<any>(null);
  private _ariaLiveText = signal('');
  private _instructionsId = signal<any>(null);
  private _optionOverrides = signal<any>({});
  private _hasHopPeer = signal(false);
  @query('[data-rozie-ref="listEl"]') private _refListEl!: HTMLElement;
private __rozieWatchPrev_3: unknown;
private __rozieWatchInitial_3 = true;
private __rozieWatchInitial_14 = true;
private __rozieFirstUpdateDone = false;

  private _rozieSlotDistributor = new RozieSlotDistributor(this);

  @state() private _hasSlotHeader = false;
  @queryAssignedElements({ slot: 'header', flatten: true }) private _slotHeaderElements!: Element[];
  @state() private _hasSlotDefault = false;
  @queryAssignedElements({ flatten: true }) private _slotDefaultElements!: Element[];
  @property({ attribute: false }) __rozieDefaultSlot__?: (scope: { item: any; index: any; instructionsId: any }) => unknown;
  @state() private _hasSlotFooter = false;
  @queryAssignedElements({ slot: 'footer', flatten: true }) private _slotFooterElements!: Element[];
  // Phase 79 Plan 08 (R4) contract for 79-09: the record intake for
  // record-routed slot fills. 79-09's consumer-side emitSlotFiller
  // accumulates an object literal onto the SAME `.rozieSlots=${{ ... }}`
  // open-tag binding; the KEY is the fill's authored (possibly
  // non-identifier) name and the VALUE is a scope-taking render
  // function. `rozieSlots?.[name]` must be checked BEFORE the legacy
  // named function-prop / <slot> fallback (AC-9). Attribute
  // deserialization is disabled — this is a function-valued record,
  // never reflected to/from an HTML attribute.
  @property({ attribute: false }) rozieSlots?: Record<string, (scope: any) => unknown>;

  private _disconnectCleanups: Array<() => void> = [];
  // Re-parenting guard: set true once the deferred teardown has actually
  // run (a genuine un-mount), so a subsequent reconnect knows to re-arm.
  private _rozieTornDown = false;

  _rozieReconcileSeq = 0;

  private _armListeners(): void {
    {
      const slotEl = this.shadowRoot?.querySelector('slot[name="header"]');
      if (slotEl !== null && slotEl !== undefined) {
        const update = () => { this._hasSlotHeader = this._slotHeaderElements.length > 0; };
        slotEl.addEventListener('slotchange', update);
        // CR-05 fix: push cleanup so the listener is removed on disconnectedCallback.
        this._disconnectCleanups.push(() => slotEl.removeEventListener('slotchange', update));
        update();
      }
    }

    {
      const slotEl = this.shadowRoot?.querySelector('slot:not([name])');
      if (slotEl !== null && slotEl !== undefined) {
        const update = () => { this._hasSlotDefault = this._slotDefaultElements.length > 0; };
        slotEl.addEventListener('slotchange', update);
        // CR-05 fix: push cleanup so the listener is removed on disconnectedCallback.
        this._disconnectCleanups.push(() => slotEl.removeEventListener('slotchange', update));
        update();
      }
    }

    {
      const slotEl = this.shadowRoot?.querySelector('slot[name="footer"]');
      if (slotEl !== null && slotEl !== undefined) {
        const update = () => { this._hasSlotFooter = this._slotFooterElements.length > 0; };
        slotEl.addEventListener('slotchange', update);
        // CR-05 fix: push cleanup so the listener is removed on disconnectedCallback.
        this._disconnectCleanups.push(() => slotEl.removeEventListener('slotchange', update));
        update();
      }
    }
  }

  connectedCallback(): void {
    // Phase 07.3.1 D-LIT-15 — pre-seed _hasSlot<X> from light DOM so first render isn't deadlocked.
    this._hasSlotHeader = Array.from(this.children).some((el) => el.getAttribute('slot') === 'header');
    this._hasSlotDefault = Array.from(this.children).some((el) => !el.hasAttribute('slot') && (el.nodeType !== 3 || (el.textContent?.trim().length ?? 0) > 0));
    this._hasSlotFooter = Array.from(this.children).some((el) => el.getAttribute('slot') === 'footer');
    super.connectedCallback();
    if (this.hasUpdated && this._rozieTornDown) { this._rozieTornDown = false; this.firstUpdated(); }
  }

  firstUpdated(): void {
    this._rozieTornDown = false;
    if (!this.isConnected) { this._rozieTornDown = true; return; }

    this._armListeners();

    this._disconnectCleanups.push((() => {
      this.instance?.destroy();
      // Unmounting while holding a keyboard lift ends it (its `end` comes from
      // the origin list, if that one is still mounted).
      if (this.registry.lift != null && this.registry.lift.holder === this.entry) this.loseLift(true);
      this.unregisterEntry?.();
      this.unregisterEntry = null;
      this.unhookNativeEvents?.();
      this.unhookNativeEvents = null;
      this.unhookStrayKeys?.();
      this.unhookStrayKeys = null;
    }));

    this._disconnectCleanups.push(effect(() => { const __watchVal = (() => [this.disabled, this.disableKeyboard, this.options, this._optionOverrides.value])(); untracked(() => { this.__rozieWatchPrev_3 = __watchVal; if (this.__rozieWatchInitial_3) { this.__rozieWatchInitial_3 = false; return; } (() => {
      if (!this.keyboardEnabled()) this.keyboardTurnedOff();
    })(); }); }));
    this._disconnectCleanups.push(effect(() => { const __watchVal = (() => this.items)(); untracked(() => { if (this.__rozieWatchInitial_14) { this.__rozieWatchInitial_14 = false; return; } (() => {
      const lift = this.registry.lift;
      if (lift == null || lift.holder !== this.entry) return;
      const i = this.registry.indexOfLift();
      if (i < 0) {
        this.loseLift();
        return;
      }
      if (this._liftedIndex.value !== i) this._liftedIndex.value = i;
      // Once the holder has rendered the lifted row, that is the lifted row
      // element. After a hop this drops the source's old row, which the source
      // may reuse for another item (index keys).
      const row = this.entry.rowEl(i);
      if (row != null) lift.liftedRowEl = row;
      this.focusNearRow(i, lift.key);
    })(); }); }));

    // Kept across a Lit element's disconnect and reconnect (mount runs again).
    if (this._instructionsId.value == null) this._instructionsId.value = nextInstructionsId();
    this.warnIfHandleMissing();
    // Named `sortable` (not `handle`) to avoid shadowing `$props.handle`
    // when the options object below references it.
    const sortable = useSortableJS(this._refListEl, {
      items: () => this.items,
      onCommit: (next: any) => {
        this._itemsControllable.write(next);
      },
      options: {
        animation: this.animation,
        disabled: this.disabled,
        group: this.resolveGroup(),
        handle: this.handle,
        ghostClass: this.ghostClass,
        chosenClass: this.chosenClass,
        dragClass: this.dragClass,
        filter: this.filter,
        forceFallback: this.forceFallback,
        swapThreshold: this.swapThreshold,
        easing: this.easing,
        ...this.options
      },
      // Lit lit-html `repeat` directive caches its part array by sentinel-
      // comment node identity; SortableJS's physical DOM mutation desyncs
      // that cache. The sigil lowers to `__rozieReconcileAfterDomMutation(this)`
      // on Lit (real call) and `void 0` on the other 5 targets (no-op).
      afterCommit: () => __rozieReconcileAfterDomMutation(this),
      // Every pointer event carries the same payload as the keyboard ones, with
      // item-row indices and the raw SortableJS event as `originalEvent`.
      onChange: (c: any) => {
        const payload = {
          interaction: 'pointer' as const,
          item: c.item,
          el: c.el,
          from: c.from,
          to: c.to,
          oldIndex: c.oldIndex,
          newIndex: c.newIndex,
          originalEvent: c.event
        };
        if (c.kind === 'reorder') this.dispatchEvent(new CustomEvent<SortablePayload>("reorder", {
          detail: payload,
          bubbles: false,
          composed: false
        }));else if (c.kind === 'add') this.dispatchEvent(new CustomEvent<SortablePayload>("add", {
          detail: payload,
          bubbles: false,
          composed: false
        }));else if (c.kind === 'remove') this.dispatchEvent(new CustomEvent<SortablePayload>("remove", {
          detail: payload,
          bubbles: false,
          composed: false
        }));
      },
      onStart: (d: any) => {
        // A pointer drag ends any active keyboard lift first.
        if (this.registry.lift != null) this.endLift('drop');
        // That lift's `end` (pending until a task) comes before this `start`.
        this.registry.flushEnds();
        this.dispatchEvent(new CustomEvent<SortablePayload>("start", {
          detail: {
            interaction: 'pointer',
            item: d.item,
            el: d.el,
            from: d.from,
            to: d.to,
            oldIndex: d.oldIndex,
            newIndex: d.newIndex,
            originalEvent: d.event
          },
          bubbles: false,
          composed: false
        }));
      },
      // `end` comes from the list the row ended up in: the destination when it
      // is a SortableList, else (dropped outside, or into a SortableJS list
      // that isn't one of ours) this source list. It goes through the
      // registry's `deferEnd`, like a keyboard `end`: it fires in a task after
      // every list involved has written its items and the re-render those
      // writes scheduled, and before the next drag's or lift's `start`. An
      // unmounted list never emits: if the destination has unmounted by then
      // (in its own `add` handler, say), this list (the origin, which emitted
      // `start`) emits it, `to` still the destination; if both are gone,
      // nothing is emitted.
      scheduleEnd: (d: any) => {
        const dest = this.registry.entryFor(d.to);
        const destGone = dest == null && d.to !== d.from && this.registry.wasList(d.to);
        this.registry.deferEnd((host: any) => {
          const row = d.item === undefined || host.el !== d.to ? null : this.rowByKey(d.to, host.keyOf(d.item, d.newIndex));
          host.emit('end', {
            interaction: 'pointer',
            item: d.item,
            el: row ?? this.liveEl(d.el),
            from: d.from,
            to: d.to,
            oldIndex: d.oldIndex,
            newIndex: d.newIndex,
            originalEvent: d.event
          });
        }, destGone ? null : dest ?? this.entry, this.entry);
      }
    });
    this.instance = sortable.instance;
    this.appliedOptions = this.options;
    // Runtime `option(name, v)` values this list remembers (Lit keeps them when
    // the element is moved in the DOM and mounts again) apply to the new
    // SortableJS instance too, so mouse and keyboard keep agreeing. Empty on a
    // first mount.
    const remembered: any = this._optionOverrides.value;
    if (remembered != null) {
      for (const name of Object.keys(remembered) as any) this.instance.option(name, remembered[name]);
    }
    const listEl = this._refListEl;
    const stopNative = (ev: any) => {
      if (ev.target === listEl) ev.stopPropagation();
    };
    for (const name of this.SORTABLE_DOM_EVENTS as any) listEl?.addEventListener(name, stopNative);
    // A focused row that stops being focusable (its tabindex goes when the
    // keyboard turns off) is blurred at once, during the framework's DOM
    // update, with focus going nowhere (`relatedTarget` null): it would land on
    // <body>. Move it to the list instead.
    const rowBlurred = (ev: any) => {
      if (listEl == null) return;
      const row: any = ev.target;
      if (ev.relatedTarget != null || row == null || row.parentNode !== listEl) return;
      if (!row.classList.contains('rozie-sortable-item') || row.hasAttribute('tabindex') || !row.isConnected) return;
      if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
      listEl.focus();
    };
    listEl?.addEventListener('focusout', rowBlurred);
    this.unhookNativeEvents = () => {
      for (const name of this.SORTABLE_DOM_EVENTS as any) listEl?.removeEventListener(name, stopNative);
      listEl?.removeEventListener('focusout', rowBlurred);
    };

    // Register with the keyboard registry. Other instances call these methods
    // when a keyboard lift hands a row between lists.
    this.entry = {
      el: listEl,
      group: () => this.effectiveGroup(),
      label: () => this.listLabel,
      // A handle-mode list without a handle selector has its keyboard off.
      keyboardEnabled: () => this.keyboardEnabled() && !(this.handleMode() && this.handleSelector() == null),
      items: () => this.items,
      keyOf: (item: any, i: any) => String(this.keyFor(item, i)),
      labelOf: (item: any, i: any, row: HTMLElement | null = null) => String(this.labelOf(item, i, row)),
      message: (kind: any, ctx: any) => announcementText(this.announcements, kind, ctx),
      onKey: (key: any, shift: any) => this.holderKey(key, shift),
      write: (next: any) => {
        this._itemsControllable.write(next);
      },
      setLifted: (i: any) => {
        this._liftedIndex.value = i;
      },
      // The same text twice in a row would not change the region, and a screen
      // reader would not read it again ("Apple is already first", twice): a
      // repeat alternates a trailing no-break space, which is not spoken.
      announce: (text: any) => {
        const next = text !== '' && text === this.lastSpoken ? text + '\u00A0' : text;
        this.lastSpoken = next;
        this._ariaLiveText.value = next;
      },
      focusRow: (item: any, i: any) => this.refocusRow(item, i),
      focusNear: (i: any) => this.focusNearRow(i),
      rowEl: (i: any) => {
        const list = this.items;
        if (i < 0 || i >= list.length) return null;
        return this.rowByKey(listEl, String(this.keyFor(list[i], i)));
      },
      // Always set (an equal value is a no-op on every target): a compare
      // against $data would read React's render-time ref, stale when two peer
      // changes land in one commit (one list unmounts, another mounts).
      peersChanged: (v: any) => {
        this._hasHopPeer.value = v;
      },
      emit: (name: any, payload: any) => {
        if (name === 'add') this.dispatchEvent(new CustomEvent<SortablePayload>("add", {
          detail: payload,
          bubbles: false,
          composed: false
        }));else if (name === 'remove') this.dispatchEvent(new CustomEvent<SortablePayload>("remove", {
          detail: payload,
          bubbles: false,
          composed: false
        }));else if (name === 'reorder') this.dispatchEvent(new CustomEvent<SortablePayload>("reorder", {
          detail: payload,
          bubbles: false,
          composed: false
        }));else if (name === 'start') this.dispatchEvent(new CustomEvent<SortablePayload>("start", {
          detail: payload,
          bubbles: false,
          composed: false
        }));else if (name === 'end') this.dispatchEvent(new CustomEvent<SortablePayload>("end", {
          detail: payload,
          bubbles: false,
          composed: false
        }));
      }
    };
    this.unregisterEntry = this.registry.register(this.entry);
    const strayKey = (ev: any) => this.onStrayKey(ev);
    // A pointer press means the user moved on: keys lost to <body> after it
    // are not routed to the lift.
    const pointerPress = () => {
      if (this.registry.lift != null) this.registry.lift.focusPending = false;
    };
    document.addEventListener('keydown', strayKey);
    document.addEventListener('pointerdown', pointerPress, true);
    this.unhookStrayKeys = () => {
      document.removeEventListener('keydown', strayKey);
      document.removeEventListener('pointerdown', pointerPress, true);
    };
    // $onMount's cleanup-return: closing over a setup-local (`sortable`) does
    // not survive the Solid emitter's setup/cleanup split — it scopes cleanup
    // outside the setup IIFE. Closing over `instance` / `unregisterEntry`
    // (module-scope `let`s) works on every target.
  }

  updated(changedProperties: Map<string, unknown>): void {
    if (this.__rozieFirstUpdateDone && (changedProperties.has('disabled'))) { const __watchVal = (() => this.disabled)(); ((v: any) => {
      this.instance?.option('disabled', v);
      this.setOverride('disabled', v);
    })(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('animation'))) { const __watchVal = (() => this.animation)(); ((v: any) => this.instance?.option('animation', this.liveOption('animation', v)))(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('options'))) { const __watchVal = (() => this.options)(); (() => {
      if (!this.instance) return;
      const next = this.options;
      const base = {
        animation: this.animation,
        disabled: this.disabled,
        group: this.resolveGroup() ?? null,
        handle: this.handle,
        ghostClass: this.ghostClass,
        chosenClass: this.chosenClass,
        dragClass: this.dragClass,
        filter: this.filter,
        swapThreshold: this.swapThreshold,
        easing: this.easing,
        sort: true,
        draggable: ROW_DRAGGABLE
      };
      // A fresh inline function with the same content (React re-renders) is
      // applied so SortableJS runs the newest closure, but it is no change: a
      // runtime `option(name, v)` still in force keeps winning over it.
      const applied = reapplyOptions(this.instance, this.appliedOptions, next, base, {
        keep: (key: any, prev: any) => {
          const ov: any = this._optionOverrides.value;
          return ov != null && Object.prototype.hasOwnProperty.call(ov, key) && ov[key] !== prev;
        },
        refreshed: (key: any) => {
          if (this.KEYBOARD_OPTIONS.includes(key)) this.setOverride(key, this.instance.option(key));
        }
      });
      this.appliedOptions = next;
      for (const key of applied as any) {
        // The keyboard reads the value SortableJS now runs with. A remembered
        // runtime `animation` / `handle` / `group` is superseded by the newer
        // `options` value.
        if (this.KEYBOARD_OPTIONS.includes(key)) this.setOverride(key, this.instance.option(key));else if (this.TRACKED_OPTIONS.includes(key)) this.clearOverride(key);
      }
      if (applied.includes('group')) this.registry.notifyPeers();
    })(); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('disabled') || changedProperties.has('disableKeyboard') || changedProperties.has('options'))) { const __watchVal = untracked(() => [this.disabled, this.disableKeyboard, this.options, this._optionOverrides.value]); if (!Object.is(__watchVal, this.__rozieWatchPrev_3)) { this.__rozieWatchPrev_3 = __watchVal; untracked(() => (() => {
      if (!this.keyboardEnabled()) this.keyboardTurnedOff();
    })()); } }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('group'))) { const __watchVal = (() => this.group)(); (() => this.applyGroup())(); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('cloneable'))) { const __watchVal = (() => this.cloneable)(); (() => this.applyGroup())(); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('swapThreshold'))) { const __watchVal = (() => this.swapThreshold)(); ((v: any) => this.instance?.option('swapThreshold', v))(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('handle'))) { const __watchVal = (() => this.handle)(); ((v: any) => {
      this.instance?.option('handle', this.liveOption('handle', v));
      this.warnIfHandleMissing();
    })(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('keyboardTrigger'))) { const __watchVal = (() => this.keyboardTrigger)(); (() => this.warnIfHandleMissing())(); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('ghostClass'))) { const __watchVal = (() => this.ghostClass)(); ((v: any) => this.instance?.option('ghostClass', v))(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('chosenClass'))) { const __watchVal = (() => this.chosenClass)(); ((v: any) => this.instance?.option('chosenClass', v))(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('dragClass'))) { const __watchVal = (() => this.dragClass)(); ((v: any) => this.instance?.option('dragClass', v))(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('filter'))) { const __watchVal = (() => this.filter)(); ((v: any) => {
      this.instance?.option('filter', v);
      this.setOverride('filter', v);
    })(__watchVal); }
    if (this.__rozieFirstUpdateDone && (changedProperties.has('easing'))) { const __watchVal = (() => this.easing)(); ((v: any) => this.instance?.option('easing', v))(__watchVal); }
    this.__rozieFirstUpdateDone = true;
  }

  disconnectedCallback(): void {
    super.disconnectedCallback();
    queueMicrotask(() => {
      if (this.isConnected || this._rozieTornDown) return;
      this._rozieTornDown = true;
      for (const fn of this._disconnectCleanups) fn();
      this._disconnectCleanups = [];
      this.__rozieWatchInitial_3 = true;
      this.__rozieWatchInitial_14 = true;
    });
  }

  attributeChangedCallback(name: string, old: string | null, value: string | null): void {
    super.attributeChangedCallback(name, old, value);
    if (name === 'items') this._itemsControllable.notifyAttributeChange(value as unknown as any[]);
  }

  render() {
    return html`
<div class="rozie-sortable-wrap" ${rozieSpread(this.$attrs)} ${rozieListeners(this.$listeners)} data-rozie-s-0af24eae>
  <div class="${(rozieClass(['rozie-sortable-list', this.listClass]))}" part="list" role="list" aria-label=${rozieAttr(this.listLabel)} data-rozie-ref="listEl" data-rozie-s-0af24eae>${keyed(this._rozieReconcileSeq ?? 0, html`
    
    ${this._hasSlotHeader ? html`<slot name="header"></slot>` : nothing}${repeat<any>(this.items, (item, index) => this.keyFor(item, index), (item, index) => html`<div class="${(rozieClass(['rozie-sortable-item', this.itemClassFor(item, index), this._liftedIndex.value === index ? 'rozie-sortable-item-lifted' : '']))}" style=${rozieStyle(this.itemStyleFor(item, index))} data-id=${rozieAttr(this.keyFor(item, index))} role="listitem" tabindex=${rozieAttr(this.rowTabbable() ? 0 : null)} aria-describedby=${rozieAttr(this.rowTabbable() ? this._instructionsId.value : null)} @keydown=${($event: KeyboardEvent & { currentTarget: HTMLDivElement; target: HTMLDivElement }) => { this.onRowKeyDown($event, index); }} data-rozie-s-0af24eae>
      ${this.rozieSlots?.['default'] !== undefined ? this.rozieSlots?.['default']!({item: item, index: index, instructionsId: this._instructionsId.value}) : this.__rozieDefaultSlot__ !== undefined ? this.__rozieDefaultSlot__({item: item, index: index, instructionsId: this._instructionsId.value}) : html`<slot data-rozie-params=${(() => { try { return JSON.stringify({item: item, index: index, instructionsId: this._instructionsId.value}); } catch { return '{}'; } })()}></slot>`}
    </div>`)}
    ${this._hasSlotFooter ? html`<slot name="footer"></slot>` : nothing}`)}</div>
  <div class="rozie-sortable-aria-live" data-rozie-sortable-aria-live="" aria-live="polite" aria-atomic="true" data-rozie-s-0af24eae>${this._ariaLiveText.value}</div>
  <span hidden="" id=${rozieAttr(this._instructionsId.value)} data-rozie-s-0af24eae>${rozieDisplay(this.instructionsText())}</span>
</div>
`;
  }

  instance: any = null;

  // The `options` object SortableJS was last given (see the `options` watcher).
  appliedOptions: any = null;

  // Keyboard lift state lives in the shared registry (one active keyboard lift
  // per page, so a later task can hand a lifted row between lists).
  // `$data.liftedIndex` is only its mirror, for the lifted-row styling.
  registry = getKeyboardRegistry();

  // This list's registry entry (a ListEntry), built and registered in $onMount.
  entry: any = null;

  unregisterEntry: any = null;

  // Removes the listeners that keep SortableJS's own DOM events inside the list.
  unhookNativeEvents: any = null;

  // Removes the document keydown listener that catches keys lost to <body>.
  unhookStrayKeys: any = null;

  // SortableJS also dispatches its events as BUBBLING native DOM events
  // (`start`, `end`, `add`, `remove`, `change`, …) on the list element, before
  // it calls the option callbacks. An output binding on the component host
  // (Angular's `(start)` / `(end)` / `(add)` / `(remove)`, a Lit listener) also
  // catches a native DOM event of the same name, so a consumer would get the raw
  // SortableJS event as an extra event. The component re-emits the committed
  // events itself, so stop the raw ones at the list element (only events
  // dispatched ON the list — an `<input>`'s own `change` is untouched).
  SORTABLE_DOM_EVENTS = ['choose', 'unchoose', 'start', 'end', 'add', 'update', 'sort', 'remove', 'filter', 'clone', 'change', 'select', 'deselect'];

  // role="list" takes no aria-orientation, so a horizontal list says which
  // arrow keys move in its instructions instead. A `sort: false` list leaves out
  // the move sentence, and a list whose rows another mounted list could take
  // (by the group SortableJS runs with, `options.group` included) says how to
  // hop.
  instructionsText = () => {
  if (this.keyboardInstructions != null) return this.keyboardInstructions;
  return defaultInstructions({
    horizontal: this.orientation === 'horizontal',
    sortable: this.liveOption('sort', true) !== false,
    grouped: this.effectiveGroup() != null && this._hasHopPeer.value
  });
};

  // Instance-scoped synthetic-id store for id-less object items. Keyed by object
  // IDENTITY, so the same object keeps its synthetic id across a reorder (the
  // framework reconciler then rebinds the row component instance to its ORIGINAL
  // item, not its slot position — the data-corruption fix).
  //
  // Phase 73 item #11-b removed the former "fold the WeakMap + counter into ONE
  // member-mutated object const" workaround: `hoistModuleLet`'s reachability
  // walk now also roots at helpers called ONLY from a template expression
  // (`keyFor` is called from `:key`/`:data-id`, never from a hook), so the bare
  // `let __rowKeySeq = 0` below hoists to a `useRef` on React exactly like the
  // hook-reached case — no more per-render reset. Verified in codegen.
  __rowKeyMap = new WeakMap();

  __rowKeySeq = 0;

  // 4-tier per-row key precedence. Its return feeds BOTH :key and :data-id.
  keyFor = (item: any, index: any) => {
  // (a) function itemKey: consumer-supplied (item, index) => key.
  if (typeof this.itemKey === 'function') {
    return this.itemKey(item, index);
  }
  // (b) string itemKey: a property name on a non-null object item.
  if (typeof this.itemKey === 'string' && item !== null && typeof item === 'object' && item[this.itemKey] != null) {
    return item[this.itemKey];
  }
  // (c) id-less object (or function) item: assign-on-first-sight WeakMap
  //     synthetic id. Survives reorder because it is keyed by object identity.
  if (item !== null && typeof item === 'object' || typeof item === 'function') {
    if (!this.__rowKeyMap.has(item)) {
      this.__rowKeyMap.set(item, '__rk' + this.__rowKeySeq++);
    }
    return this.__rowKeyMap.get(item);
  }
  // (d) primitive item: fall back to index. NOTE: duplicate primitives are
  //     unsafe to reorder this way — pass a function itemKey for those.
  return index;
};

  // Resolve the SortableJS `group` option: `cloneable` is a high-level Rozie
  // prop that REPLACES a string `group` with SortableJS's
  // `{ name, pull: 'clone', put: false }` clone-mode object form (a palette
  // takes nothing back, by mouse or keyboard). When
  // `cloneable:false`, pass `$props.group` through verbatim. When
  // `cloneable:true` AND `$props.group` is null, leave it null — a clone-mode
  // list without a group name is not meaningful (no peer list can join the
  // cross-list flow). Shared by $onMount construction AND the group/cloneable
  // $watch reconcile below — single source of truth, no duplicated ternary.
  resolveGroup = () => this.cloneable && typeof this.group === 'string' ? {
  name: this.group,
  pull: 'clone' as const,
  put: false as const
} : this.group ?? undefined;

  // The group SortableJS actually runs with: a runtime `option('group', v)`,
  // else `options.group` (it lands after the named props in the merge), else
  // the `group` / `cloneable` props. Keyboard hops follow the same rules as the
  // mouse, so they read this one.
  effectiveGroup = () => {
  const ov: any = this._optionOverrides.value;
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, 'group')) return ov.group;
  const o: any = this.options;
  return o != null && o.group != null ? o.group : this.resolveGroup();
};

  // Resolve itemClass for a row: a static value (string | array | object) OR a
  // per-row (item, index) => class function. The result is fed into the :class
  // array and normalized by each target's class path (rozieClass / clsx / native).
  itemClassFor = (item: any, index: any) => {
  const v = this.itemClass;
  return typeof v === 'function' ? v(item, index) : v;
};

  // Resolve itemStyle for a row: a static value (string | object) OR a per-row
  // (item, index) => style function. Returns string | object | null; the dynamic
  // :style binding normalizes it per target. null / empty → attribute dropped.
  itemStyleFor = (item: any, index: any) => {
  const s = typeof this.itemStyle === 'function' ? this.itemStyle(item, index) : this.itemStyle;
  return s == null || s === '' ? null : s;
};

  // Read the display label for an item — used by the aria-live announcer.
  // Phase 16 R7 / D-08: $props.labelFor reads as `null` on all 6 targets when
  // the consumer omits it (Plan 16-01 prop-default coercion fix); the check is
  // a plain null compare — NO runtime callable-type coercion. Without
  // `labelFor` or a `label` field, the row's text (`row`), else `String(item)`
  // for a primitive, else `item {position}`.
  labelOf = (item: any, idx: any, row: HTMLElement | null = null) => {
  if (this.labelFor !== null) return this.labelFor(item, idx);
  if (item !== null && typeof item === 'object' && item.label != null) return item.label;
  return fallbackLabel(item, idx, row);
};

  // The text this list's live region showed last (see the registry entry's
  // `announce`).
  lastSpoken = '';

  // Keyboard handler (Phase 16 R7): Space/Enter lift and drop; while lifted,
  // ArrowUp/ArrowDown (ArrowLeft/ArrowRight when horizontal), Home/End and
  // PageUp/PageDown move the row, and Escape returns it to where it was lifted
  // from. The lift itself lives in the shared keyboard registry. After
  // any array-reorder write, refocusRow() keeps focus on the moved row (or its
  // handle) on all six targets.
  //
  // Note: `index` is passed directly as a number. Plan 16-02 (Solid call-arg
  // accessor unwrap) ensures Solid's <For> alias unwraps to `index()` at the
  // call site — no runtime callable-type coercion needed in user source.
  // Keyboard reordering is available only when the list is not disabled AND the
  // `disableKeyboard` opt-out is off. Drives BOTH the row tabindex (rows are
  // focusable only when reorderable) and the onRowKeyDown guard below. Reads
  // straight off $props so the tabindex binding re-evaluates reactively when
  // `disabled`/`disableKeyboard` toggle at runtime.
  //
  // The keyboard follows the SortableJS options the mouse obeys: `disabled`
  // (the prop, `options.disabled`, or `option('disabled', v)`), `filter` and
  // `draggable` (which rows lift, see rowLiftable) and `sort: false` (no moves
  // within the list). `liveOption` reads the value SortableJS runs with: one set
  // at runtime, else `options`, else the named prop.
  KEYBOARD_OPTIONS = ['disabled', 'filter', 'draggable', 'sort'];

  liveOption = (name: any, fallback: any) => {
  const ov: any = this._optionOverrides.value;
  if (ov != null && Object.prototype.hasOwnProperty.call(ov, name)) return ov[name];
  const o: any = this.options;
  if (o != null && o[name] !== undefined) return o[name];
  return fallback;
};

  setOverride = (name: any, value: any) => {
  this._optionOverrides.value = {
    ...this._optionOverrides.value,
    [name]: value
  };
};

  clearOverride = (name: any) => {
  const ov: any = this._optionOverrides.value;
  if (ov == null || !Object.prototype.hasOwnProperty.call(ov, name)) return;
  const next = {
    ...ov
  };
  delete next[name];
  this._optionOverrides.value = next;
};

  // Options whose runtime value (`option(name, v)`) is remembered, so a later
  // change of the matching prop doesn't overwrite it: the keyboard ones, plus
  // `animation`, `handle` and `group` (runtime override → `options` → prop).
  TRACKED_OPTIONS = [...this.KEYBOARD_OPTIONS, 'animation', 'handle', 'group'];

  keyboardEnabled = () => !this.disableKeyboard && !this.liveOption('disabled', this.disabled);

  // The handle selector SortableJS runs with (`option('handle', v)`, else
  // `options.handle`, else the `handle` prop): the keyboard reads the same one.
  handleSelector = () => this.liveOption('handle', this.handle);

  // keyboardTrigger='handle' mode: rows are not tab stops and the keys are read
  // from the consumer's handle element instead. Any other value is 'row' mode.
  handleMode = () => this.keyboardTrigger === 'handle';

  // Rows are tab stops only in row mode (and only while keyboard is enabled).
  rowTabbable = () => this.keyboardEnabled() && !this.handleMode();

  // One-time-per-change dev warning: handle mode needs a handle selector. Without
  // one the keyboard is OFF (see the onRowKeyDown gate) — never a silent fallback
  // to row mode, which would re-introduce the tab stops the consumer opted out of.
  warnIfHandleMissing = () => {
  if (this.handleMode() && this.handleSelector() == null) {
    console.warn('[rozie-sortable-list] keyboardTrigger is "handle" but no handle selector is set, so keyboard reordering is off. Pass a handle selector (e.g. handle=".grip") or use keyboardTrigger "row".');
  }
};

  // True only when a keydown originated inside a `handle` element that belongs to
  // THIS row. Walks the COMPOSED ancestor chain from the event target up to (but
  // excluding) the row (currentTarget): assignedSlot -> parentNode -> shadow host.
  // Plain closest()/contains() stop at a shadow boundary, and Lit renders a Rozie
  // consumer's slot content inside the SortableList shadow root while plain-HTML
  // consumers project light-DOM nodes through a <slot>. composedPath() is not
  // used because React's synthetic event does not expose it. Another
  // .rozie-sortable-item met first means the key came from a NESTED list's row,
  // which must not reorder this (outer) list.
  isHandleKeyOrigin = ($event: any) => {
  const sel = this.handleSelector();
  if (sel == null) return false;
  const row = $event.currentTarget;
  let n: any = $event.target;
  while (n && n !== row) {
    if (n.nodeType === 1) {
      if (n.matches(sel)) {
        // Matched a handle: it counts only if this row is reachable from here
        // without crossing a different sortable item.
        let m: any = n.assignedSlot ?? n.parentNode ?? n.host;
        while (m && m !== row) {
          if (m.nodeType === 1 && m.classList.contains('rozie-sortable-item')) return false;
          m = m.assignedSlot ?? m.parentNode ?? m.host;
        }
        return m === row;
      }
      if (n.classList.contains('rozie-sortable-item')) return false;
    }
    n = n.assignedSlot ?? n.parentNode ?? n.host;
  }
  return false;
};

  // Put focus back on the MOVED row (row mode) or its handle (handle mode) after
  // a reorder write. Looks the row up by KEY (data-id), not by index, so it finds
  // the moved row whether this runs before the framework commit (the row element
  // is the same one) or after it (Svelte/Solid/Lit re-create the DOM) — and it is
  // correct for index-keyed primitive lists too. Direct children of the list
  // container only: that skips nested-list rows and the header/footer slot
  // content.
  //
  // Two passes. (1) A microtask covers targets that commit synchronously or in an
  // earlier microtask (Vue's scheduler flush is queued by the model write, before
  // this one). (2) A timer + rAF "heal" pass covers targets whose DOM commit is
  // scheduled AFTER the key handler returns (Angular): the commit can MOVE the
  // focused row, and moving a focused node blurs it, so a Home/End/Escape jump or
  // a rapid Space/Arrow/Arrow/Space burst would otherwise end with focus on
  // <body>. The heal pass never steals: it acts only when focus has been lost to
  // <body>. (`$restoreFocus(selector, index)` is not enough here: it is a no-op on
  // Vue/Angular, where a long jump moves the focused row itself, and it looks the
  // row up by index, which can land on a neighbour on Lit.) The $refs read
  // happens here, synchronously, inside an event handler — which is safe.
  refocusRow = (item: any, idx: any) => {
  const listEl = this._refListEl;
  const sel = this.handleSelector();
  const useHandle = this.handleMode();
  const key = String(this.keyFor(item, idx));
  // While this refocus is outstanding, a key that falls to <body> belongs to
  // the lift (see onStrayKey). Cleared once the row has focus again, or by a
  // pointer press anywhere.
  const pending = this.registry.lift;
  if (pending != null) pending.focusPending = true;
  const focusIt = (onlyIfLost: any) => {
    if (!listEl) return;
    if (useHandle && sel == null) return;
    if (onlyIfLost && document.activeElement && document.activeElement !== document.body) return;
    for (const row of Array.from(listEl.children) as any[]) {
      if (row.getAttribute('data-id') === key) {
        const target = useHandle ? row.querySelector(sel) : row;
        if (target && typeof target.focus === 'function') {
          target.focus();
          const l = this.registry.lift;
          if (l != null && l === pending && l.key === key) {
            l.focusPending = false;
            // This row is the lifted row element now (see the items watcher).
            l.liftedRowEl = row;
          }
        }
        return;
      }
    }
  };
  queueMicrotask(() => focusIt(false));
  setTimeout(() => focusIt(true), 0);
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => focusIt(true));
};

  // `el` in an event payload: the row element while it is in the page, else
  // null (a row that left with an unmounted list is no row of any list).
  liveEl = (el: any) => el != null && el.isConnected ? el : null;

  // The row element carrying `data-id === key` among a list element's direct
  // children (skips nested-list rows and header/footer slot content).
  rowByKey = (listEl: any, key: any) => {
  if (!listEl || key == null) return null;
  for (const row of Array.from(listEl.children) as any[]) {
    if (row.getAttribute('data-id') === key) return row;
  }
  return null;
};

  // After the consumer changed the items of the list holding a lift, put focus
  // on the row (or its handle) whose key is `key`, else the row nearest `index`
  // (or the list itself when it has no rows left) — but only once focus has fallen to <body> (the focused row's element went
  // away: the lift was lost, or a framework that keys rows by object identity
  // re-created the lifted row). Never steals focus from anywhere else. Same
  // three passes as refocusRow, for targets that commit late.
  focusNearRow = (index: number, key: string | null = null) => {
  const listEl = this._refListEl;
  const sel = this.handleSelector();
  const useHandle = this.handleMode();
  const focusIt = () => {
    if (!listEl) return;
    if (useHandle && sel == null) return;
    if (document.activeElement && document.activeElement !== document.body) return;
    const rows = Array.from(listEl.children).filter((r: any) => r.hasAttribute('data-id') && r.classList.contains('rozie-sortable-item')) as any[];
    if (rows.length === 0) {
      // The list is now empty: focus the list itself (out of the tab order)
      // so keyboard and screen-reader users stay where they were.
      if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
      listEl.focus();
      return;
    }
    const row = rows.find((r: any) => key != null && r.getAttribute('data-id') === key) ?? rows[Math.max(0, Math.min(rows.length - 1, index))];
    const target = useHandle ? row.querySelector(sel) : row;
    if (target && typeof target.focus === 'function') target.focus();
  };
  queueMicrotask(focusIt);
  setTimeout(focusIt, 0);
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(focusIt);
};

  // Speak `text` from `target`'s aria-live region. The region that spoke last
  // is cleared when it belongs to another list, so a message is heard once, from
  // the list the row is in now, and never from a list that just lost it.
  speak = (target: any, text: any) => {
  const prev = this.registry.speaker;
  if (prev != null && prev !== target && this.registry.has(prev)) prev.announce('');
  this.registry.speaker = target;
  target.announce(text);
};

  // Say announcement `kind` from `target`, in `target`'s words: its
  // `announcements` function for that kind, else the default text (see
  // ./internal/announcements). `index` is the row's 0-based position in
  // `target`, `row` the row element its label is read from (when there is no
  // `labelFor` or `label` field), and `total` how many rows `target` holds after
  // the change (null for the kinds without a position). A function returning
  // null or '' clears the region, so nothing is said.
  say = (target: any, kind: AnnouncementKind, item: unknown, index: number, row: HTMLElement | null, total: number | null = null, fromList: any = null) => {
  const ctx: any = {
    item,
    list: this.registry.listName(target)
  };
  // The label is read only when the text needs it (a default with `{label}`,
  // or an override that reads `label`), so `labelFor` is not called for a
  // message that doesn't name the row (`Lift ended`: the item has left).
  let label: string | null = null;
  Object.defineProperty(ctx, 'label', {
    enumerable: true,
    get: () => {
      if (label === null) label = target.labelOf(item, index, row);
      return label;
    }
  });
  if (total != null) {
    ctx.position = index + 1;
    ctx.total = total;
  }
  if (fromList != null) ctx.fromList = this.registry.listName(fromList);
  this.speak(target, target.message(kind, ctx));
};

  // The lifted item is no longer in the list holding it: the consumer changed
  // that list's items (or re-keyed the item), or the list is unmounting. End the
  // lift without writing anything (the item is wherever the consumer's data put
  // it). `end` still fires once, with `item` = the lifted value and `el: null`
  // (there is no row), so keyboard `start` / `end` pair (unless the holder and the origin have both unmounted). Lost to a consumer change (not an
  // unmount), the holder says `Lift ended` and, if focus fell to <body> with the
  // row, focuses its row nearest where the lifted row was.
  loseLift = (unmounting = false) => {
  const lift = this.registry.lift;
  if (!lift) return;
  const h = lift.holder;
  this.registry.lift = null;
  h.setLifted(null);
  if (!unmounting) {
    this.say(h, 'liftEnded', lift.item, lift.index ?? lift.origin.index, lift.liftedRowEl);
    h.focusNear(lift.index ?? lift.origin.index);
  }
  const payload = {
    interaction: 'keyboard' as const,
    item: lift.item,
    el: null,
    from: lift.origin.list.el,
    to: h.el,
    oldIndex: lift.origin.index,
    newIndex: -1
  };
  // Like every `end`, in a task after the writes, from the holder. An
  // unmounted list never emits (Angular rejects an emit from a destroyed
  // component): when the holder is unmounting, the origin list (which emitted
  // `start`) ends the lift if it is still mounted, so `start` and `end` pair;
  // if it is gone too, nothing is emitted.
  this.registry.deferEnd((host: any) => host.emit('end', payload), h, lift.origin.list);
};

  // Keyboard `start` / `end` (the same payload as every other event): `item` is
  // the item value, `el` its row element. `start` fires from the origin list
  // (`from`), `end` from the list the row ends up in (`to`). `el` is the row in
  // that list when it is rendered, else `fallbackEl` (the row element the move
  // started from, before a target re-rendered). `end` is called after
  // `registry.lift` is cleared, so a consumer `end` handler that writes the
  // items (re-keying a clone copy) is not mistaken for a lost lift, and it is
  // emitted in a task (`registry.deferEnd`), after the writes AND the re-render
  // they schedule: a consumer `end` handler reads the new state on every target
  // (React included, whose handler closure is the one from the latest render).
  // If `to` has unmounted by then, `from` (the origin, which emitted `start`)
  // emits it instead, `to` unchanged in the payload; an unmounted list never
  // emits.
  keyboardStartEnd = (name: any, lift: any, from: any, to: any, oldIndex: any, newIndex: any, fallbackEl: HTMLElement | null = null) => {
  const fire = (host: any) => host.emit(name, {
    interaction: 'keyboard',
    item: lift ? lift.item : null,
    el: (lift && host === to ? this.rowByKey(host.el, lift.key) : null) ?? this.liveEl(fallbackEl),
    from: from.el,
    to: to.el,
    oldIndex,
    newIndex
  });
  if (name === 'end') this.registry.deferEnd(fire, to, from);else fire(from);
};

  // Move the lifted row to `toIndex` (clamped) within the list holding it.
  // Works through the registry entry, so it acts on the current holder. `dir`
  // is the key's direction (-1 toward the start), for when the row can't move.
  moveLiftTo = (toIndex: any, dir: any) => {
  const lift = this.registry.lift;
  if (!lift) return;
  const h = lift.holder;
  const from = this.registry.indexOfLift();
  if (from < 0) {
    this.loseLift();
    return;
  }
  const items = h.items();
  const to = Math.max(0, Math.min(items.length - 1, toIndex));
  // The moved row's element, read before the write (an index key changes).
  const el = h.rowEl(from);
  if (to === from) {
    // Nowhere to go: say so (the row is already at that end).
    this.say(h, dir < 0 ? 'atStart' : 'atEnd', items[from], from, el ?? lift.liftedRowEl, items.length);
    return;
  }
  const next = [...items];
  const [moved] = next.splice(from, 1);
  next.splice(to, 0, moved);
  // Index keys (primitive items without itemKey) change with the position.
  // Update the lift BEFORE writing: a target whose watchers run synchronously
  // on the write must already see where the row is going.
  lift.key = h.keyOf(moved, to);
  lift.index = to;
  h.write(next);
  h.setLifted(to);
  // Name the row that MOVED from the local `moved` item: on React/Vue/Lit the
  // items prop still holds the pre-write array here. Labels come from the
  // holder's own `labelFor`.
  this.say(h, 'moved', moved, to, el, items.length);
  h.focusRow(moved, to);
  h.emit('reorder', {
    interaction: 'keyboard',
    item: moved,
    el,
    from: h.el,
    to: h.el,
    oldIndex: from,
    newIndex: to
  });
};

  // Hop the lifted row to the next (`dir` 1) or previous (-1) list it could
  // also reach by mouse, in composed-tree source order. One hand-off: the source
  // writes its items without the row, the destination writes them with it, and
  // the destination becomes the holder. As with the mouse, the destination
  // emits `add` first, then the source emits `remove`. A forward hop lands
  // first, a backward hop lands last.
  hop = (dir: any) => {
  const lift = this.registry.lift;
  if (!lift) return;
  const from = lift.holder;
  const i = this.registry.indexOfLift();
  if (i < 0) {
    this.loseLift();
    return;
  }
  const fromItems = from.items();
  const data = fromItems[i];
  const el = from.rowEl(i);
  // Keep the lifted row element current: lists nested inside it (a grid
  // widget's columns) are never hop targets. Before a target re-renders the
  // row may not exist yet, so keep the last known element then.
  lift.liftedRowEl = el ?? lift.liftedRowEl;
  const to = this.registry.findHopTarget(from, dir);
  if (to == null) {
    this.say(from, dir === 1 ? 'noListAfter' : 'noListBefore', data, i, el ?? lift.liftedRowEl);
    return;
  }
  const origin = lift.origin;
  const toItems = to.items();
  // A clone copy hopping back into the list it was cloned from merges with
  // its original there (that list never gave it up), rather than adding a
  // second row with the same key.
  if (lift.copy && to === origin.list) {
    let home = toItems.indexOf(data);
    if (home < 0) home = Math.max(0, Math.min(toItems.length - 1, origin.index));
    lift.holder = to;
    lift.copy = false;
    lift.key = to.keyOf(toItems[home], home);
    lift.item = toItems[home];
    lift.index = home;
    const rest = [...fromItems];
    rest.splice(i, 1);
    from.write(rest);
    from.emit('remove', {
      interaction: 'keyboard',
      item: data,
      el,
      from: from.el,
      to: to.el,
      oldIndex: i,
      newIndex: -1
    });
    from.setLifted(null);
    to.setLifted(home);
    this.say(to, 'movedToList', data, home, el, toItems.length, from);
    to.focusRow(toItems[home], home);
    return;
  }
  // The first hop out of a clone source (`pull: 'clone'`) leaves the source
  // untouched and carries a copy (the same item value the mouse path
  // inserts); from then on the copy moves like any row.
  const cloneOut = canHop(from.group(), to.group()).copy && from === origin.list && !lift.copy;
  const at = dir === 1 ? 0 : toItems.length;
  // Update the lift BEFORE writing, so a target whose watchers run
  // synchronously on a write already sees the new holder.
  lift.holder = to;
  lift.key = to.keyOf(data, at);
  lift.index = at;
  lift.hopped = true;
  if (cloneOut) {
    lift.copy = true;
  } else {
    const rest = [...fromItems];
    rest.splice(i, 1);
    from.write(rest);
  }
  const next = [...toItems];
  next.splice(at, 0, data);
  to.write(next);
  // The destination has not rendered its new row yet: `el` is the row the
  // move started from. `add` (destination) before `remove` (source), as by
  // mouse.
  to.emit('add', {
    interaction: 'keyboard',
    item: data,
    el,
    from: from.el,
    to: to.el,
    oldIndex: -1,
    newIndex: at
  });
  if (!cloneOut) from.emit('remove', {
    interaction: 'keyboard',
    item: data,
    el,
    from: from.el,
    to: to.el,
    oldIndex: i,
    newIndex: -1
  });
  from.setLifted(null);
  to.setLifted(at);
  this.say(to, 'movedToList', data, at, el, toItems.length + 1, from);
  to.focusRow(data, at);
};

  // End the active keyboard lift. 'drop' leaves the row where it is ('off' too,
  // announced as `Lift ended`: the holder's keyboard was turned off); 'cancel'
  // returns it to the list and position it was lifted from (after hops, a
  // reverse hand-off with its own `remove` / `add`; a clone copy is removed).
  // Emits `end` once, from the list the row ends up in.
  endLift = (kind: any) => {
  const lift = this.registry.lift;
  if (!lift) return;
  const h = lift.holder;
  const origin = lift.origin;
  const at = this.registry.indexOfLift();
  if (at < 0) {
    this.loseLift();
    return;
  }
  const items = h.items();
  const item = items[at];
  // The lifted row's element, read before any write below. Right after a hop
  // the holder may not have rendered it yet: its label is read from the
  // lifted row element then.
  const el = h.rowEl(at);
  const row = el ?? lift.liftedRowEl;
  if (kind === 'drop' || kind === 'off') {
    // A row that hopped always names its list, even back in its origin. The
    // keyboard turned off mid-lift ('off') ends it where it is, too.
    if (kind === 'off') this.say(h, 'liftEnded', item, at, row);else this.say(h, lift.hopped ? 'droppedInList' : 'dropped', item, at, row, items.length);
    h.setLifted(null);
    this.registry.lift = null;
    this.keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
    return;
  }
  if (h !== origin.list && !this.registry.has(origin.list) && lift.copy) {
    // A clone copy is removed on cancel even when its source list has
    // unmounted (the source never gave its item up). Focus moves to the
    // neighbouring row, if any. The lift ends BEFORE the write: the copy is
    // leaving on purpose, and a target whose items watcher runs synchronously
    // on the write (Solid) must not take it for a lost lift (a second `end`).
    this.registry.lift = null;
    const rest = [...items];
    rest.splice(at, 1);
    h.write(rest);
    h.emit('remove', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: h.el,
      oldIndex: at,
      newIndex: -1
    });
    h.setLifted(null);
    this.say(h, 'cancelledRemoved', item, at, row);
    if (rest.length > 0) {
      const k = Math.min(at, rest.length - 1);
      h.focusRow(rest[k], k);
    }
    // The copy is gone, so there is no row: `el: null`.
    const fromEl = origin.list.el;
    this.registry.deferEnd((host: any) => host.emit('end', {
      interaction: 'keyboard',
      item,
      el: null,
      from: fromEl,
      to: h.el,
      oldIndex: origin.index,
      newIndex: -1
    }), h, origin.list);
    return;
  }
  if (h !== origin.list && (!this.registry.has(origin.list) || !isRenderable(origin.list.el) || !origin.list.keyboardEnabled())) {
    // The origin list has unmounted, is hidden, or has its keyboard off:
    // there is nowhere to return to (focus would be stranded), so the row
    // stays where it is (the lift ends as a drop at its position).
    this.say(h, 'cancelledStays', item, at, row, items.length);
    h.setLifted(null);
    this.registry.lift = null;
    this.keyboardStartEnd('end', lift, origin.list, h, origin.index, at, el);
    return;
  }
  if (h === origin.list) {
    const to = Math.max(0, Math.min(items.length - 1, origin.index));
    if (to !== at) {
      const next = [...items];
      next.splice(at, 1);
      next.splice(to, 0, item);
      lift.key = h.keyOf(item, to);
      h.write(next);
      h.focusRow(item, to);
      h.emit('reorder', {
        interaction: 'keyboard',
        item,
        el,
        from: h.el,
        to: h.el,
        oldIndex: at,
        newIndex: to
      });
    }
    this.say(h, lift.hopped ? 'cancelledReturnedToList' : 'cancelledReturned', item, to, row, items.length);
    h.setLifted(null);
    this.registry.lift = null;
    this.keyboardStartEnd('end', lift, origin.list, h, origin.index, to, el);
    return;
  }
  // Reverse hand-off from the current holder back to the origin list.
  const home = origin.list;
  const homeItems = home.items();
  let back;
  if (lift.copy) {
    // The clone source never gave its item up: drop the copy, focus the
    // original.
    back = homeItems.indexOf(item);
    if (back < 0) back = Math.max(0, Math.min(homeItems.length - 1, origin.index));
  } else {
    back = Math.min(origin.index, homeItems.length);
  }
  lift.holder = home;
  lift.key = home.keyOf(item, back);
  const rest = [...items];
  rest.splice(at, 1);
  h.write(rest);
  if (!lift.copy) {
    const next = [...homeItems];
    next.splice(back, 0, item);
    home.write(next);
    // `add` (destination) before `remove` (source), as by mouse.
    home.emit('add', {
      interaction: 'keyboard',
      item,
      el,
      from: h.el,
      to: home.el,
      oldIndex: -1,
      newIndex: back
    });
  }
  h.emit('remove', {
    interaction: 'keyboard',
    item,
    el,
    from: h.el,
    to: home.el,
    oldIndex: at,
    newIndex: -1
  });
  h.setLifted(null);
  // `home` holds the lift during its write, so a target whose items watcher
  // runs synchronously on the write (Solid) highlighted the row there: clear it.
  home.setLifted(null);
  this.say(home, 'cancelledReturnedToList', item, back, row, homeItems.length + (lift.copy ? 0 : 1));
  home.focusRow(lift.copy ? homeItems[back] : item, back);
  this.registry.lift = null;
  this.keyboardStartEnd('end', lift, home, home, origin.index, back, lift.copy ? home.rowEl(back) : el);
};

  // This list's keyboard was turned off (`disabled`, `disableKeyboard`, or
  // `option('disabled', true)`): a lift it holds ends where the row is, with
  // its `end`.
  endLiftIfHeld = () => {
  const lift = this.registry.lift;
  if (lift != null && lift.holder === this.entry) this.endLift('off');
};

  // In row mode the rows leave the tab order when the keyboard turns off, and a
  // focused element that stops being focusable drops focus to <body>. If one of
  // this list's rows still has focus (a target whose watcher runs before its DOM
  // update), move it to the list itself (out of the tab order), like an emptied
  // list. Once the DOM update has run, the `focusout` listener added in $onMount
  // does it instead.
  keepFocusOffBody = () => {
  const listEl = this.entry ? this.entry.el : null;
  if (!listEl) return;
  const root: any = listEl.getRootNode();
  const a: any = root != null ? root.activeElement : null;
  if (a == null || a.parentNode !== listEl || !a.classList.contains('rozie-sortable-item')) return;
  if (!listEl.hasAttribute('tabindex')) listEl.setAttribute('tabindex', '-1');
  listEl.focus();
};

  keyboardTurnedOff = () => {
  this.endLiftIfHeld();
  this.keepFocusOffBody();
};

  // Lift the row at `index` of this list.
  startLift = (index: any) => {
  if (!this.entry) return;
  // A previous drag's or lift's `end` that is still pending fires first, so
  // every `end` comes before the next `start`.
  this.registry.flushEnds();
  const item = this.items[index];
  this.registry.lift = {
    holder: this.entry,
    key: this.entry.keyOf(item, index),
    item,
    copy: false,
    hopped: false,
    origin: {
      list: this.entry,
      index
    },
    liftedRowEl: this.entry.rowEl(index),
    index
  };
  this._liftedIndex.value = index;
  this.say(this.entry, 'lifted', item, index, this.registry.lift.liftedRowEl, this.items.length);
  this.keyboardStartEnd('start', this.registry.lift, this.entry, this.entry, index, index);
};

  onRowKeyDown = ($event: any, index: any) => {
  // Origin guard — must run FIRST, before the keyboardEnabled() check.
  //  - handle mode (keyboardTrigger='handle'): reorder keys apply ONLY when the
  //    keydown came from inside this row's `handle` element. A missing `handle`
  //    selector means keyboard is OFF (warned in warnIfHandleMissing).
  //  - row mode (quick 260716-ggq): reorder keys apply ONLY when the row
  //    element ITSELF is focused. A slotted interactive child (an <input>,
  //    <button>, etc. rendered into the row's default slot) bubbles its own
  //    keydown up to this handler — without this guard, Space/Enter typed into
  //    that child would be hijacked for lift/drop instead of reaching the
  //    child.
  if (this.handleMode()) {
    if (this.handleSelector() == null || !this.isHandleKeyOrigin($event)) return;
  } else if ($event.target !== $event.currentTarget) {
    return;
  }
  // Defense-in-depth: when keyboard reordering is off the rows carry no
  // tabindex and can't receive focus, but a consumer-focused row (or a
  // programmatic .focus()) must still no-op here rather than reorder.
  if (!this.keyboardEnabled()) return;
  // While a lift exists, reorder keys in the list holding it act on it. A key
  // from ANOTHER list of the holder's group is routed to the holder only when
  // it comes from the lifted row element itself (its old row, still there
  // before the frameworks re-render after a hop; compared by element, so a
  // row of another list that shares the lifted row's key is not it) or while a refocus after a move is
  // outstanding (a fast burst). Any other row — and every row of an unrelated
  // list (another group, or none) — keeps single-list behaviour: Space/Enter
  // there drops the foreign lift and lifts its own row, other keys do nothing.
  const lift = this.registry.lift;
  const key = $event.key;
  if (lift != null) {
    const mine = this.groupNameOf(this.effectiveGroup());
    const sameGroup = mine != null && mine === this.groupNameOf(lift.holder.group());
    const fromLiftedRow = lift.liftedRowEl != null && $event.currentTarget === lift.liftedRowEl;
    if (lift.holder === this.entry || sameGroup && (fromLiftedRow || lift.focusPending === true)) {
      if (lift.holder.onKey(key, !!$event.shiftKey)) $event.preventDefault();
      return;
    }
  }
  // Space (' ' on browsers; KeyboardEvent.key === ' ') OR Enter — lift. A row
  // the mouse can't drag (it matches `filter`, or not `draggable`) can't be
  // lifted either: the key is left alone (not prevented).
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    const rules = {
      filter: this.liveOption('filter', this.filter),
      draggable: this.liveOption('draggable', undefined),
      sortable: this.instance
    };
    if (!rowLiftable($event.currentTarget as any, rules)) return;
    $event.preventDefault();
    if (lift != null) this.endLift('drop');
    this.startLift(index);
  }
};

  // The group NAME of a SortableJS group option (string or object form).
  groupNameOf = (g: any) => g == null ? null : typeof g === 'string' ? g : g.name ?? null;

  // A reorder key for the lift THIS list holds (routed here from any list via
  // the registry entry's onKey). Returns true when the key was handled. Every
  // key except Space/Enter acts only while lifted, so it never steals keys from
  // fields inside a row.
  holderKey = (key: any, shift: any) => {
  const lift = this.registry.lift;
  if (lift == null || lift.holder !== this.entry) return false;
  if (key === ' ' || key === 'Spacebar' || key === 'Enter') {
    this.endLift('drop');
    return true;
  }
  if (key === 'Escape') {
    this.endLift('cancel');
    return true;
  }
  const horizontal = this.orientation === 'horizontal';
  const prevKey = horizontal ? 'ArrowLeft' : 'ArrowUp';
  const nextKey = horizontal ? 'ArrowRight' : 'ArrowDown';
  if (shift && (key === nextKey || key === prevKey)) {
    // Hopping is on wherever a group is set; an ungrouped list ignores it.
    if (this.effectiveGroup() == null) return false;
    this.hop(key === nextKey ? 1 : -1);
    return true;
  }
  const from = this.registry.indexOfLift();
  if (from < 0) {
    this.loseLift();
    return false;
  }
  // pageStep below 1 (or not a number) still moves by at least one position.
  const step = Math.max(1, Math.floor(Number(this.pageStep) || 1));
  let to: any = null;
  if (key === nextKey) to = from + 1;else if (key === prevKey) to = from - 1;else if (key === 'Home') to = 0;else if (key === 'End') to = this.entry.items().length - 1;else if (key === 'PageDown') to = from + step;else if (key === 'PageUp') to = from - step;
  if (to === null) return false;
  // `sort: false`: no moves within the list (as by mouse). The key is still
  // taken, so it does not scroll the page while a row is lifted, and says why
  // nothing moved.
  if (this.liveOption('sort', true) === false) {
    this.say(this.entry, 'notSortable', this.entry.items()[from], from, this.entry.rowEl(from) ?? lift.liftedRowEl);
    return true;
  }
  this.moveLiftTo(to, key === prevKey || key === 'Home' || key === 'PageUp' ? -1 : 1);
  return true;
};

  // A key pressed while focus has fallen to <body> during a lift. A hop removes
  // the focused row from one list and the destination may render (and take
  // focus) only after the handler returns (Angular), so the next key of a fast
  // burst can reach <body>. The list holding the lift handles it as if it had
  // landed on the lifted row, then puts focus back on that row.
  //
  // Only while a refocus of ours is outstanding (`focusPending`): focus that left
  // the lifted row for any other reason (the user clicked elsewhere or tabbed
  // away) keeps today's behaviour, and those keys are not ours. Modified keys
  // and keys someone already handled are never taken.
  onStrayKey = (ev: any) => {
  const lift = this.registry.lift;
  if (lift == null || lift.holder !== this.entry || !lift.focusPending) return;
  if (ev.defaultPrevented || ev.ctrlKey || ev.metaKey || ev.altKey) return;
  const t = ev.target;
  if (t !== document.body && t !== document.documentElement) return;
  const item = lift.item;
  const at = this.registry.indexOfLift();
  if (!this.holderKey(ev.key, !!ev.shiftKey)) return;
  ev.preventDefault();
  const now = this.registry.lift;
  if (now != null) now.holder.focusRow(now.item, this.registry.indexOfLift());else if (at >= 0) this.entry.focusRow(item, at);
};

  // SortableJS wiring lives in `useSortableJS()` (./internal/useSortableJS).
  // The helper owns the SortableJS-vs-reconciler dance — DOM-restore hardening
  // against fragile-event paths, identity-based item lookup over fragile
  // `e.oldIndex`, and the single-onEnd disambiguation that collapses
  // onUpdate / onAdd / onRemove into one handler.
  //
  // What stays here is purely declarative: which array to read, what to write
  // back, what to emit, and how to bridge `afterCommit` to the Lit-only
  // `$reconcileAfterDomMutation()` sigil.
  // `options.group` wins over `group` / `cloneable` (see effectiveGroup), for
  // the mouse as for the keyboard.
  // A group change can change which lists can take each other's rows: every
  // list rechecks its Shift instructions.
  applyGroup = () => {
  this.instance?.option('group', this.effectiveGroup());
  this.registry.notifyPeers();
};

  // Imperative handle (Phase 21 $expose). The SortableJS imperative surface a
  // consumer can't drive through props alone — exposed uniformly to all 6 targets.
  // Each guards the pre-mount/destroyed `instance = null`. Collision-clear: none of
  // the 4 verb names collide with the 16 props or the 5 events — `option` is a
  // distinct identifier from the `options` prop, so ROZ121 is clear.
  getInstance() {
    return this.instance;
  }

  // toArray()/sort() use the rows' data-id keys — every row carries
  // :data-id="keyFor(item, index)", so toArray() returns the current key order
  // (set itemKey for stable object-list keys).
  toArray() {
    return this.instance ? this.instance.toArray() : [];
  }

  // sort(order) reorders the bound items by those keys and writes them back
  // (the framework re-renders the rows; SortableJS never moves them behind the
  // model). Listed keys come first, in order; the rest follow in their order. No
  // event fires: it is the consumer's own call. With `useAnimation` (and a
  // non-zero `animation`) the rows slide from where they were.
  sort(order: any, useAnimation = true) {
    const list = this.items;
    const next = orderByKeys(list, order ?? [], this.keyFor);
    if (next.every((item: any, i: any) => item === list[i])) return;
    const animate = useAnimation && this.instance != null;
    if (animate) this.instance.captureAnimationState();
    this._itemsControllable.write(next);
    if (animate) {
      const sortable = this.instance;
      afterFlush(() => sortable.animateAll());
    }
  }

  // option(name) reads a live SortableJS option; option(name, value) sets one — the
  // runtime escape hatch for any SortableJS option beyond the curated props.
  // Setting `disabled`, `filter`, `draggable` or `sort` also applies to the
  // keyboard; `option('disabled', true)` mid-lift ends the lift this list holds.
  // A runtime `animation` is kept over later `animation` prop changes.
  option(name: any, value: any) {
    if (!this.instance) return undefined;
    if (value === undefined) return this.instance.option(name);
    this.instance.option(name, value);
    if (this.TRACKED_OPTIONS.includes(name)) this.setOverride(name, value);
    if (name === 'disabled' && value) this.keyboardTurnedOff();
    // After the re-render, so every list reads the new group (React reads
    // state as of its last render).
    if (name === 'group') afterFlush(() => this.registry.notifyPeers());
    return value;
  }

  get items(): any[] { return this._itemsControllable.read(); }
  set items(v: any[]) { this._itemsControllable.notifyPropertyWrite(v); }

  addEventListener<K extends keyof RozieSortableListEventMap>(type: K, listener: (this: SortableList, ev: RozieSortableListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
  addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
  addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void {
    super.addEventListener(type, listener, options);
  }
  removeEventListener<K extends keyof RozieSortableListEventMap>(type: K, listener: (this: SortableList, ev: RozieSortableListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
  removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
  removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void {
    super.removeEventListener(type, listener, options);
  }

  /**
   * Plan 14-05 — cross-framework attribute fallthrough source. Reads the
   * host custom element's attributes on each call so a consumer-side bound
   * attribute flows through on every render. The `rozieSpread` directive
   * (D-02) does the cross-render diff downstream.
   *
   * Phase 15 follow-up Bug A — declared-prop attribute names are filtered
   * out so `$attrs` returns "rest after declared props" (semantic parity
   * with React/Vue/Svelte/Solid/Angular). Both Lit attribute-naming
   * forms are folded into the skip set: kebab-case for model props
   * (explicit `attribute:`) AND lowercased property name (Lit's default).
   *
   * command-palette-per-level-virtual / portal-through-portal cluster —
   * `data-rozie-ref` is ALWAYS skipped too (a reserved compiler bookkeeping
   * attribute, never a consumer prop) so a parent-assigned `ref=` on this
   * component's own host tag can never clobber this component's OWN
   * internal `data-rozie-ref` ref markers via fallthrough re-application.
   */
  private get $attrs(): Record<string, string> {
    const __skip = new Set<string>(['data-rozie-ref', 'items', 'item-key', 'itemkey', 'handle', 'group', 'animation', 'disabled', 'disable-keyboard', 'disablekeyboard', 'keyboard-trigger', 'keyboardtrigger', 'options', 'label-for', 'labelfor', 'ghost-class', 'ghostclass', 'chosen-class', 'chosenclass', 'drag-class', 'dragclass', 'filter', 'easing', 'force-fallback', 'forcefallback', 'swap-threshold', 'swapthreshold', 'cloneable', 'list-class', 'listclass', 'item-class', 'itemclass', 'list-label', 'listlabel', 'orientation', 'page-step', 'pagestep', 'keyboard-instructions', 'keyboardinstructions', 'announcements', 'item-style', 'itemstyle']);
    const out: Record<string, string> = {};
    for (const a of Array.from(this.attributes)) {
      if (__skip.has(a.name)) continue;
      out[a.name] = a.value;
    }
    return out;
  }

  /**
   * Phase 15 D-19 — consumer-passed listener cluster placeholder.
   * Lit attaches event listeners directly on the host element via
   * `addEventListener` (no per-instance prop rest binding), so the
   * runtime value is undefined; the `rozieListeners` directive's
   * nullish coercion (`obj ?? {}`) handles the no-op cleanly.
   * The declaration exists to satisfy `tsc --noEmit` on consumer
   * projects with strict mode — bare `$listeners` in `render()`
   * would otherwise raise TS2304 (Cannot find name).
   */
  private get $listeners(): Record<string, EventListener> | undefined {
    return undefined;
  }
}

Demo source — SortableListDemo.rozie ​

rozie
<!--
  SortableListDemo.rozie — companion consumer for SortableList.

  The whole point of writing the demo IN Rozie: a single source compiles
  to React + Vue + Svelte + Angular + Solid + Lit consumers automatically,
  so the demo is itself a six-way "look ma, no per-framework integration"
  proof. There is no /examples/consumers/react-sortable-page.tsx companion
  here — there's just THIS file, fanned out by the compiler.

  Exercises (in addition to dragging):
    - `r-model:items` consumer-side two-way binding (Phase 07.3)
    - Component composition via <components> block
    - Default slot with scoped params + fallback
    - r-for (in the state-display section) — covered by the bare-comma
      regression coverage in extractRForAliases
    - r-model on text input + checkbox
    - @submit.prevent + @click event-modifier passthrough
    - r-if / r-else for the empty-state branch
-->

<rozie name="SortableListDemo">

<components>
{
  SortableList: '../../packages/ui/sortable-list/src/SortableList.rozie',
}
</components>

<data>
{
  items: [],
  newLabel: '',
  disabled: false,
  nextId: 6,
  endOrder: '',
}
</data>

<script>
const INITIAL_DATA = [
 { id: 'a', label: 'Apple' },
 { id: 'b', label: 'Banana' },
 { id: 'c', label: 'Cherry' },
 { id: 'd', label: 'Date' },
 { id: 'e', label: 'Elderberry' },
];

const addItem = () => {
  const label = $data.newLabel.trim()
  if (!label) return
  $data.items = [...$data.items, { id: String($data.nextId), label }]
  $data.nextId = $data.nextId + 1
  $data.newLabel = ''
}

const removeItem = (id) => {
  $data.items = $data.items.filter(i => i.id !== id)
}

// `end` fires after the bound array is written, so the order read here is the
// new one (sortable-drag.spec.ts reads it from the hidden readout below).
const onEnd = () => {
  $data.endOrder = $data.items.map((i) => i.id).join(',')
}

const reset = () => {
  $data.items = INITIAL_DATA
}

$onMount(() => reset());
</script>

<template>
<div class="sortable-demo">
  <header>
    <h3>Drag to reorder</h3>
    <p class="hint">Grab a row by the handle (⋮⋮) and drop it elsewhere. The bound array on the right updates in real time.</p>
  </header>

  <div class="grid">
    <section class="list-pane">
      <SortableList r-model:items="$data.items" itemKey="id" :handle="$classSelector('grip')" :disabled="$data.disabled" @end="onEnd">
        <template #default="{ item }">
          <div class="row">
            <span class="grip" aria-label="Drag handle">⋮⋮</span>
            <span class="label">{{ item.label }}</span>
            <button class="remove" @click="removeItem(item.id)" aria-label="Remove">×</button>
          </div>
        </template>
      </SortableList>

      <form @submit.prevent="addItem" class="add-form">
        <input r-model="$data.newLabel" placeholder="Add an item…" />
        <button type="submit" :disabled="!$data.newLabel.trim()">Add</button>
      </form>

      <div class="controls">
        <label><input type="checkbox" r-model="$data.disabled" /> Disabled</label>
        <button type="button" @click="reset">Reset</button>
      </div>
    </section>

    <aside class="state-pane">
      <h4>Bound state ({{ $data.items.length }})</h4>
      <ol r-if="$data.items.length > 0" class="state-list">
        <li r-for="item, index in $data.items" :key="item.id">
          <span class="state-index">{{ index + 1 }}.</span>
          <code>{{ item.id }}</code>
          <span>{{ item.label }}</span>
        </li>
      </ol>
      <p r-else class="empty">Empty.</p>
      <output hidden data-testid="end-order">{{ $data.endOrder }}</output>
    </aside>
  </div>
</div>
</template>

<style>
.sortable-demo {
  font-family: system-ui, -apple-system, sans-serif;
  color: #1a1a1a;
  padding: 1rem;
  max-width: 720px;
}

header h3 { margin: 0 0 0.25rem; font-size: 1.125rem; }
header .hint { margin: 0 0 1rem; color: rgba(0, 0, 0, 0.55); font-size: 0.875rem; }

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  align-items: start;
}

.list-pane, .state-pane { min-width: 0; }

.row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: #f5f5f7;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 6px;
  margin: 0.25rem 0;
}

.grip {
  color: rgba(0, 0, 0, 0.35);
  cursor: grab;
  user-select: none;
  font-family: monospace;
}
.grip:active { cursor: grabbing; }

.label { flex: 1; }

.remove {
  background: transparent;
  border: none;
  color: rgba(0, 0, 0, 0.4);
  cursor: pointer;
  font-size: 1.125rem;
  line-height: 1;
  padding: 0 0.25rem;
}
.remove:hover { color: #c00; }

.add-form {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.75rem;
}
.add-form input {
  flex: 1;
  padding: 0.375rem 0.5rem;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  font: inherit;
}
.add-form button {
  padding: 0.375rem 0.875rem;
  border: 1px solid rgba(0, 0, 0, 0.15);
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.controls {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-top: 0.5rem;
  font-size: 0.875rem;
}
.controls button {
  padding: 0.25rem 0.625rem;
  border: 1px solid rgba(0, 0, 0, 0.15);
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font: inherit;
}

.state-pane h4 {
  margin: 0 0 0.5rem;
  font-size: 0.875rem;
  color: rgba(0, 0, 0, 0.55);
  text-transform: uppercase;
  letter-spacing: 0.04em;
}

.state-list {
  list-style: none;
  margin: 0;
  padding: 0;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 6px;
  overflow: hidden;
}
.state-list li {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
  padding: 0.375rem 0.625rem;
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
}
.state-list li:last-child { border-bottom: none; }
.state-index {
  color: rgba(0, 0, 0, 0.35);
  font-variant-numeric: tabular-nums;
  min-width: 1.5rem;
}
.state-list code {
  font-family: ui-monospace, monospace;
  font-size: 0.75rem;
  color: rgba(0, 0, 0, 0.5);
  background: rgba(0, 0, 0, 0.04);
  padding: 0.0625rem 0.25rem;
  border-radius: 2px;
}

.empty {
  margin: 0;
  padding: 0.75rem;
  color: rgba(0, 0, 0, 0.4);
  font-style: italic;
  text-align: center;
  border: 1px dashed rgba(0, 0, 0, 0.1);
  border-radius: 6px;
}
</style>

</rozie>

Pre-1.0 — APIs may change between minor versions.