feat(admin): 为支持单删的管理列表补齐批量删除
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import { failureDetail } from '../components/load-failure-model.ts'
|
||||
|
||||
type RowId = number | string
|
||||
interface BatchRow<Id extends RowId> { id: Id; label: string }
|
||||
|
||||
export interface BatchDeleteResult<Id extends RowId> {
|
||||
deleted: Id[]
|
||||
failures: Array<BatchRow<Id> & { reason: string }>
|
||||
remaining: number
|
||||
}
|
||||
|
||||
export function togglePageSelection<Id extends RowId, Row extends BatchRow<Id>>(
|
||||
selected: ReadonlyMap<Id, Row>, rows: readonly Row[],
|
||||
): Map<Id, Row> {
|
||||
const next = new Map(selected)
|
||||
if (rows.every(({ id }) => next.has(id))) {
|
||||
rows.forEach(({ id }) => next.delete(id))
|
||||
} else {
|
||||
rows.forEach((row) => next.set(row.id, row))
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
export async function runBatchDelete<Id extends RowId, Row extends BatchRow<Id>>(options: {
|
||||
rows: readonly Row[]
|
||||
deleteOne: (row: Row) => Promise<unknown>
|
||||
precheck?: (row: Row) => string | undefined
|
||||
isCurrent?: () => boolean
|
||||
onProgress?: (processed: number) => void
|
||||
}): Promise<BatchDeleteResult<Id>> {
|
||||
const { deleteOne, isCurrent, onProgress, precheck } = options
|
||||
const rows = [...new Map(options.rows.map((row) => [row.id, row])).values()]
|
||||
const deleted: Id[] = []
|
||||
const failures: BatchDeleteResult<Id>['failures'] = []
|
||||
let processed = 0
|
||||
for (const row of rows) {
|
||||
if (isCurrent && !isCurrent()) break
|
||||
try {
|
||||
const reason = precheck?.(row)
|
||||
if (reason) failures.push({ id: row.id, label: row.label, reason })
|
||||
else {
|
||||
await deleteOne(row)
|
||||
deleted.push(row.id)
|
||||
}
|
||||
} catch (error) {
|
||||
failures.push({ id: row.id, label: row.label, reason: failureDetail(error) || '删除请求失败' })
|
||||
}
|
||||
processed++
|
||||
onProgress?.(processed)
|
||||
}
|
||||
return { deleted, failures, remaining: rows.length - processed }
|
||||
}
|
||||
|
||||
export function batchResultMessage(result: BatchDeleteResult<RowId>, verb = '删除', detailLimit = Infinity): string {
|
||||
const counts = [`已${verb} ${result.deleted.length} 条`]
|
||||
if (result.failures.length) counts.push(`失败 ${result.failures.length} 条`)
|
||||
if (result.remaining) counts.push(`未处理 ${result.remaining} 条`)
|
||||
const details = result.failures.slice(0, detailLimit).map(({ label, reason }) => `${label}(${reason})`)
|
||||
if (details.length && details.length < result.failures.length) details.push('其余原因见列表上方')
|
||||
return counts.join(',') + (details.length ? `:${details.join(';')}` : '')
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { computed, onScopeDispose, reactive, ref, shallowRef, watch } from 'vue'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { batchResultMessage, runBatchDelete, togglePageSelection, type BatchDeleteResult } from './batch-delete'
|
||||
|
||||
type RowId = number | string
|
||||
|
||||
export function useRowSelection<Row, Id extends RowId>(options: {
|
||||
pageRows: () => readonly Row[]
|
||||
rowId: (row: Row) => Id
|
||||
rowLabel: (row: Row) => string
|
||||
deleteOne: (id: Id, row: Row, isCurrent: () => boolean) => Promise<unknown>
|
||||
refresh: (result: BatchDeleteResult<Id>) => unknown
|
||||
scope?: () => unknown
|
||||
blocked?: () => boolean
|
||||
precheck?: (row: Row) => string | undefined
|
||||
consequence?: string
|
||||
verb?: string
|
||||
}) {
|
||||
type Item = { id: Id; label: string; row: Row }
|
||||
const selected = shallowRef(new Map<Id, Item>())
|
||||
const busy = ref(false)
|
||||
const progress = ref('')
|
||||
const result = shallowRef<BatchDeleteResult<Id> | null>(null)
|
||||
const disabled = computed(() => busy.value || Boolean(options.blocked?.()))
|
||||
const pageItems = computed(() => options.pageRows().filter((row) => !options.precheck?.(row)).map(itemOf))
|
||||
const pageAll = computed(() => pageItems.value.length > 0 && pageItems.value.every(({ id }) => selected.value.has(id)))
|
||||
const pageSome = computed(() => !pageAll.value && pageItems.value.some(({ id }) => selected.value.has(id)))
|
||||
const verb = options.verb ?? '删除'
|
||||
let generation = 0
|
||||
|
||||
function itemOf(row: Row): Item {
|
||||
return { id: options.rowId(row), label: options.rowLabel(row), row }
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
generation++
|
||||
selected.value = new Map()
|
||||
result.value = null
|
||||
}
|
||||
|
||||
if (options.scope) watch(options.scope, clearSelection, { flush: 'sync' })
|
||||
onScopeDispose(clearSelection)
|
||||
|
||||
function removeFromSelection(id: Id) {
|
||||
const next = new Map(selected.value)
|
||||
next.delete(id)
|
||||
selected.value = next
|
||||
}
|
||||
|
||||
function toggle(row: Row) {
|
||||
if (disabled.value || options.precheck?.(row)) return
|
||||
selected.value = togglePageSelection(selected.value, [itemOf(row)])
|
||||
}
|
||||
|
||||
function togglePage() {
|
||||
if (disabled.value) return
|
||||
selected.value = togglePageSelection(selected.value, pageItems.value)
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (disabled.value || !selected.value.size) return
|
||||
const current = generation
|
||||
const isCurrent = () => current === generation
|
||||
const items = [...selected.value.values()]
|
||||
const names = items.slice(0, 3).map(({ label }) => label).join('、')
|
||||
const sample = items.length > 3 ? `${names}等` : names
|
||||
busy.value = true
|
||||
try {
|
||||
const confirmed = await openAdminConfirm({ danger: true,
|
||||
title: `批量${verb}`,
|
||||
confirmText: `确认${verb}`,
|
||||
message: `确定${verb}选中的 ${items.length} 条记录(${sample})吗?${options.consequence ?? '此操作不可恢复。'}`,
|
||||
})
|
||||
if (!confirmed || !isCurrent() || options.blocked?.()) return
|
||||
result.value = null
|
||||
progress.value = `0/${items.length}`
|
||||
const outcome = await runBatchDelete<Id, Item>({
|
||||
rows: items,
|
||||
precheck: ({ row }) => options.precheck?.(row),
|
||||
deleteOne: ({ id, row }) => options.deleteOne(id, row, isCurrent),
|
||||
isCurrent,
|
||||
onProgress: (done) => { progress.value = `${done}/${items.length}` },
|
||||
})
|
||||
if (isCurrent()) {
|
||||
const next = new Map(selected.value)
|
||||
outcome.deleted.forEach((id) => next.delete(id))
|
||||
selected.value = next
|
||||
result.value = outcome.failures.length ? outcome : null
|
||||
}
|
||||
showAdminFeedback(batchResultMessage(outcome, verb, isCurrent() ? 3 : Infinity),
|
||||
outcome.failures.length || outcome.remaining ? 'error' : 'success')
|
||||
if (isCurrent() && (outcome.deleted.length || outcome.failures.length)) await options.refresh(outcome)
|
||||
} finally {
|
||||
busy.value = false
|
||||
progress.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
return reactive({
|
||||
busy, disabled, progress, result, verb, pageAll, pageSome,
|
||||
count: computed(() => selected.value.size),
|
||||
pageEmpty: computed(() => !pageItems.value.length),
|
||||
isSelected: (row: Row) => selected.value.has(options.rowId(row)),
|
||||
reason: (row: Row) => options.precheck?.(row),
|
||||
label: options.rowLabel,
|
||||
toggle, togglePage, submit, clearSelection, removeFromSelection,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user