import {Refresh} from "~/components/ui/Icon/refresh";
import {Accessor, Component, createMemo, createSignal, JSX, onMount, Show} from "solid-js";
import {isVisible} from "~/lib/utils/element/isVisible";
export type InfiniteScrollProps = {
data: Accessor<any[] | null | undefined>
totalCount: Accessor<number | null | undefined>
loadingComponent?: Component
load: () => void
loading: Accessor<boolean>
}
export function createInfiniteScroll(props: InfiniteScrollProps): [isLoading: Accessor<boolean>, loading: JSX.Element] {
let loadingRef = null as HTMLElement | null
let loading = props.loadingComponent
? <props.loadingComponent ref={loadingRef!}/>
: <div class='flex flex-row justify-center space-x-2 w-full'>
<Refresh ref={loadingRef! as unknown as SVGSVGElement} class='animate-spin'/>
<span>Loading</span>
</div>
const loadIfNotLoading = () => {
if (props.loading()) return
if (reachedEnd()) return
props.load()
}
const reachedEnd = createMemo(() => props.data()?.length === props.totalCount())
onMount(() => {
if (loadingRef && isVisible(loadingRef)) loadIfNotLoading()
window.addEventListener('scroll', () => {
if (loadingRef && isVisible(loadingRef)) {
loadIfNotLoading()
}
})
})
return (
<Show when={!reachedEnd()}>
{loading}
</Show>
)
}