import { Lifecycle, Trigger, type TriggerAttributes } from "../base/index.js"; type Strategy = "hover" | "load" | "visible"; export interface PrefetchAttributes extends TriggerAttributes { /** When to prefetch the url. */ strategy?: Strategy; /** Prerender on the client with the Speculation Rules API. */ prerender?: boolean; /** URL to prefetch. */ url?: string; } // https://developer.chrome.com/blog/speculation-rules-improvements type SpeculationRules = { prerender?: DocumentRule[] | ListRule[]; prefetch?: DocumentRule[] | ListRule[]; }; type Rule = { expects_no_vary_search?: string; referrer_policy?: ReferrerPolicy; requires?: string[]; }; type DocumentRule = { source: "document"; where: WhereCondition; eagerness?: "immediate" | "moderate" | "eager" | "conservative"; } & Rule; type ListRule = { source: "list"; urls: string[] } & Rule; type WhereCondition = | { href_matches: string } | { selector_matches: string } | { and: WhereCondition[] } | { not: WhereCondition } | { or: WhereCondition[] }; /** * The `Prefetch` element can prefetch a url, or enhance the `HTMLAnchorElement` by loading the HTML for a page before it is navigated to. This element speeds up the navigation for multi-page applications (MPAs). * * If you are using a framework that already has a prefetch feature or uses a client side router, it is best to use the framework's feature instead of this element to ensure prefetching is working in accordance with the router. * * ### Attributes * * `strategy` * * Set the `strategy` attribute to specify the when the prefetch will take place. * * - `"hover"` - (default) After `mouseover`, `focus`, or `touchstart` for > 200ms * - `"visible"` - Uses an intersection observer to prefetch when the anchor is within the viewport. * - `"load"` - Immediately prefetches when the element is loaded, use carefully. * * `prerender` * * Use the `prerender` attribute to use the Speculation Rules API when supported to prerender on the client. This allows you to run client side JavaScript in advance instead of only fetching the HTML. * * Browsers that do not support will still use `` instead. * * [Speculation Rules Reference](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API) * * `url` * * Add a `url` attribute to immediately prefetch a url without having to provide * (or in addition to) `trigger` anchor elements. * * This element can be deprecated once the Speculation Rules API is supported across browsers. The API will be able to prefetch assets in a similar way with the `source: "document"` and `eagerness` features, and will work without JavaScript. */ export class Prefetch extends Lifecycle(Trigger()) { #prefetchedUrls = new Set(); constructor() { super(); } /** * Appends `` or `