Ordo UI
组件Navigation

Sortable

@mox-hub/ui 组件 · Navigation · canonical

sortable@mox-hub/uiNavigationcanonicalsrc/components/sortable.tsx
变体演示sortable

Props API

Prop类型默认值说明
value*T[]——
onValueChange*(value: T[]) => void——
getItemValue*(item: T) => string——
className*string——
render*ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>——
onMove*(event: { event: DragEndEvent; activeIndex: number; overIndex: number; }) => void——
onValueCommit*(value: T[], meta: SortableCommitMeta<T>) => void——
strategy*"grid" | "horizontal" | "vertical"'vertical'—
onDragStart*(event: DragStartEvent) => void——
onDragEnd*(event: DragEndEvent) => void——
onDragCancel*(event: DragCancelEvent) => void——
accessibility*{ announcements?: Announcements; container?: Element; restoreFocus?: boolean; screenReaderInstructions?: ScreenReaderInstructions; }——
modifiers*Modifiers——
children*ReactNode——

源码

packages/ui/src/components/sortable.tsx
/* eslint-disable @typescript-eslint/no-explicit-any */

import * as React from 'react';
import type { CSSProperties, ReactElement, ReactNode } from 'react';
import {
  Children,
  cloneElement,
  createContext,
  isValidElement,
  useCallback,
  useContext,
  useMemo,
  useState,
  useSyncExternalStore,
} from 'react';
import { mergeProps } from '@base-ui/react/merge-props';
import { useRender } from '@base-ui/react/use-render';
import type {
  DragCancelEvent,
  DragEndEvent,
  DragStartEvent,
  DropAnimation,
  Modifiers,
  UniqueIdentifier,
} from '@dnd-kit/core';
import {
  defaultDropAnimationSideEffects,
  DndContext,
  DragOverlay,
  KeyboardSensor,
  MeasuringStrategy,
  MouseSensor,
  TouchSensor,
  useSensor,
  useSensors,
  type DraggableSyntheticListeners,
} from '@dnd-kit/core';
import {
  arrayMove,
  defaultAnimateLayoutChanges,
  rectSortingStrategy,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
  type AnimateLayoutChanges,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { createPortal } from 'react-dom';

import { cn } from '../lib/utils';

/**
 * 复合式拖拽排序列表(reui base-nova 配方移植,2026-09-14)。
 * 语义限定「同列表条目重排序」——看板跨列拖拽/画布节点/文件投放请继续用 dnd-kit 原语。
 * 落放一次性提交:onValueChange 收到重排后全量数组即可持久化;
 * 需要索引式变更与回滚快照时用 onValueCommit(携带 previousValue)。
 */

// Sortable Item Context
const SortableItemContext = createContext<{
  listeners: DraggableSyntheticListeners | undefined;
  attributes?: ReturnType<typeof useSortable>['attributes'];
  isDragging?: boolean;
  disabled?: boolean;
}>({
  listeners: undefined,
  attributes: undefined,
  isDragging: false,
  disabled: false,
});

const IsOverlayContext = createContext(false);

const SortableInternalContext = createContext<{
  activeId: UniqueIdentifier | null;
  modifiers?: Modifiers;
}>({
  activeId: null,
  modifiers: undefined,
});

const animateLayoutChanges: AnimateLayoutChanges = (args) =>
  defaultAnimateLayoutChanges({ ...args, wasDragging: true });

const dropAnimationConfig: DropAnimation = {
  sideEffects: defaultDropAnimationSideEffects({
    styles: {
      active: {
        opacity: '0.4',
      },
    },
  }),
};

/**
 * createPortal 的客户端挂载闸(portal 需要 document.body,SSR/水合期不可执行)。
 * 永不通知的订阅让 useSyncExternalStore 在服务端返回 false、挂载后返回 true,
 * 等价于旧版 useLayoutEffect(() => setMounted(true), []) 且少一次渲染,
 * 同时避开 react-hooks/set-state-in-effect 规则。三个函数都在模块作用域,
 * 保证订阅身份稳定(内联 getSnapshot 是无限重订阅的经典成因)。
 */
const subscribeToNothing = () => () => {};
const getIsMounted = () => true;
const getIsMountedOnServer = () => false;

const MOUSE_SENSOR_OPTIONS = { activationConstraint: { distance: 10 } };
const TOUCH_SENSOR_OPTIONS = {
  activationConstraint: { delay: 250, tolerance: 5 },
};
const KEYBOARD_SENSOR_OPTIONS = {
  coordinateGetter: sortableKeyboardCoordinates,
};
const MEASURING_CONFIG = {
  droppable: { strategy: MeasuringStrategy.Always },
};
const STRATEGY_MAP = {
  horizontal: rectSortingStrategy,
  grid: rectSortingStrategy,
  vertical: verticalListSortingStrategy,
} as const;

export interface SortableCommitMeta<T> {
  event: DragEndEvent;
  activeIndex: number;
  overIndex: number;
  previousValue: T[];
}

export interface SortableRootProps<T>
  extends Omit<useRender.ComponentProps<'div'>, 'onDragStart' | 'onDragEnd' | 'children'> {
  value: T[];
  onValueChange: (value: T[]) => void;
  getItemValue: (item: T) => string;
  children: ReactNode;
  onMove?: (event: {
    event: DragEndEvent;
    activeIndex: number;
    overIndex: number;
  }) => void;
  onValueCommit?: (value: T[], meta: SortableCommitMeta<T>) => void;
  strategy?: 'horizontal' | 'vertical' | 'grid';
  onDragStart?: (event: DragStartEvent) => void;
  onDragEnd?: (event: DragEndEvent) => void;
  onDragCancel?: (event: DragCancelEvent) => void;
  accessibility?: React.ComponentProps<typeof DndContext>['accessibility'];
  modifiers?: Modifiers;
}

function Sortable<T>({
  value,
  onValueChange,
  getItemValue,
  className,
  render,
  onMove,
  onValueCommit,
  strategy = 'vertical',
  onDragStart,
  onDragEnd,
  onDragCancel,
  accessibility,
  modifiers,
  children,
  ...props
}: SortableRootProps<T>) {
  const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null);
  const mounted = useSyncExternalStore(
    subscribeToNothing,
    getIsMounted,
    getIsMountedOnServer
  );

  const sensors = useSensors(
    useSensor(MouseSensor, MOUSE_SENSOR_OPTIONS),
    useSensor(TouchSensor, TOUCH_SENSOR_OPTIONS),
    useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
  );

  const handleDragStart = useCallback(
    (event: DragStartEvent) => {
      setActiveId(event.active.id);
      onDragStart?.(event);
    },
    [onDragStart]
  );

  const handleDragEnd = useCallback(
    (event: DragEndEvent) => {
      const { active, over } = event;
      setActiveId(null);
      onDragEnd?.(event);

      if (!over) return;

      const activeIndex = value.findIndex(
        (item: T) => getItemValue(item) === active.id
      );
      const overIndex = value.findIndex(
        (item: T) => getItemValue(item) === over.id
      );

      if (activeIndex === -1 || overIndex === -1) return;

      if (activeIndex !== overIndex) {
        if (onMove) {
          onMove({ event, activeIndex, overIndex });
        } else {
          const newValue = arrayMove(value, activeIndex, overIndex);
          onValueChange(newValue);
          onValueCommit?.(newValue, {
            event,
            activeIndex,
            overIndex,
            previousValue: value,
          });
        }
      }
    },
    [value, getItemValue, onValueChange, onMove, onDragEnd, onValueCommit]
  );

  const handleDragCancel = useCallback(
    (event: DragCancelEvent) => {
      setActiveId(null);
      onDragCancel?.(event);
    },
    [onDragCancel]
  );

  const itemIds = useMemo(() => {
    const ids = value.map(getItemValue);
    if (process.env.NODE_ENV !== 'production') {
      const seen = new Set<string>();
      for (const id of ids) {
        if (seen.has(id)) {
          console.warn(
            `[Sortable] Duplicate item id "${id}". Item ids must be unique, or drag and drop will misbehave.`
          );
          break;
        }
        seen.add(id);
      }
    }
    return ids;
  }, [value, getItemValue]);

  const contextValue = useMemo(
    () => ({ activeId, modifiers }),
    [activeId, modifiers]
  );

  const defaultProps = {
    'data-slot': 'sortable',
    'data-dragging': activeId !== null || undefined,
    className: cn(activeId !== null && 'cursor-grabbing!', className),
    children,
  };

  // 拖拽中的活动项克隆为 overlay 内容
  const overlayContent = useMemo(() => {
    if (!activeId) return null;
    let result: ReactNode = null;
    Children.forEach(children, (child) => {
      if (isValidElement(child) && (child.props as any).value === activeId) {
        result = cloneElement(child as ReactElement<any>, {
          ...(child.props as any),
          className: cn((child.props as any).className, 'z-modal'),
        });
      }
    });
    return result;
  }, [activeId, children]);

  return (
    <SortableInternalContext.Provider value={contextValue}>
      <DndContext
        sensors={sensors}
        modifiers={modifiers}
        accessibility={accessibility}
        measuring={MEASURING_CONFIG}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        onDragCancel={handleDragCancel}
      >
        <SortableContext
          items={itemIds}
          strategy={STRATEGY_MAP[strategy] ?? verticalListSortingStrategy}
        >
          {useRender({
            defaultTagName: 'div',
            render,
            props: mergeProps<'div'>(defaultProps, props),
          })}
        </SortableContext>
        {mounted &&
          createPortal(
            <DragOverlay
              dropAnimation={dropAnimationConfig}
              modifiers={modifiers}
              className={cn('z-modal', activeId && 'cursor-grabbing')}
            >
              <IsOverlayContext.Provider value={true}>
                {overlayContent}
              </IsOverlayContext.Provider>
            </DragOverlay>,
            document.body
          )}
      </DndContext>
    </SortableInternalContext.Provider>
  );
}

export interface SortableItemProps extends useRender.ComponentProps<'div'> {
  value: string;
  disabled?: boolean;
}

function SortableItem({
  value,
  className,
  render,
  disabled,
  ...props
}: SortableItemProps) {
  const isOverlay = useContext(IsOverlayContext);

  const {
    setNodeRef,
    transform,
    transition,
    attributes,
    listeners,
    isDragging: isSortableDragging,
  } = useSortable({
    id: value,
    disabled: disabled || isOverlay,
    animateLayoutChanges,
  });

  const style = {
    transition,
    transform: CSS.Transform.toString(transform),
  } as CSSProperties;

  const defaultProps = isOverlay
    ? {
        'data-slot': 'sortable-item',
        'data-value': value,
        'data-dragging': true,
        className: cn(className),
        children: props.children,
      }
    : {
        'data-slot': 'sortable-item',
        'data-value': value,
        'data-dragging': isSortableDragging || undefined,
        'data-disabled': disabled || undefined,
        ref: setNodeRef,
        style,
        className: cn(
          isSortableDragging && 'opacity-50 z-modal',
          disabled && 'opacity-50',
          className
        ),
        children: props.children,
      };

  return (
    <SortableItemContext.Provider
      value={
        isOverlay
          ? { listeners: undefined, attributes: undefined, isDragging: true, disabled: false }
          : { listeners, attributes, isDragging: isSortableDragging, disabled }
      }
    >
      {useRender({
        defaultTagName: 'div',
        render,
        props: mergeProps<'div'>(defaultProps, props),
      })}
    </SortableItemContext.Provider>
  );
}

export interface SortableItemHandleProps
  extends useRender.ComponentProps<'div'> {
  cursor?: boolean;
}

function SortableItemHandle({
  className,
  render,
  cursor = true,
  ...props
}: SortableItemHandleProps) {
  const { listeners, attributes, isDragging, disabled } = useContext(SortableItemContext);

  const defaultProps = {
    'data-slot': 'sortable-item-handle',
    'data-dragging': isDragging || undefined,
    'data-disabled': disabled || undefined,
    // dnd-kit 的键盘拖拽要求 attributes(role/tabIndex/aria-roledescription)与
    // listeners(KeyboardSensor onKeyDown)落在同一个可聚焦节点上(审计 P1-08)。
    role: 'button',
    tabIndex: 0,
    ...attributes,
    ...listeners,
    className: cn(
      'touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
      cursor && (isDragging ? 'cursor-grabbing!' : 'cursor-grab!'),
      className
    ),
    children: props.children,
  };

  return useRender({
    defaultTagName: 'div',
    render,
    props: mergeProps<'div'>(defaultProps, props),
  });
}

export interface SortableOverlayProps
  extends Omit<React.ComponentProps<typeof DragOverlay>, 'children'> {
  children?: ReactNode | ((params: { value: UniqueIdentifier }) => ReactNode);
}

function SortableOverlay({
  children,
  className,
  ...props
}: SortableOverlayProps) {
  const { activeId, modifiers } = useContext(SortableInternalContext);
  const mounted = useSyncExternalStore(
    subscribeToNothing,
    getIsMounted,
    getIsMountedOnServer
  );

  const content =
    activeId && children
      ? typeof children === 'function'
        ? children({ value: activeId })
        : children
      : null;

  if (!mounted) return null;

  return createPortal(
    <DragOverlay
      dropAnimation={dropAnimationConfig}
      modifiers={modifiers}
      className={cn('z-modal', activeId && 'cursor-grabbing', className)}
      {...props}
    >
      <IsOverlayContext.Provider value={true}>
        {content}
      </IsOverlayContext.Provider>
    </DragOverlay>,
    document.body
  );
}

export { Sortable, SortableItem, SortableItemHandle, SortableOverlay };

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

可排序列表(dnd-kit),由 Sortable 与 SortableItem/SortableItemHandle 组合;拖拽结束回写顺序,需提供稳定 id。