260703_01_FST: First Commit
This commit is contained in:
30
registry/components/data-table/hooks/usePagination.ts
Normal file
30
registry/components/data-table/hooks/usePagination.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useMemo } from 'react'
|
||||
|
||||
interface UsePaginationProps {
|
||||
currentPage: number
|
||||
totalPages: number
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
|
||||
export function usePagination({ currentPage, totalPages, paginationItemsToDisplay = 5 }: UsePaginationProps) {
|
||||
return useMemo(() => {
|
||||
if (totalPages <= 0) {
|
||||
return { pages: [] as number[], showLeftEllipsis: false, showRightEllipsis: false }
|
||||
}
|
||||
|
||||
const visibleCount = Math.max(1, paginationItemsToDisplay)
|
||||
const half = Math.floor(visibleCount / 2)
|
||||
let startPage = Math.max(1, currentPage - half)
|
||||
let endPage = Math.min(totalPages, startPage + visibleCount - 1)
|
||||
|
||||
if (endPage - startPage + 1 < visibleCount) {
|
||||
startPage = Math.max(1, endPage - visibleCount + 1)
|
||||
}
|
||||
|
||||
return {
|
||||
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
|
||||
showLeftEllipsis: startPage > 1,
|
||||
showRightEllipsis: endPage < totalPages,
|
||||
}
|
||||
}, [currentPage, paginationItemsToDisplay, totalPages])
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as React from 'react'
|
||||
|
||||
export function usePreventClickOnDrag(thresholdPx = 6) {
|
||||
const state = React.useRef({ x: 0, y: 0, dragging: false })
|
||||
|
||||
const onPointerDown = React.useCallback((event: React.PointerEvent) => {
|
||||
if (event.button !== 0) return
|
||||
state.current = { x: event.clientX, y: event.clientY, dragging: false }
|
||||
}, [])
|
||||
|
||||
const onPointerMove = React.useCallback((event: React.PointerEvent) => {
|
||||
if (event.buttons === 0) return
|
||||
const dx = event.clientX - state.current.x
|
||||
const dy = event.clientY - state.current.y
|
||||
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) state.current.dragging = true
|
||||
}, [thresholdPx])
|
||||
|
||||
const onPointerUp = React.useCallback(() => {
|
||||
setTimeout(() => {
|
||||
state.current.dragging = false
|
||||
}, 0)
|
||||
}, [])
|
||||
|
||||
const wrapClick = React.useCallback(
|
||||
(callback: () => void) => (event: React.MouseEvent) => {
|
||||
if (state.current.dragging) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
callback()
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick }
|
||||
}
|
||||
Reference in New Issue
Block a user