You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

45 lines
1.2 KiB
JavaScript

import { useEffect } from 'preact/hooks'
export async function fetchJson(url, options = {}) {
if (options.hasOwnProperty('method')) {
options.headers = { 'Content-Type': 'application/json' }
options.body = JSON.stringify(options.body)
}
const res = await fetch(url, options)
return await res.json()
}
export function useEventListener(target, event, handler, deps = []) {
useEffect(() => {
target.addEventListener(event, handler)
return () => {
target.removeEventListener(event, handler)
}
}, deps)
}
export function stripPrefix(s, prefix) {
return s.slice(0, prefix.length) === prefix ? s.slice(prefix.length) : s
}
export function clamp(min, value, max) {
return Math.max(min, Math.min(value, max))
}
export function useClickOutside(ref, handler) {
useEffect(() => {
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
handler()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [ref, handler])
}