mcpField
B
bulk-select-actions

bulk-select-actions

github.com/blink-new设计与 UI53 次安装
代码仓库

关于 bulk-select-actions

bulk-select-actions 是用于构建表格和列表多选及批量操作的技能,提供可复用的选择与工具栏模式,并涵盖破坏性操作的确认流程。

主要功能

  1. 01页面级选择状态
  2. 02支持不确定状态的复选框
  3. 03浮动批量操作工具栏
  4. 04按项目状态显示操作
  5. 05破坏性操作确认
  6. 06可复用的表格和选择模板

适用场景

  1. 01为数据表添加多选
  2. 02提供批量归档或状态变更
  3. 03为批量删除添加确认
  4. 04在多个列表复用选择交互

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/blink-new/claude --skill bulk-select-actions

安装后在 Claude Code 中输入/bulk-select-actions确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/components/
bulk-actions-toolbar.tsx
selectable-table.tsx
assets/hooks/
use-bulk-selection.ts

详细介绍

何时使用此技能

适用于:

  • 构建支持多选功能的表格/列表
  • 实现批量操作(删除、归档、导出、更改状态)
  • 需要一个在选中项目时显示的悬浮操作工具栏
  • 希望在多个表格中保持一致的选择体验

技术栈

软件包版本用途
@radix-ui/react-checkbox^1.x支持不确定状态的复选框
tailwindcss-animate^1.x入场动画
shadcn/uilatestAlertDialog、Button、DropdownMenu
lucide-react^0.x图标

架构概览

┌─────────────────────────────────────────────────────────────┐
│  Page Component (selection state owner)                     │
│  ├── selectedIds: Set<string>                               │
│  ├── onSelectionChange: (ids: Set<string>) => void          │
│  └── bulk action handlers                                   │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────┐    │
│  │ Table Component                                      │    │
│  │ ┌─────┬─────────────────────────────────────────┐   │    │
│  │ │ ☑️  │ Header row with select-all checkbox      │   │    │
│  │ ├─────┼─────────────────────────────────────────┤   │    │
│  │ │ ☐  │ Row 1                                    │   │    │
│  │ │ ☑️  │ Row 2 (selected)                         │   │    │
│  │ │ ☑️  │ Row 3 (selected)                         │   │    │
│  │ │ ☐  │ Row 4                                    │   │    │
│  │ └─────┴─────────────────────────────────────────┘   │    │
│  └─────────────────────────────────────────────────────┘    │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────┐    │
│  │ Floating Toolbar (fixed bottom center, z-50)        │    │
│  │ ┌──────────────┬────────────┬────────────┬───────┐  │    │
│  │ │ 2 selected ✕ │  Action 1  │  Action 2  │ Delete│  │    │
│  │ └──────────────┴────────────┴────────────┴───────┘  │    │
│  └─────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────┘

关键模式

1. 选择状态管理(页面级)

选择状态必须保存在页面组件中,而不是表格中:

// page.tsx
"use client";

import { useState } from "react";

export default function ItemsPage() {
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  // Clear selection when filters change
  const handleFilterChange = (value: string) => {
    setFilter(value);
    setSelectedIds(new Set());
  };

  return (
    <>
      <ItemsTable
        items={items}
        selectedIds={selectedIds}
        onSelectionChange={setSelectedIds}
      />
      <BulkActionsToolbar
        selectedIds={selectedIds}
        onClearSelection={() => setSelectedIds(new Set())}
        // ... action handlers
      />
    </>
  );
}
2. 复选框不确定状态(关键)

使用内置的 checked 属性,并将其值设为 "indeterminate":

// ✅ CORRECT - Use built-in indeterminate prop
<Checkbox
  checked={allSelected ? true : someSelected ? "indeterminate" : false}
  onCheckedChange={handleSelectAll}
  aria-label="Select all"
/>

// ❌ WRONG - Manual ref approach (gets overwritten by Radix)
<Checkbox
  checked={allSelected}
  ref={(el) => {
    if (el) {
      (el as HTMLButtonElement).dataset.state = someSelected
        ? "indeterminate"
        : "checked";
    }
  }}
/>
3. 选择逻辑
// Table component
const allSelected = items.length > 0 && items.every((item) => selectedIds.has(item.id));
const someSelected = items.some((item) => selectedIds.has(item.id)) && !allSelected;

const handleSelectAll = () => {
  if (allSelected) {
    onSelectionChange(new Set()); // Deselect all
  } else {
    onSelectionChange(new Set(items.map((item) => item.id))); // Select all
  }
};

const handleSelectOne = (id: string, checked: boolean) => {
  const newSet = new Set(selectedIds);
  if (checked) {
    newSet.add(id);
  } else {
    newSet.delete(id);
  }
  onSelectionChange(newSet);
};
4. 悬浮工具栏的位置与动画
// CRITICAL: These exact classes for consistent UX
<div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 animate-in fade-in slide-in-from-bottom-4 duration-200">
  <div className="flex items-center gap-2 bg-background border rounded-lg shadow-lg px-4 py-3">
    {/* Toolbar content */}
  </div>
</div>
5. 工具栏结构
export function BulkActionsToolbar({
  selectedIds,
  onClearSelection,
  onAction1,
  onAction2,
  onDelete,
  isLoading = false,
}: BulkActionsToolbarProps) {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const selectedCount = selectedIds.size;

  // Hide when nothing selected
  if (selectedCount === 0) {
    return null;
  }

  return (
    <>
      <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 animate-in fade-in slide-in-from-bottom-4 duration-200">
        <div className="flex items-center gap-2 bg-background border rounded-lg shadow-lg px-4 py-3">
          {/* Selected count with clear button */}
          <div className="flex items-center gap-2 pr-3 border-r">
            <span className="text-sm font-medium">
              {selectedCount} selected
            </span>
            <Button
              variant="ghost"
              size="sm"
              className="h-6 w-6 p-0"
              onClick={onClearSelection}
            >
              <X className="h-4 w-4" />
            </Button>
          </div>

          {/* Action buttons */}
          <Button variant="outline" size="sm" onClick={onAction1} disabled={isLoading}>
            <Icon className="h-4 w-4 mr-2" />
            Action 1
          </Button>

          {/* Destructive action - always last, with confirmation */}
          <Button
            variant="outline"
            size="sm"
            onClick={() => setDeleteDialogOpen(true)}
            disabled={isLoading}
            className="text-red-600 hover:text-red-700 hover:bg-red-50"
          >
            <Trash2 className="h-4 w-4 mr-2" />
            Delete
          </Button>
        </div>
      </div>

      {/* Confirmation dialog for destructive actions */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Items</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete {selectedCount} item
              {selectedCount === 1 ? "" : "s"}? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => { onDelete(); setDeleteDialogOpen(false); }}
              className="bg-red-600 hover:bg-red-700"
            >
              Delete {selectedCount} Item{selectedCount === 1 ? "" : "s"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
6. 行复选框——阻止行点击事件
<TableRow
  className="cursor-pointer"
  onClick={() => onRowClick(item.id)}
>
  <TableCell onClick={(e) => e.stopPropagation()}>
    <Checkbox
      checked={selectedIds.has(item.id)}
      onCheckedChange={(checked) => handleSelectOne(item.id, !!checked)}
      aria-label={`Select ${item.name}`}
    />
  </TableCell>
  {/* ... other cells */}
</TableRow>
7. 根据项目状态显示条件操作
// Check selected items' states for conditional actions
const selectedItems = items.filter((item) => selectedIds.has(item.id));
const allDraft = selectedItems.every((item) => item.status === "DRAFT");
const allPublished = selectedItems.every((item) => item.status === "PUBLISHED");

// Only show "Publish" if all selected are DRAFT
{allDraft && (
  <Button variant="outline" size="sm" onClick={onPublish}>
    <Globe className="h-4 w-4 mr-2" />
    Publish
  </Button>
)}

// Only show "Close" if all selected are PUBLISHED
{allPublished && (
  <Button variant="outline" size="sm" onClick={onClose}>
    <XCircle className="h-4 w-4 mr-2" />
    Close
  </Button>
)}

表格组件 Props 接口

interface SelectableTableProps<T extends { id: string }> {
  items: T[];
  isLoading?: boolean;
  selectedIds: Set<string>;
  onSelectionChange: (ids: Set<string>) => void;
  onRowClick?: (id: string) => void;
}

工具栏组件 Props 接口

interface BulkActionsToolbarProps {
  selectedIds: Set<string>;
  onClearSelection: () => void;
  isLoading?: boolean;
  // Add specific action handlers as needed
}

样式模式

复选框列宽度
<TableHead className="w-12">
  <Checkbox ... />
</TableHead>
清除选择按钮
<Button
  variant="ghost"
  size="sm"
  className="h-6 w-6 p-0"  // Compact square button
  onClick={onClearSelection}
>
  <X className="h-4 w-4" />
</Button>
危险操作按钮
<Button
  variant="outline"
  size="sm"
  className="text-red-600 hover:text-red-700 hover:bg-red-50"
>
  <Trash2 className="h-4 w-4 mr-2" />
  Delete
</Button>
确认对话框操作
<AlertDialogAction className="bg-red-600 hover:bg-red-700">
  Delete {count} Item{count === 1 ? "" : "s"}
</AlertDialogAction>
已选数量区域(带分隔线)
<div className="flex items-center gap-2 pr-3 border-r">
  <span className="text-sm font-medium">{count} selected</span>
  <ClearButton />
</div>

应避免的常见错误

❌ 使用 useEffect 在筛选条件变化时清除选择
// WRONG - ESLint error, causes cascading renders
useEffect(() => {
  setSelectedIds(new Set());
}, [filter]);
✅ 在筛选处理函数中清除选择
// CORRECT - Clear inline when filter changes
const handleFilterChange = (value: string) => {
  setFilter(value);
  setSelectedIds(new Set());
};
❌ 在表格组件中保存选择状态
// WRONG - State should be lifted to page
function Table() {
  const [selectedIds, setSelectedIds] = useState(new Set());
  // ...
}
✅ 在页面组件中保存选择状态
// CORRECT - Page owns state, passes to children
function Page() {
  const [selectedIds, setSelectedIds] = useState(new Set());
  return (
    <>
      <Table selectedIds={selectedIds} onSelectionChange={setSelectedIds} />
      <Toolbar selectedIds={selectedIds} onClearSelection={() => setSelectedIds(new Set())} />
    </>
  );
}
❌ 行复选框缺少 stopPropagation
// WRONG - Clicking checkbox also triggers row click
<TableRow onClick={onRowClick}>
  <TableCell>
    <Checkbox onCheckedChange={handleSelect} />
  </TableCell>
</TableRow>
✅ 在复选框单元格中阻止事件传播
// CORRECT - Checkbox click doesn't bubble to row
<TableRow onClick={onRowClick}>
  <TableCell onClick={(e) => e.stopPropagation()}>
    <Checkbox onCheckedChange={handleSelect} />
  </TableCell>
</TableRow>
❌ 危险批量操作没有确认步骤
// WRONG - Dangerous actions need confirmation
<Button onClick={onBulkDelete}>Delete All</Button>
✅ 始终确认危险操作
// CORRECT - AlertDialog for confirmation
<Button onClick={() => setDeleteDialogOpen(true)}>Delete</Button>
<AlertDialog open={deleteDialogOpen}>
  {/* Confirmation content */}
</AlertDialog>

文件结构

src/
├── app/
│   └── (dashboard)/
│       └── dashboard/
│           └── items/
│               └── page.tsx           # Selection state owner
├── components/
│   └── items/
│       ├── items-table.tsx            # Table with checkboxes
│       ├── items-bulk-actions-toolbar.tsx  # Floating toolbar
│       └── index.ts                   # Exports
└── hooks/
    └── use-items.ts                   # Include bulk mutation hooks

批量变更 Hook 模式

// hooks/use-items.ts
export function useBulkDeleteItems(teamId?: string) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (ids: string[]) => {
      const response = await fetch(`/api/teams/${teamId}/items/bulk-delete`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids }),
      });
      if (!response.ok) throw new Error("Failed to delete items");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["items", teamId] });
    },
  });
}

相关资源文件

资源描述
assets/components/bulk-actions-toolbar.tsx通用工具栏模板
assets/components/selectable-table.tsx带复选框选择功能的表格
assets/hooks/use-bulk-selection.ts可复用的选择 Hook

检查清单

  • 选择状态保存在页面组件中(而不是表格中)
  • 复选框使用 checked={allSelected ? true : someSelected ? "indeterminate" : false}
  • 悬浮工具栏具有 fixed bottom-6 left-1/2 -translate-x-1/2 z-50
  • 工具栏具有 animate-in fade-in slide-in-from-bottom-4 duration-200
  • 当 selectedCount === 0 时,工具栏返回 null
  • 行复选框单元格具有 onClick={(e) => e.stopPropagation()}
  • 已选数量区域具有 border-r 分隔线
  • 危险操作带有确认对话框
  • 危险操作按钮具有 text-red-600 hover:text-red-700 hover:bg-red-50
  • 确认操作具有 bg-red-600 hover:bg-red-700
  • 筛选条件变化时清除选择(在处理函数中,而不是 useEffect 中)
  • 批量变更 Hook 在操作成功后使查询失效

评论

支持 Markdown