41 行
1.4 KiB
JavaScript
41 行
1.4 KiB
JavaScript
// 通用排序工具:在分页列表内与相邻行交换 sortOrder
|
||
// 用法:
|
||
// const { swapAdjacent } = useAdminSort('/api/admin/faqs')
|
||
// await swapAdjacent(currentRow, neighborRow) // 把两条的 sortOrder 字段互换并落库
|
||
export function useAdminSort(apiBase) {
|
||
const { adminFetch } = useAdmin()
|
||
|
||
async function swapAdjacent(a, b) {
|
||
if (!a || !b) return
|
||
const orderA = a.sortOrder ?? 0
|
||
const orderB = b.sortOrder ?? 0
|
||
// 同时发两次 PUT(并行)
|
||
await Promise.all([
|
||
adminFetch(`${apiBase}/${a.id}`, { method: 'PUT', body: { sortOrder: orderB } }),
|
||
adminFetch(`${apiBase}/${b.id}`, { method: 'PUT', body: { sortOrder: orderA } }),
|
||
])
|
||
a.sortOrder = orderB
|
||
b.sortOrder = orderA
|
||
}
|
||
|
||
// 在列表内按 UI 位置上移/下移(仅与相邻行交换)
|
||
async function moveUp(list, index) {
|
||
if (index <= 0) return
|
||
const a = list[index]
|
||
const b = list[index - 1]
|
||
await swapAdjacent(a, b)
|
||
// UI 顺序也要立即交换,让人看见结果
|
||
;[list[index - 1], list[index]] = [list[index], list[index - 1]]
|
||
}
|
||
|
||
async function moveDown(list, index) {
|
||
if (index >= list.length - 1) return
|
||
const a = list[index]
|
||
const b = list[index + 1]
|
||
await swapAdjacent(a, b)
|
||
;[list[index], list[index + 1]] = [list[index + 1], list[index]]
|
||
}
|
||
|
||
return { swapAdjacent, moveUp, moveDown }
|
||
}
|