-
-
Save songjiz/0664b0030d1f6cfb4aea86fec5b7b398 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "stimulus"; | |
import { get } from "@rails/request.js"; | |
import { PageSnapshot } from "@hotwired/turbo"; | |
export default class extends Controller { | |
static values = { hoverTime: Number }; | |
connect() { | |
this.element.addEventListener("mouseover", this.prefetch.bind(this)); | |
this.element.addEventListener("touchstart", this.prefetch.bind(this)); | |
} | |
async prefetch(e) { | |
if (this.prefetched) return; | |
const response = await get(this.url.toString()); | |
if (response.ok) { | |
const html = await response.html; | |
const snapshot = snapshotFromHTML(html); | |
Turbo.navigator.view.snapshotCache.put(this.url, snapshot); | |
} | |
} | |
get prefetched() { | |
return ( | |
location.href === this.url || | |
Turbo.navigator.view.snapshotCache.has(this.url) | |
); | |
} | |
get url() { | |
this._url = | |
this._url || new URL(this.element.getAttribute("href"), document.baseURI); | |
return this._url; | |
} | |
get hoverTime() { | |
return this.hoverTimeValue || 300; | |
} | |
} | |
const snapshotFromHTML = (html) => PageSnapshot.fromHTMLString(html); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment