flotilla/src/lib/html.ts

65 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-09-11 22:21:25 +00:00
import {sleep} from "@welshman/lib"
2024-09-11 18:33:50 +00:00
2024-08-08 23:32:46 +00:00
export const copyToClipboard = (text: string) => {
const {activeElement} = document
const input = document.createElement("textarea")
input.innerHTML = text
document.body.appendChild(input)
input.select()
const result = document.execCommand("copy")
document.body.removeChild(input)
;(activeElement as HTMLElement).focus()
return result
}
2024-09-11 18:33:50 +00:00
type ScrollerOpts = {
2024-10-01 21:55:33 +00:00
onScroll: () => any
element: Element
2024-09-11 18:33:50 +00:00
threshold?: number
reverse?: boolean
2024-09-24 23:47:36 +00:00
delay?: number
2024-09-11 18:33:50 +00:00
}
2024-10-01 21:55:33 +00:00
export const createScroller = ({
onScroll,
element,
delay = 1000,
threshold = 2000,
reverse = false,
}: ScrollerOpts) => {
2024-09-11 18:33:50 +00:00
let done = false
2024-09-11 18:33:50 +00:00
const check = async () => {
// While we have empty space, fill it
const {scrollY, innerHeight} = window
2024-10-01 21:55:33 +00:00
const {scrollHeight, scrollTop} = element
2024-09-11 18:33:50 +00:00
const offset = Math.abs(scrollTop || scrollY)
const shouldLoad = offset + innerHeight + threshold > scrollHeight
// Only trigger loading the first time we reach the threshold
if (shouldLoad) {
2024-10-01 21:55:33 +00:00
await onScroll()
2024-09-11 18:33:50 +00:00
}
// No need to check all that often
await sleep(delay)
if (!done) {
requestAnimationFrame(check)
}
}
requestAnimationFrame(check)
return {
check,
stop: () => {
done = true
},
}
}