Initial commit
This commit is contained in:
54
frontend/src/lib/actions.ts
Normal file
54
frontend/src/lib/actions.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { Action } from "svelte/action"
|
||||
import { overlays } from "./store"
|
||||
|
||||
export const spaLink: Action<HTMLAnchorElement> = (node) => {
|
||||
const onClick = (event: MouseEvent) => {
|
||||
if (node.dataset.spaPrevent && node.dataset.spaPrevent !== "false") {
|
||||
return
|
||||
}
|
||||
const anchor = event.currentTarget as HTMLAnchorElement
|
||||
if ((anchor.target === "" || anchor.target === "_self") && anchor.href.startsWith(window.location.origin)) {
|
||||
event.preventDefault()
|
||||
const currentUrl = window.location.pathname + window.location.search + window.location.hash
|
||||
const newUrl = anchor.pathname + anchor.search + anchor.hash
|
||||
if (currentUrl === newUrl) {
|
||||
window.scrollTo(0, 0)
|
||||
return
|
||||
}
|
||||
spaNavigate(anchor.pathname + anchor.search + anchor.hash)
|
||||
}
|
||||
}
|
||||
|
||||
node.addEventListener("click", onClick)
|
||||
|
||||
return {
|
||||
destroy() {
|
||||
node.removeEventListener("click", onClick)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const spaNavigate = (to: string, options?: { replace?: boolean }) => {
|
||||
overlays.update((current) => [])
|
||||
window.scrollTo(0, 0)
|
||||
//scroll to top of page
|
||||
setTimeout(
|
||||
() => {
|
||||
window.scrollTo(0, 0)
|
||||
},
|
||||
|
||||
100
|
||||
)
|
||||
|
||||
if (options?.replace) {
|
||||
window.history.replaceState(null, "", to)
|
||||
} else {
|
||||
window.history.pushState(null, "", to)
|
||||
}
|
||||
}
|
||||
|
||||
export const spaBack = () => {
|
||||
window.history.back()
|
||||
}
|
||||
|
||||
// TODO: spaLinks container for containing {@html ...}
|
||||
Reference in New Issue
Block a user