97 lines
2.3 KiB
TypeScript
97 lines
2.3 KiB
TypeScript
"use client"
|
|
|
|
import * as React from "react"
|
|
|
|
type Selectable = { id: string }
|
|
|
|
export function useTrackSelection<T extends Selectable>(
|
|
items: T[],
|
|
initialSelectedId?: string
|
|
) {
|
|
const initialIndex =
|
|
initialSelectedId !== undefined
|
|
? items.findIndex((item) => item.id === initialSelectedId)
|
|
: -1
|
|
|
|
const [selectedIds, setSelectedIds] = React.useState<Set<string>>(() => {
|
|
if (initialIndex >= 0) {
|
|
return new Set([initialSelectedId!])
|
|
}
|
|
return new Set()
|
|
})
|
|
const anchorIndexRef = React.useRef<number | null>(
|
|
initialIndex >= 0 ? initialIndex : null
|
|
)
|
|
|
|
const isSelected = React.useCallback(
|
|
(id: string) => selectedIds.has(id),
|
|
[selectedIds]
|
|
)
|
|
|
|
const handlePointerDown = React.useCallback((event: React.MouseEvent) => {
|
|
if (event.shiftKey) {
|
|
event.preventDefault()
|
|
}
|
|
}, [])
|
|
|
|
const handleSelect = React.useCallback(
|
|
(id: string, index: number, event: React.MouseEvent) => {
|
|
if (event.shiftKey || event.metaKey || event.ctrlKey) {
|
|
event.preventDefault()
|
|
window.getSelection()?.removeAllRanges()
|
|
}
|
|
|
|
if (event.metaKey || event.ctrlKey) {
|
|
setSelectedIds((current) => {
|
|
const next = new Set(current)
|
|
if (next.has(id)) {
|
|
next.delete(id)
|
|
} else {
|
|
next.add(id)
|
|
}
|
|
return next
|
|
})
|
|
anchorIndexRef.current = index
|
|
return
|
|
}
|
|
|
|
if (event.shiftKey && anchorIndexRef.current !== null) {
|
|
const start = Math.min(anchorIndexRef.current, index)
|
|
const end = Math.max(anchorIndexRef.current, index)
|
|
setSelectedIds(
|
|
new Set(items.slice(start, end + 1).map((item) => item.id))
|
|
)
|
|
return
|
|
}
|
|
|
|
setSelectedIds(new Set([id]))
|
|
anchorIndexRef.current = index
|
|
},
|
|
[items]
|
|
)
|
|
|
|
const prepareContextMenu = React.useCallback((id: string) => {
|
|
setSelectedIds((current) => {
|
|
if (current.has(id)) {
|
|
return current
|
|
}
|
|
return new Set([id])
|
|
})
|
|
}, [])
|
|
|
|
const clearSelection = React.useCallback(() => {
|
|
setSelectedIds(new Set())
|
|
anchorIndexRef.current = null
|
|
}, [])
|
|
|
|
return {
|
|
selectedIds,
|
|
selectedCount: selectedIds.size,
|
|
isSelected,
|
|
handleSelect,
|
|
handlePointerDown,
|
|
prepareContextMenu,
|
|
clearSelection,
|
|
}
|
|
}
|