{"version":3,"file":"barba-prefetch.mjs","sources":["../src/polyfills/requestIdleCallback.ts","../src/prefetch.ts"],"sourcesContent":["/**\n * @module prefetch/polyfills\n */\n/**\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// [source](https://github.com/GoogleChromeLabs/quicklink/blob/master/src/request-idle-callback.mjs)\n// RIC and shim for browsers setTimeout() without it\nexport const requestIdleCallback =\n  // @ts-ignore\n  window.requestIdleCallback ||\n  function ric(cb: any) {\n    const start = Date.now();\n\n    return setTimeout(() => {\n      cb({\n        didTimeout: false,\n        timeRemaining: function timeRemaining() {\n          return Math.max(0, 50 - (Date.now() - start));\n        },\n      });\n    }, 1);\n  };\n","/**\n * @barba/prefetch\n * <br><br>\n * ## Barba prefetch.\n *\n * @module prefetch\n * @preferred\n */\n\nimport { IPrefetchOptions } from './defs';\n\n/***/\n\n// Definitions\nimport { Core } from '@barba/core/src/core';\nimport { IBarbaPlugin, Link } from '@barba/core/src/defs';\nimport { Logger } from '@barba/core/src/modules/Logger';\n\nimport { version } from '../package.json';\nimport { requestIdleCallback } from './polyfills';\n\nclass Prefetch implements IBarbaPlugin<IPrefetchOptions> {\n  public name = '@barba/prefetch';\n  public version = version;\n  public barba: Core;\n  public logger: Logger;\n\n  public observer: IntersectionObserver;\n  public root: HTMLElement | HTMLDocument;\n  public timeout: number;\n  public limit: number;\n  public toPrefetch: Set<string> = new Set();\n\n  /**\n   * Plugin installation.\n   */\n  public install(\n    barba: Core,\n    { root = document.body, timeout = 2e3, limit = 0 }: IPrefetchOptions = {}\n  ) {\n    this.logger = new barba.Logger(this.name);\n    this.logger.info(this.version);\n    this.barba = barba;\n    this.root = root;\n    this.timeout = timeout;\n    this.limit = limit;\n  }\n\n  /**\n   * Plugin initialisation.\n   */\n  public init() {\n    if (this.barba.prefetchIgnore) {\n      this.logger.warn('barba.prefetchIgnore is enabled');\n\n      return;\n    }\n    if (this.barba.cacheIgnore) {\n      this.logger.warn('barba.cacheIgnore is enabled');\n\n      return;\n    }\n\n    /**\n     * Init intersection observer\n     * when intersecting, it will check if URL should be prefetched\n     * then unobserve the element\n     * and, if no cache data, fetch the page\n     */\n    /* istanbul ignore next */\n    this.observer = new IntersectionObserver(entries => {\n      entries.forEach(entry => {\n        if (!entry.isIntersecting) {\n          return;\n        }\n\n        const link = entry.target as Link;\n        const href = this.barba.url.getAbsoluteHref(this.barba.dom.getHref(link));\n\n        if (!this.toPrefetch.has(href)) {\n          return;\n        }\n\n        this.observer.unobserve(link);\n\n        // Prefetch and cache\n        if (!this.barba.cache.has(href)) {\n          this.barba.cache.set(\n            href,\n            this.barba\n              .request(\n                href,\n                this.barba.timeout,\n                this.barba['onRequestError'].bind(this.barba, 'barba'), // tslint:disable-line:no-string-literal\n                this.barba.cache,\n                this.barba.headers\n              )\n              .catch(error => {\n                this.logger.error(error);\n              }),\n            'prefetch',\n            'pending'\n          );\n        } else {\n          this.barba.cache.update(href, { action: 'prefetch' });\n        }\n      });\n    });\n    this.observe();\n\n    // Register hooks\n    this.barba.hooks.after(this.observe, this);\n  }\n\n  /* istanbul ignore next */\n  public observe(): void {\n    const timeout = this.timeout;\n\n    requestIdleCallback(\n      () => {\n        let links = Array.from(this.root.querySelectorAll('a'));\n\n        if (this.limit > 0) {\n          links = links.slice(0, this.limit);\n        }\n\n        // If not, find all links and use IntersectionObserver.\n        links.forEach(el => {\n          const link = (el as unknown) as Link;\n          const href = this.barba.dom.getHref(link);\n\n          if (\n            !this.barba.cache.has(href) &&\n            !this.barba.prevent.checkHref(href) &&\n            !this.barba.prevent.checkLink(link, {} as Event, href)\n          ) {\n            this.observer.observe(el);\n            this.toPrefetch.add(href);\n          }\n        });\n      },\n      { timeout }\n    );\n  }\n}\n\nconst prefetch = new Prefetch();\n\nexport default prefetch;\n"],"names":["requestIdleCallback","window","cb","start","Date","now","setTimeout","didTimeout","timeRemaining","Math","max","prefetch","Prefetch","this","name","version","barba","logger","observer","root","timeout","limit","toPrefetch","Set","_proto","prototype","install","_temp","_ref","_ref$root","document","body","_ref$timeout","_ref$limit","Logger","info","init","_this","prefetchIgnore","warn","cacheIgnore","IntersectionObserver","entries","forEach","entry","isIntersecting","link","target","href","url","getAbsoluteHref","dom","getHref","has","unobserve","cache","update","action","set","request","bind","headers","error","observe","hooks","after","_this2","links","Array","from","querySelectorAll","slice","el","prevent","checkHref","checkLink","add"],"mappings":"IAqBaA,EAEXC,OAAOD,qBACP,SAAaE,GACX,IAAWC,EAAGC,KAAKC,MAEnB,OAAiBC,WAAC,WAChBJ,EAAG,CACDK,YAAY,EACZC,cAAe,WACb,OAAOC,KAAKC,IAAI,EAAG,IAAMN,KAAKC,MAAQF,GACxC,GAEJ,EAAG,EACL,EC+GIQ,EAAW,iBA7HH,WAAA,SAAAC,IAAAC,KACLC,KAAO,kBAAiBD,KACxBE,gBAAiBF,KACjBG,WAAK,EAAAH,KACLI,YAAM,EAAAJ,KAENK,cAAQ,EAAAL,KACRM,UAAI,EAAAN,KACJO,aACAC,EAAAA,KAAAA,WACAC,EAAAA,KAAAA,WAA0B,IAASC,GAAA,CAAA,IAAAC,EAAAZ,EAAAa,UAgHzC,OAhHyCD,EAKnCE,QAAA,SACLV,EACyEW,GAAA,IAAAC,OAAA,IAAAD,EAAF,CAAE,QAAvER,KAAAA,OAAI,IAAAU,EAAGC,SAASC,KAAIF,EAAAG,EAAAJ,EAAER,QAAAA,OAAO,IAAAY,EAAG,IAAGA,EAAAC,EAAAL,EAAEP,MAAAA,OAAQ,IAAAY,EAAA,EAE/CA,EAAApB,KAAKI,OAAS,IAASD,EAACkB,OAAOrB,KAAKC,MACpCD,KA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