swup 3.0.0-rc.4 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/Swup.cjs +1 -1
  2. package/dist/Swup.cjs.map +1 -1
  3. package/dist/Swup.modern.js +1 -1
  4. package/dist/Swup.modern.js.map +1 -1
  5. package/dist/Swup.module.js +1 -1
  6. package/dist/Swup.module.js.map +1 -1
  7. package/dist/Swup.umd.js +1 -1
  8. package/dist/Swup.umd.js.map +1 -1
  9. package/dist/types/Swup.d.ts +14 -14
  10. package/dist/types/__test__/index.test.d.ts +1 -0
  11. package/dist/types/helpers/fetch.d.ts +2 -2
  12. package/dist/types/helpers.d.ts +10 -10
  13. package/dist/types/index.d.ts +3 -3
  14. package/dist/types/modules/Cache.d.ts +2 -2
  15. package/dist/types/modules/enterPage.d.ts +1 -1
  16. package/dist/types/modules/{on.d.ts → events.d.ts} +4 -2
  17. package/dist/types/modules/fetchPage.d.ts +3 -3
  18. package/dist/types/modules/getAnimationPromises.d.ts +1 -1
  19. package/dist/types/modules/getPageData.d.ts +2 -2
  20. package/dist/types/modules/leavePage.d.ts +2 -2
  21. package/dist/types/modules/loadPage.d.ts +1 -1
  22. package/dist/types/modules/plugins.d.ts +1 -1
  23. package/dist/types/modules/renderPage.d.ts +2 -2
  24. package/dist/types/modules/updateTransition.d.ts +1 -1
  25. package/dist/types/utils.d.ts +1 -1
  26. package/package.json +16 -8
  27. package/readme.md +2 -2
  28. package/src/Swup.ts +24 -26
  29. package/src/__test__/index.test.ts +52 -0
  30. package/src/helpers/createHistoryRecord.ts +1 -1
  31. package/src/helpers/fetch.ts +2 -2
  32. package/src/helpers/getDataFromHtml.ts +1 -1
  33. package/src/helpers/markSwupElements.ts +1 -1
  34. package/src/helpers/updateHistoryRecord.ts +1 -1
  35. package/src/helpers.ts +10 -10
  36. package/src/index.ts +3 -3
  37. package/src/modules/Cache.ts +3 -3
  38. package/src/modules/enterPage.ts +2 -2
  39. package/src/modules/events.ts +71 -0
  40. package/src/modules/fetchPage.ts +4 -4
  41. package/src/modules/getAnchorElement.ts +1 -1
  42. package/src/modules/getAnimationPromises.ts +2 -2
  43. package/src/modules/getPageData.ts +3 -3
  44. package/src/modules/leavePage.ts +2 -2
  45. package/src/modules/loadPage.ts +3 -3
  46. package/src/modules/plugins.ts +1 -1
  47. package/src/modules/renderPage.ts +3 -3
  48. package/src/modules/updateTransition.ts +1 -1
  49. package/src/utils.ts +1 -1
  50. package/dist/helpers.cjs +0 -2
  51. package/dist/helpers.cjs.map +0 -1
  52. package/dist/helpers.modern.js +0 -2
  53. package/dist/helpers.modern.js.map +0 -1
  54. package/dist/helpers.module.js +0 -2
  55. package/dist/helpers.module.js.map +0 -1
  56. package/dist/types/helpers/index.d.ts +0 -11
  57. package/dist/types/helpers/versionSatisfies.d.ts +0 -11
  58. package/dist/types/modules/off.d.ts +0 -3
  59. package/dist/types/modules/triggerEvent.d.ts +0 -3
  60. package/dist/utils.cjs +0 -2
  61. package/dist/utils.cjs.map +0 -1
  62. package/dist/utils.modern.js +0 -2
  63. package/dist/utils.modern.js.map +0 -1
  64. package/dist/utils.module.js +0 -2
  65. package/dist/utils.module.js.map +0 -1
  66. package/src/modules/off.ts +0 -21
  67. package/src/modules/on.ts +0 -33
  68. package/src/modules/triggerEvent.ts +0 -21
package/src/Swup.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import delegate from 'delegate-it';
2
2
 
3
- import version from './config/version.js';
3
+ import version from './config/version';
4
4
 
5
5
  import {
6
6
  cleanupAnimationClasses,
@@ -9,26 +9,24 @@ import {
9
9
  Location,
10
10
  markSwupElements,
11
11
  updateHistoryRecord
12
- } from './helpers.js';
13
- import { Unsubscribe } from './helpers/delegateEvent.js';
14
-
15
- import { Cache } from './modules/Cache.js';
16
- import { enterPage } from './modules/enterPage.js';
17
- import { getAnchorElement } from './modules/getAnchorElement.js';
18
- import { getAnimationPromises } from './modules/getAnimationPromises.js';
19
- import { getPageData } from './modules/getPageData.js';
20
- import { fetchPage } from './modules/fetchPage.js';
21
- import { leavePage } from './modules/leavePage.js';
22
- import { loadPage } from './modules/loadPage.js';
23
- import { replaceContent } from './modules/replaceContent.js';
24
- import { off } from './modules/off.js';
25
- import { on, Handlers } from './modules/on.js';
26
- import { use, unuse, findPlugin, Plugin } from './modules/plugins.js';
27
- import { renderPage } from './modules/renderPage.js';
28
- import { triggerEvent } from './modules/triggerEvent.js';
29
- import { updateTransition } from './modules/updateTransition.js';
30
-
31
- import { queryAll } from './utils.js';
12
+ } from './helpers';
13
+ import { Unsubscribe } from './helpers/delegateEvent';
14
+
15
+ import { Cache } from './modules/Cache';
16
+ import { enterPage } from './modules/enterPage';
17
+ import { getAnchorElement } from './modules/getAnchorElement';
18
+ import { getAnimationPromises } from './modules/getAnimationPromises';
19
+ import { getPageData } from './modules/getPageData';
20
+ import { fetchPage } from './modules/fetchPage';
21
+ import { leavePage } from './modules/leavePage';
22
+ import { loadPage } from './modules/loadPage';
23
+ import { replaceContent } from './modules/replaceContent';
24
+ import { on, off, triggerEvent, Handlers } from './modules/events';
25
+ import { use, unuse, findPlugin, Plugin } from './modules/plugins';
26
+ import { renderPage } from './modules/renderPage';
27
+ import { updateTransition } from './modules/updateTransition';
28
+
29
+ import { queryAll } from './utils';
32
30
 
33
31
  export type Transition = {
34
32
  from?: string;
@@ -49,7 +47,7 @@ export type Options = {
49
47
  requestHeaders: Record<string, string>;
50
48
  plugins: Plugin[];
51
49
  skipPopStateHandling: (event: any) => boolean;
52
- ignoreVisit: (href: string, { el }: { el?: Element }) => boolean;
50
+ ignoreVisit: (url: string, { el }: { el?: Element }) => boolean;
53
51
  resolveUrl: (url: string) => string;
54
52
  };
55
53
 
@@ -122,7 +120,7 @@ export default class Swup {
122
120
  animationSelector: '[class*="transition-"]',
123
121
  cache: true,
124
122
  containers: ['#swup'],
125
- ignoreVisit: (href, { el } = {}) => !!el?.closest('[data-no-swup]'),
123
+ ignoreVisit: (url, { el } = {}) => !!el?.closest('[data-no-swup]'),
126
124
  linkSelector: 'a[href]',
127
125
  plugins: [],
128
126
  resolveUrl: (url) => url,
@@ -216,9 +214,9 @@ export default class Swup {
216
214
  }
217
215
 
218
216
  shouldIgnoreVisit(href: string, { el }: { el?: Element } = {}) {
219
- const { origin } = Location.fromUrl(href);
217
+ const { origin, url, hash } = Location.fromUrl(href);
220
218
 
221
- // Ignore if the new URL's origin doesn't match the current one
219
+ // Ignore if the new origin doesn't match the current one
222
220
  if (origin !== window.location.origin) {
223
221
  return true;
224
222
  }
@@ -229,7 +227,7 @@ export default class Swup {
229
227
  }
230
228
 
231
229
  // Ignore if the visit should be ignored as per user options
232
- if (this.options.ignoreVisit(href, { el })) {
230
+ if (this.options.ignoreVisit(url + hash, { el })) {
233
231
  return true;
234
232
  }
235
233
 
@@ -0,0 +1,52 @@
1
+ import Swup, { Options, Plugin } from '../index';
2
+
3
+ console.log = jest.fn();
4
+ console.warn = jest.fn();
5
+ console.error = jest.fn();
6
+
7
+ const baseUrl = window.location.origin;
8
+
9
+ describe('exports', () => {
10
+ it('exports Swup, and Options/Plugin types', () => {
11
+ class SwupPlugin implements Plugin {
12
+ name = 'SwupPlugin';
13
+ isSwupPlugin = true as const;
14
+ mount = () => {};
15
+ unmount = () => {};
16
+ }
17
+
18
+ const options: Partial<Options> = {
19
+ animateHistoryBrowsing: false,
20
+ animationSelector: '[class*="transition-"]',
21
+ cache: true,
22
+ containers: ['#swup'],
23
+ ignoreVisit: (url, { el } = {}) => !!el?.closest('[data-no-swup]'),
24
+ linkSelector: 'a[href]',
25
+ plugins: [new SwupPlugin()],
26
+ resolveUrl: (url) => url,
27
+ requestHeaders: {
28
+ 'X-Requested-With': 'swup',
29
+ Accept: 'text/html, application/xhtml+xml'
30
+ },
31
+ skipPopStateHandling: (event) => event.state?.source !== 'swup'
32
+ };
33
+
34
+ const swup = new Swup(options);
35
+
36
+ expect(swup.version).not.toBeUndefined();
37
+ });
38
+
39
+ it('passes relative URL to ignoreVisit', () => {
40
+ let ignorableUrl = 'nothing';
41
+ const swup = new Swup({
42
+ ignoreVisit: (url, { el } = {}) => {
43
+ ignorableUrl = url;
44
+ return false;
45
+ }
46
+ });
47
+
48
+ swup.shouldIgnoreVisit(baseUrl + '/path/?query#hash');
49
+
50
+ expect(ignorableUrl).toEqual('/path/?query#hash');
51
+ });
52
+ });
@@ -1,4 +1,4 @@
1
- import { getCurrentUrl } from './getCurrentUrl.js';
1
+ import { getCurrentUrl } from './getCurrentUrl';
2
2
 
3
3
  export const createHistoryRecord = (
4
4
  url: string,
@@ -1,5 +1,5 @@
1
- import { TransitionOptions } from '../modules/loadPage.js';
2
- import { Options } from '../Swup.js';
1
+ import { TransitionOptions } from '../modules/loadPage';
2
+ import { Options } from '../Swup';
3
3
 
4
4
  export const fetch = (
5
5
  options: TransitionOptions & { headers: Options['requestHeaders'] },
@@ -1,4 +1,4 @@
1
- import { query, queryAll } from '../utils.js';
1
+ import { query, queryAll } from '../utils';
2
2
 
3
3
  export type PageHtmlData = {
4
4
  title: string;
@@ -1,4 +1,4 @@
1
- import { query, queryAll } from '../utils.js';
1
+ import { query, queryAll } from '../utils';
2
2
 
3
3
  export const markSwupElements = (element: Element, containers: string[]): void => {
4
4
  let blocks = 0;
@@ -1,4 +1,4 @@
1
- import { getCurrentUrl } from './getCurrentUrl.js';
1
+ import { getCurrentUrl } from './getCurrentUrl';
2
2
 
3
3
  export const updateHistoryRecord = (
4
4
  url: string | null = null,
package/src/helpers.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  // Re-export all helpers to allow custom package export path
2
2
  // e.g. import { getPageData } from 'swup/helpers'
3
3
 
4
- export { classify } from './helpers/classify.js';
5
- export { createHistoryRecord } from './helpers/createHistoryRecord.js';
6
- export { updateHistoryRecord } from './helpers/updateHistoryRecord.js';
7
- export { delegateEvent } from './helpers/delegateEvent.js';
8
- export { getDataFromHtml } from './helpers/getDataFromHtml.js';
9
- export { fetch } from './helpers/fetch.js';
10
- export { getCurrentUrl } from './helpers/getCurrentUrl.js';
11
- export { Location } from './helpers/Location.js';
12
- export { markSwupElements } from './helpers/markSwupElements.js';
13
- export { cleanupAnimationClasses } from './helpers/cleanupAnimationClasses.js';
4
+ export { classify } from './helpers/classify';
5
+ export { createHistoryRecord } from './helpers/createHistoryRecord';
6
+ export { updateHistoryRecord } from './helpers/updateHistoryRecord';
7
+ export { delegateEvent } from './helpers/delegateEvent';
8
+ export { getDataFromHtml } from './helpers/getDataFromHtml';
9
+ export { fetch } from './helpers/fetch';
10
+ export { getCurrentUrl } from './helpers/getCurrentUrl';
11
+ export { Location } from './helpers/Location';
12
+ export { markSwupElements } from './helpers/markSwupElements';
13
+ export { cleanupAnimationClasses } from './helpers/cleanupAnimationClasses';
package/src/index.ts CHANGED
@@ -1,9 +1,9 @@
1
- import Swup, { Options } from './Swup.js';
1
+ import Swup, { Options } from './Swup';
2
2
  import { Plugin } from './modules/plugins';
3
3
 
4
4
  export default Swup;
5
5
 
6
- export * from './helpers.js';
7
- export * from './utils.js';
6
+ export * from './helpers';
7
+ export * from './utils';
8
8
 
9
9
  export type { Options, Plugin };
@@ -1,6 +1,6 @@
1
- import { getCurrentUrl, Location } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageData } from './getPageData.js';
1
+ import { getCurrentUrl, Location } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageData } from './getPageData';
4
4
 
5
5
  export interface PageRecord extends PageData {
6
6
  url: string;
@@ -1,5 +1,5 @@
1
- import { nextTick } from '../utils.js';
2
- import Swup from '../Swup.js';
1
+ import { nextTick } from '../utils';
2
+ import Swup from '../Swup';
3
3
 
4
4
  export const enterPage = function (
5
5
  this: Swup,
@@ -0,0 +1,71 @@
1
+ import Swup from '../Swup';
2
+
3
+ export type EventType =
4
+ | 'animationInDone'
5
+ | 'animationInStart'
6
+ | 'animationOutDone'
7
+ | 'animationOutStart'
8
+ | 'animationSkipped'
9
+ | 'clickLink'
10
+ | 'contentReplaced'
11
+ | 'disabled'
12
+ | 'enabled'
13
+ | 'openPageInNewTab'
14
+ | 'pageLoaded'
15
+ | 'pageRetrievedFromCache'
16
+ | 'pageView'
17
+ | 'popState'
18
+ | 'samePage'
19
+ | 'samePageWithHash'
20
+ | 'serverError'
21
+ | 'transitionStart'
22
+ | 'transitionEnd'
23
+ | 'willReplaceContent';
24
+ export type Handler = (event?: Event) => void;
25
+ export type Handlers = Record<EventType, Handler[]>;
26
+
27
+ export function on(this: Swup, event: EventType, handler: Handler) {
28
+ if (this._handlers[event]) {
29
+ this._handlers[event].push(handler);
30
+ } else {
31
+ console.warn(`Unsupported event ${event}.`);
32
+ }
33
+ }
34
+
35
+ export function off(this: Swup, event?: EventType, handler?: Handler) {
36
+ if (event && handler) {
37
+ // Remove specific handler
38
+ if (this._handlers[event].includes(handler)) {
39
+ this._handlers[event] = this._handlers[event].filter((h) => h !== handler);
40
+ } else {
41
+ console.warn(`Handler for event '${event}' not found.`);
42
+ }
43
+ } else if (event) {
44
+ // Remove all handlers for specific event
45
+ this._handlers[event] = [];
46
+ } else {
47
+ // Remove all handlers for all events
48
+ Object.keys(this._handlers).forEach((event) => {
49
+ this._handlers[event as EventType] = [];
50
+ });
51
+ }
52
+ }
53
+
54
+ export function triggerEvent(
55
+ this: Swup,
56
+ eventName: EventType,
57
+ originalEvent?: PopStateEvent | MouseEvent
58
+ ): void {
59
+ // call saved handlers with "on" method and pass originalEvent object if available
60
+ this._handlers[eventName].forEach((handler) => {
61
+ try {
62
+ handler(originalEvent);
63
+ } catch (error) {
64
+ console.error(error);
65
+ }
66
+ });
67
+
68
+ // trigger event on document with prefix "swup:"
69
+ const event = new CustomEvent(`swup:${eventName}`, { detail: eventName });
70
+ document.dispatchEvent(event);
71
+ }
@@ -1,7 +1,7 @@
1
- import Swup from '../Swup.js';
2
- import { fetch } from '../helpers.js';
3
- import { TransitionOptions } from './loadPage.js';
4
- import { PageRecord } from './Cache.js';
1
+ import Swup from '../Swup';
2
+ import { fetch } from '../helpers';
3
+ import { TransitionOptions } from './loadPage';
4
+ import { PageRecord } from './Cache';
5
5
 
6
6
  export function fetchPage(this: Swup, data: TransitionOptions): Promise<PageRecord> {
7
7
  const headers = this.options.requestHeaders;
@@ -1,4 +1,4 @@
1
- import { escapeCssIdentifier, query } from '../utils.js';
1
+ import { escapeCssIdentifier, query } from '../utils';
2
2
 
3
3
  export const getAnchorElement = (hash: string): Element | null => {
4
4
  if (!hash) {
@@ -1,5 +1,5 @@
1
- import { queryAll, toMs } from '../utils.js';
2
- import Swup from '../Swup.js';
1
+ import { queryAll, toMs } from '../utils';
2
+ import Swup from '../Swup';
3
3
 
4
4
  // Transition property/event sniffing
5
5
  let transitionProp = 'transition';
@@ -1,6 +1,6 @@
1
- import { getDataFromHtml } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageHtmlData } from '../helpers/getDataFromHtml.js';
1
+ import { getDataFromHtml } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageHtmlData } from '../helpers/getDataFromHtml';
4
4
 
5
5
  export type PageData = PageHtmlData & {
6
6
  responseURL: string;
@@ -1,5 +1,5 @@
1
- import Swup from '../Swup.js';
2
- import { TransitionOptions } from './loadPage.js';
1
+ import Swup from '../Swup';
2
+ import { TransitionOptions } from './loadPage';
3
3
 
4
4
  export const leavePage = function (
5
5
  this: Swup,
@@ -1,6 +1,6 @@
1
- import { classify, createHistoryRecord, getCurrentUrl } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageRecord } from './Cache.js';
1
+ import { classify, createHistoryRecord, getCurrentUrl } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageRecord } from './Cache';
4
4
 
5
5
  export type TransitionOptions = {
6
6
  url: string;
@@ -1,4 +1,4 @@
1
- import Swup from '../Swup.js';
1
+ import Swup from '../Swup';
2
2
 
3
3
  export type Plugin = {
4
4
  name: string;
@@ -1,6 +1,6 @@
1
- import { Location, updateHistoryRecord, getCurrentUrl } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageRecord } from './Cache.js';
1
+ import { Location, updateHistoryRecord, getCurrentUrl } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageRecord } from './Cache';
4
4
 
5
5
  export const renderPage = function (
6
6
  this: Swup,
@@ -1,4 +1,4 @@
1
- import Swup from '../Swup.js';
1
+ import Swup from '../Swup';
2
2
 
3
3
  export const updateTransition = function (
4
4
  this: Swup,
package/src/utils.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  // Re-export all utils to allow custom package export path
2
2
  // e.g. import { queryAll } from 'swup/utils'
3
3
 
4
- export * from './utils/index.js';
4
+ export * from './utils/index';
package/dist/helpers.cjs DELETED
@@ -1,2 +0,0 @@
1
- function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t=/*#__PURE__*/e(require("delegate-it"));const n=function(e){let{hash:t}=void 0===e?{}:e;return location.pathname+location.search+(t?location.hash:"")},o=function(e,t){return void 0===t&&(t=document),t.querySelector(e)},r=function(e,t){return void 0===t&&(t=document),Array.from(t.querySelectorAll(e))};class a extends URL{constructor(e,t){void 0===t&&(t=document.baseURI),super(e.toString(),t)}get url(){return this.pathname+this.search}static fromElement(e){const t=e.getAttribute("href")||e.getAttribute("xlink:href");return new a(t)}static fromUrl(e){return new a(e)}}const s=e=>/^to-/.test(e)||["is-changing","is-rendering","is-popstate"].includes(e),c=e=>String(e).split(".").concat(["0","0"]).slice(0,3).join(".");exports.Location=a,exports.classify=(e,t)=>String(e).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/,"")||t||"",exports.cleanupAnimationClasses=()=>{const e=document.documentElement.className.split(" ").filter(s);document.documentElement.classList.remove(...e)},exports.createHistoryRecord=function(e,t){void 0===t&&(t={});const o={url:e=e||n({hash:!0}),random:Math.random(),source:"swup",...t};history.pushState(o,"",e)},exports.delegateEvent=function(e,n,o,r){let{base:a=document,...s}=void 0===r?{}:r;const c=t.default(a,e,n,o,s);return{destroy:()=>c.destroy()}},exports.fetch=(e,t)=>{const n={url:window.location.pathname+window.location.search,method:"GET",data:null,headers:{}},{url:o,method:r,headers:a,data:s}={...n,...e},c=new XMLHttpRequest;return c.onreadystatechange=function(){4===c.readyState&&t(c)},c.open(r,o,!0),Object.entries(a).forEach(e=>{let[t,n]=e;c.setRequestHeader(t,n)}),c.send(s),c},exports.getCurrentUrl=n,exports.getDataFromHtml=(e,t)=>{var n,a;let s=document.createElement("html");s.innerHTML=e;let c=[];t.forEach(e=>{if(null==o(e,s))return console.warn("[swup] Container "+e+" not found on page."),null;r(e).length!==r(e,s).length&&console.warn("[swup] Mismatched number of containers found on new page."),r(e).forEach((t,n)=>{r(e,s)[n].setAttribute("data-swup",String(c.length)),c.push(r(e,s)[n].outerHTML)})});const i=(null==(n=o("title",s))?void 0:n.innerText)||"",l=null==(a=o("body",s))?void 0:a.className;return s.innerHTML="",s=null,{title:i,pageClass:l,blocks:c,originalContent:e}},exports.markSwupElements=(e,t)=>{let n=0;t.forEach(t=>{null==o(t,e)?console.warn("[swup] Container "+t+" not found on page."):r(t).forEach((o,a)=>{r(t,e)[a].setAttribute("data-swup",String(n)),n++})})},exports.updateHistoryRecord=function(e,t){void 0===e&&(e=null),void 0===t&&(t={}),e=e||n({hash:!0});const o={...history.state,url:e,random:Math.random(),source:"swup",...t};history.replaceState(o,"",e)},exports.versionSatisfies=(e,t)=>t.every(t=>{const[,n,o]=t.match(/^([\D]+)?(.*)$/)||[];var r,a;return((e,t)=>{const n={"":e=>0===e,">":e=>e>0,">=":e=>e>=0,"<":e=>e<0,"<=":e=>e<=0};return(n[t]||n[""])(e)})((a=o,r=c(r=e),a=c(a),r.localeCompare(a,void 0,{numeric:!0})),n||">=")});
2
- //# sourceMappingURL=helpers.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.cjs","sources":["../src/helpers/classify.ts","../src/helpers/getCurrentUrl.ts","../src/utils/index.ts","../src/helpers/Location.ts","../src/helpers/markSwupElements.ts","../src/helpers/cleanupAnimationClasses.ts","../src/helpers/versionSatisfies.ts","../src/helpers/createHistoryRecord.ts","../src/helpers/delegateEvent.ts","../src/helpers/fetch.ts","../src/helpers/getDataFromHtml.ts","../src/helpers/updateHistoryRecord.ts"],"sourcesContent":["const classify = (text: string, fallback?: string): string => {\n\tconst output = String(text)\n\t\t.toLowerCase()\n\t\t// .normalize('NFD') // split an accented letter in the base letter and the acent\n\t\t// .replace(/[\\u0300-\\u036f]/g, '') // remove all previously split accents\n\t\t.replace(/[\\s/_.]+/g, '-') // replace spaces and _./ with '-'\n\t\t.replace(/[^\\w-]+/g, '') // remove all non-word chars\n\t\t.replace(/--+/g, '-') // replace repeating '-' with single '-'\n\t\t.replace(/^-+|-+$/, ''); // trim '-' from edges\n\treturn output || fallback || '';\n};\n\nexport default classify;\n","const getCurrentUrl = ({ hash }: { hash?: boolean } = {}): string => {\n\treturn location.pathname + location.search + (hash ? location.hash : '');\n};\n\nexport default getCurrentUrl;\n","export const query = (selector: string, context: Document | Element = document) => {\n\treturn context.querySelector<HTMLElement>(selector);\n};\n\nexport const queryAll = (\n\tselector: string,\n\tcontext: Document | Element = document\n): HTMLElement[] => {\n\treturn Array.from(context.querySelectorAll(selector));\n};\n\nexport const nextTick = (callback: () => void) => {\n\trequestAnimationFrame(() => {\n\t\trequestAnimationFrame(() => {\n\t\t\tcallback();\n\t\t});\n\t});\n};\n\nexport const escapeCssIdentifier = (ident: string) => {\n\t// @ts-ignore this is for support check, so it's correct that TS complains\n\tif (window.CSS && window.CSS.escape) {\n\t\treturn CSS.escape(ident);\n\t} else {\n\t\treturn ident;\n\t}\n};\n\n// Fix for Chrome below v61 formatting CSS floats with comma in some locales\nexport const toMs = (s: string) => {\n\treturn Number(s.slice(0, -1).replace(',', '.')) * 1000;\n};\n","/**\n * A helper for creating a Location from either an element\n * or a URL object/string\n *\n * Note: this could be implemented as a class inheriting from URL\n * Except: Babel will add tons of boilerplate for ES6 classes + getters\n * So for now it's implemented as an augmented URL object with custom getter\n *\n * class Location extends URL {\n * get url() {\n *\t return this.pathname + this.search;\n * }\n * }\n *\n */\n\nexport default class Location extends URL {\n\tconstructor(url: string, base: string = document.baseURI) {\n\t\tsuper(url.toString(), base);\n\t}\n\n\tget url() {\n\t\treturn this.pathname + this.search;\n\t}\n\n\t/**\n\t * Instantiate a Location from an element's href attribute\n\t * @param {Element} el\n\t * @return new Location instance\n\t */\n\tstatic fromElement(el: HTMLAnchorElement): Location {\n\t\tconst href = el.getAttribute('href') || el.getAttribute('xlink:href');\n\t\treturn new Location(href!);\n\t}\n\n\t/**\n\t * Instantiate a Location from a URL object or string\n\t * @param {URL|string} url\n\t * @return new Location instance\n\t */\n\tstatic fromUrl(url: string): Location {\n\t\treturn new Location(url);\n\t}\n}\n","import { query, queryAll } from '../utils.js';\n\nconst markSwupElements = (element: Element, containers: string[]): void => {\n\tlet blocks = 0;\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, element) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t} else {\n\t\t\tqueryAll(selector).forEach((item: Element, index: number) => {\n\t\t\t\tqueryAll(selector, element)[index].setAttribute('data-swup', String(blocks));\n\t\t\t\tblocks++;\n\t\t\t});\n\t\t}\n\t});\n};\n\nexport default markSwupElements;\n","const isSwupClass = (className: string): boolean =>\n\t/^to-/.test(className) || ['is-changing', 'is-rendering', 'is-popstate'].includes(className);\n\nconst cleanupAnimationClasses = (): void => {\n\tconst htmlClasses = document.documentElement.className.split(' ');\n\tconst removeClasses = htmlClasses.filter(isSwupClass);\n\tdocument.documentElement.classList.remove(...removeClasses);\n};\n\nexport default cleanupAnimationClasses;\n","type Comparator = '>' | '>=' | '<' | '<=';\n\n// Fill versions to exactly 3 decimals\nconst normalizeVersion = (version: string): string => {\n\treturn String(version).split('.').concat(['0', '0']).slice(0, 3).join('.');\n};\n\n// Numerically compare version strings after normalizing them\nconst compareVersion = (a: string, b: string): number => {\n\ta = normalizeVersion(a);\n\tb = normalizeVersion(b);\n\treturn a.localeCompare(b, undefined, { numeric: true });\n};\n\n// Apply a comparator (equals, greater-than, etc) by its symbol to a sort comparison\nconst applyComparator = (comparisonResult: number, comparator: Comparator) => {\n\tconst comparators = {\n\t\t'': (r: number) => r === 0,\n\t\t'>': (r: number) => r > 0,\n\t\t'>=': (r: number) => r >= 0,\n\t\t'<': (r: number) => r < 0,\n\t\t'<=': (r: number) => r <= 0\n\t};\n\tconst comparatorFn = comparators[comparator] || comparators[''];\n\treturn comparatorFn(comparisonResult);\n};\n\n/**\n * Check if a version satisfies all given version requirements\n *\n * versionSatisfies('2.1.0', ['>=2', '<4']) // true\n * versionSatisfies('2.1.0', ['5']) // false\n *\n * @param {string} installed Installed version\n * @param {Array.<string>} requirements Array of requirements that must be satisfied\n * @returns boolean\n */\nexport const versionSatisfies = (installed: string, requirements: string[]) => {\n\treturn requirements.every((required) => {\n\t\tconst [, comparator, version] = required.match(/^([\\D]+)?(.*)$/) || [];\n\t\tconst comparisonResult = compareVersion(installed, version);\n\t\treturn applyComparator(comparisonResult, (comparator as Comparator) || '>=');\n\t});\n};\n\nexport default versionSatisfies;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst createHistoryRecord = (url: string, customData: Record<string, unknown> = {}): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.pushState(data, '', url);\n};\n\nexport default createHistoryRecord;\n","import delegate, { EventType } from 'delegate-it';\nimport { ParseSelector } from 'typed-query-selector/parser';\n\nexport type Unsubscribe = {\n\tdestroy: () => void;\n};\nconst delegateEvent = <Selector extends string, TEvent extends EventType>(\n\tselector: Selector,\n\ttype: TEvent,\n\tcallback: delegate.EventHandler<GlobalEventHandlersEventMap[TEvent]>,\n\t{ base = document, ...eventOptions } = {}\n): Unsubscribe => {\n\tconst delegation = delegate<string, ParseSelector<Selector, HTMLElement>, TEvent>(\n\t\tbase,\n\t\tselector,\n\t\ttype,\n\t\tcallback,\n\t\teventOptions\n\t);\n\treturn { destroy: () => delegation.destroy() };\n};\n\nexport default delegateEvent;\n","import { TransitionOptions } from '../modules/loadPage.js';\nimport { Options } from '../Swup.js';\n\nconst fetch = (\n\toptions: TransitionOptions & { headers: Options['requestHeaders'] },\n\tcallback: (request: XMLHttpRequest) => void\n): XMLHttpRequest => {\n\tconst defaults = {\n\t\turl: window.location.pathname + window.location.search,\n\t\tmethod: 'GET',\n\t\tdata: null,\n\t\theaders: {}\n\t};\n\n\tconst { url, method, headers, data } = { ...defaults, ...options };\n\n\tconst request = new XMLHttpRequest();\n\n\trequest.onreadystatechange = function () {\n\t\tif (request.readyState === 4) {\n\t\t\t// if (request.status === 500) {} else {}\n\t\t\tcallback(request);\n\t\t}\n\t};\n\n\trequest.open(method, url, true);\n\tObject.entries(headers).forEach(([key, header]) => {\n\t\trequest.setRequestHeader(key, header);\n\t});\n\trequest.send(data);\n\n\treturn request;\n};\n\nexport default fetch;\n","import { query, queryAll } from '../utils.js';\n\nexport type PageHtmlData = {\n\ttitle: string;\n\toriginalContent: string;\n\tblocks: string[];\n\tpageClass?: string;\n};\n\nconst getDataFromHtml = (html: string, containers: string[]): PageHtmlData => {\n\tlet fakeDom = document.createElement('html');\n\tfakeDom.innerHTML = html;\n\tlet blocks: string[] = [];\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, fakeDom) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t\treturn null;\n\t\t} else {\n\t\t\tif (queryAll(selector).length !== queryAll(selector, fakeDom).length) {\n\t\t\t\tconsole.warn(`[swup] Mismatched number of containers found on new page.`);\n\t\t\t}\n\t\t\tqueryAll(selector).forEach((item, index) => {\n\t\t\t\tqueryAll(selector, fakeDom)[index].setAttribute('data-swup', String(blocks.length));\n\t\t\t\tblocks.push(queryAll(selector, fakeDom)[index].outerHTML);\n\t\t\t});\n\t\t}\n\t});\n\n\tconst title = query('title', fakeDom)?.innerText || '';\n\tconst pageClass = query('body', fakeDom)?.className;\n\n\t// to prevent memory leaks\n\tfakeDom.innerHTML = '';\n\t// @ts-ignore don't want to type it as possible null, since it's created at the top of the function always\n\tfakeDom = null;\n\n\treturn { title, pageClass, blocks, originalContent: html };\n};\n\nexport default getDataFromHtml;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst updateHistoryRecord = (\n\turl: string | null = null,\n\tcustomData: Record<string, unknown> = {}\n): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\t...history.state,\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.replaceState(data, '', url);\n};\n\nexport default updateHistoryRecord;\n"],"names":["classify","getCurrentUrl","_temp","hash","pathname","location","search","query","selector","context","document","querySelector","queryAll","Array","from","querySelectorAll","Location","constructor","url","base","baseURI","super","toString","this","static","el","getAttribute","href","markSwupElements","isSwupClass","className","test","includes","normalizeVersion","version","String","split","concat","slice","join","text","fallback","toLowerCase","replace","removeClasses","documentElement","filter","classList","remove","customData","data","random","Math","source","history","pushState","type","callback","eventOptions","delegate","destroy","delegation","options","defaults","window","method","headers","request","XMLHttpRequest","onreadystatechange","readyState","open","Object","entries","forEach","_ref","key","header","setRequestHeader","send","html","containers","_query","_query2","createElement","fakeDom","innerHTML","blocks","console","warn","length","item","index","setAttribute","push","outerHTML","title","innerText","pageClass","originalContent","element","state","replaceState","installed","requirements","every","required","comparator","match","a","b","comparisonResult","comparators","r","applyComparator","localeCompare","undefined","numeric"],"mappings":"qHAAMA,MCAaC,EAAG,SAA8CC,GAAA,IAA7CC,KAAEA,QAA6B,IAAAD,EAAA,CAAE,EACvDA,EAAA,gBAAgBE,SAAWC,SAASC,QAAUH,EAAOE,SAASF,KAAO,GACtE,ECFaI,EAAQ,SAACC,EAAkBC,GACvC,YADuC,IAAAA,IAAAA,EAA8BC,UACvDD,EAACE,cAA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CAACoB,EAAkBnB,KAC3C,IAAUM,EAAG,EAEbN,EAAWP,QAASlE,IACa,MAA5BD,EAAMC,EAAU4F,GACnBZ,QAAQC,KAAI,oBAAqBjF,EACjC,uBACAI,EAASJ,GAAUkE,QAAQ,CAACiB,EAAeC,KAC1ChF,EAASJ,EAAU4F,GAASR,GAAOC,aAAa,YAAa1D,OAAOoD,IACpEA,GAAM,EAEP,EAEH,8BOb4B,SAC3BrE,EACA+B,YADA/B,IAAAA,EAAqB,WACrB+B,IAAAA,IAAAA,EAAsC,CAAE,GAExC/B,EAAMA,GAAOjB,EAAc,CAAEE,MAAM,IACnC,QAAa,IACTmD,QAAQ+C,MACXnF,MACAiC,OAAQC,KAAKD,SACbE,OAAQ,UACLJ,GAEJK,QAAQgD,aAAapD,EAAM,GAAIhC,EAChC,2BLsBgC,CAACqF,EAAmBC,IAC5CA,EAAaC,MAAOC,IAC1B,OAASC,EAAYzE,GAAWwE,EAASE,MAAM,mBAAqB,GA/B/C,IAACC,EAAWC,EAiCjC,MA1BsB,EAACC,EAA0BJ,KAClD,MAAMK,EAAc,CACnB,GAAKC,GAAoB,IAANA,EACnB,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,EAC1B,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,GAG3B,OADqBD,EAAYL,IAAeK,EAAY,KACxCD,EAAgB,EAiB5BG,EAjC0BJ,EAgCkB5E,EA/BpD2E,EAAI5E,EADmB4E,EAgCkBN,GA9BzCO,EAAI7E,EAAiB6E,GACbD,EAACM,cAAcL,OAAGM,EAAW,CAAEC,SAAS,KA8BLV,GAA6B,KAAI"}
@@ -1,2 +0,0 @@
1
- import e from"delegate-it";const t=(e,t)=>String(e).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/,"")||t||"";function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(this,arguments)}const r=({hash:e}={})=>location.pathname+location.search+(e?location.hash:""),o=(e,t={})=>{const o=n({url:e=e||r({hash:!0}),random:Math.random(),source:"swup"},t);history.pushState(o,"",e)},a=(e=null,t={})=>{e=e||r({hash:!0});const o=n({},history.state,{url:e,random:Math.random(),source:"swup"},t);history.replaceState(o,"",e)},s=["base"],c=(t,n,r,o={})=>{let{base:a=document}=o,c=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)t.indexOf(n=a[r])>=0||(o[n]=e[n]);return o}(o,s);const l=e(a,t,n,r,c);return{destroy:()=>l.destroy()}},l=(e,t=document)=>t.querySelector(e),u=(e,t=document)=>Array.from(t.querySelectorAll(e)),i=(e,t)=>{var n,r;let o=document.createElement("html");o.innerHTML=e;let a=[];t.forEach(e=>{if(null==l(e,o))return console.warn(`[swup] Container ${e} not found on page.`),null;u(e).length!==u(e,o).length&&console.warn("[swup] Mismatched number of containers found on new page."),u(e).forEach((t,n)=>{u(e,o)[n].setAttribute("data-swup",String(a.length)),a.push(u(e,o)[n].outerHTML)})});const s=(null==(n=l("title",o))?void 0:n.innerText)||"",c=null==(r=l("body",o))?void 0:r.className;return o.innerHTML="",o=null,{title:s,pageClass:c,blocks:a,originalContent:e}},h=(e,t)=>{const r={url:window.location.pathname+window.location.search,method:"GET",data:null,headers:{}},{url:o,method:a,headers:s,data:c}=n({},r,e),l=new XMLHttpRequest;return l.onreadystatechange=function(){4===l.readyState&&t(l)},l.open(a,o,!0),Object.entries(s).forEach(([e,t])=>{l.setRequestHeader(e,t)}),l.send(c),l};class d extends URL{constructor(e,t=document.baseURI){super(e.toString(),t)}get url(){return this.pathname+this.search}static fromElement(e){const t=e.getAttribute("href")||e.getAttribute("xlink:href");return new d(t)}static fromUrl(e){return new d(e)}}const m=(e,t)=>{let n=0;t.forEach(t=>{null==l(t,e)?console.warn(`[swup] Container ${t} not found on page.`):u(t).forEach((r,o)=>{u(t,e)[o].setAttribute("data-swup",String(n)),n++})})},p=e=>/^to-/.test(e)||["is-changing","is-rendering","is-popstate"].includes(e),g=()=>{const e=document.documentElement.className.split(" ").filter(p);document.documentElement.classList.remove(...e)},f=e=>String(e).split(".").concat(["0","0"]).slice(0,3).join("."),w=(e,t)=>t.every(t=>{const[,n,r]=t.match(/^([\D]+)?(.*)$/)||[];var o,a;return((e,t)=>{const n={"":e=>0===e,">":e=>e>0,">=":e=>e>=0,"<":e=>e<0,"<=":e=>e<=0};return(n[t]||n[""])(e)})((a=r,o=f(o=e),a=f(a),o.localeCompare(a,void 0,{numeric:!0})),n||">=")});export{d as Location,t as classify,g as cleanupAnimationClasses,o as createHistoryRecord,c as delegateEvent,h as fetch,r as getCurrentUrl,i as getDataFromHtml,m as markSwupElements,a as updateHistoryRecord,w as versionSatisfies};
2
- //# sourceMappingURL=helpers.modern.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.modern.js","sources":["../src/helpers/classify.ts","../src/helpers/getCurrentUrl.ts","../src/helpers/createHistoryRecord.ts","../src/helpers/updateHistoryRecord.ts","../src/helpers/delegateEvent.ts","../src/utils/index.ts","../src/helpers/getDataFromHtml.ts","../src/helpers/fetch.ts","../src/helpers/Location.ts","../src/helpers/markSwupElements.ts","../src/helpers/cleanupAnimationClasses.ts","../src/helpers/versionSatisfies.ts"],"sourcesContent":["const classify = (text: string, fallback?: string): string => {\n\tconst output = String(text)\n\t\t.toLowerCase()\n\t\t// .normalize('NFD') // split an accented letter in the base letter and the acent\n\t\t// .replace(/[\\u0300-\\u036f]/g, '') // remove all previously split accents\n\t\t.replace(/[\\s/_.]+/g, '-') // replace spaces and _./ with '-'\n\t\t.replace(/[^\\w-]+/g, '') // remove all non-word chars\n\t\t.replace(/--+/g, '-') // replace repeating '-' with single '-'\n\t\t.replace(/^-+|-+$/, ''); // trim '-' from edges\n\treturn output || fallback || '';\n};\n\nexport default classify;\n","const getCurrentUrl = ({ hash }: { hash?: boolean } = {}): string => {\n\treturn location.pathname + location.search + (hash ? location.hash : '');\n};\n\nexport default getCurrentUrl;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst createHistoryRecord = (url: string, customData: Record<string, unknown> = {}): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.pushState(data, '', url);\n};\n\nexport default createHistoryRecord;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst updateHistoryRecord = (\n\turl: string | null = null,\n\tcustomData: Record<string, unknown> = {}\n): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\t...history.state,\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.replaceState(data, '', url);\n};\n\nexport default updateHistoryRecord;\n","import delegate, { EventType } from 'delegate-it';\nimport { ParseSelector } from 'typed-query-selector/parser';\n\nexport type Unsubscribe = {\n\tdestroy: () => void;\n};\nconst delegateEvent = <Selector extends string, TEvent extends EventType>(\n\tselector: Selector,\n\ttype: TEvent,\n\tcallback: delegate.EventHandler<GlobalEventHandlersEventMap[TEvent]>,\n\t{ base = document, ...eventOptions } = {}\n): Unsubscribe => {\n\tconst delegation = delegate<string, ParseSelector<Selector, HTMLElement>, TEvent>(\n\t\tbase,\n\t\tselector,\n\t\ttype,\n\t\tcallback,\n\t\teventOptions\n\t);\n\treturn { destroy: () => delegation.destroy() };\n};\n\nexport default delegateEvent;\n","export const query = (selector: string, context: Document | Element = document) => {\n\treturn context.querySelector<HTMLElement>(selector);\n};\n\nexport const queryAll = (\n\tselector: string,\n\tcontext: Document | Element = document\n): HTMLElement[] => {\n\treturn Array.from(context.querySelectorAll(selector));\n};\n\nexport const nextTick = (callback: () => void) => {\n\trequestAnimationFrame(() => {\n\t\trequestAnimationFrame(() => {\n\t\t\tcallback();\n\t\t});\n\t});\n};\n\nexport const escapeCssIdentifier = (ident: string) => {\n\t// @ts-ignore this is for support check, so it's correct that TS complains\n\tif (window.CSS && window.CSS.escape) {\n\t\treturn CSS.escape(ident);\n\t} else {\n\t\treturn ident;\n\t}\n};\n\n// Fix for Chrome below v61 formatting CSS floats with comma in some locales\nexport const toMs = (s: string) => {\n\treturn Number(s.slice(0, -1).replace(',', '.')) * 1000;\n};\n","import { query, queryAll } from '../utils.js';\n\nexport type PageHtmlData = {\n\ttitle: string;\n\toriginalContent: string;\n\tblocks: string[];\n\tpageClass?: string;\n};\n\nconst getDataFromHtml = (html: string, containers: string[]): PageHtmlData => {\n\tlet fakeDom = document.createElement('html');\n\tfakeDom.innerHTML = html;\n\tlet blocks: string[] = [];\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, fakeDom) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t\treturn null;\n\t\t} else {\n\t\t\tif (queryAll(selector).length !== queryAll(selector, fakeDom).length) {\n\t\t\t\tconsole.warn(`[swup] Mismatched number of containers found on new page.`);\n\t\t\t}\n\t\t\tqueryAll(selector).forEach((item, index) => {\n\t\t\t\tqueryAll(selector, fakeDom)[index].setAttribute('data-swup', String(blocks.length));\n\t\t\t\tblocks.push(queryAll(selector, fakeDom)[index].outerHTML);\n\t\t\t});\n\t\t}\n\t});\n\n\tconst title = query('title', fakeDom)?.innerText || '';\n\tconst pageClass = query('body', fakeDom)?.className;\n\n\t// to prevent memory leaks\n\tfakeDom.innerHTML = '';\n\t// @ts-ignore don't want to type it as possible null, since it's created at the top of the function always\n\tfakeDom = null;\n\n\treturn { title, pageClass, blocks, originalContent: html };\n};\n\nexport default getDataFromHtml;\n","import { TransitionOptions } from '../modules/loadPage.js';\nimport { Options } from '../Swup.js';\n\nconst fetch = (\n\toptions: TransitionOptions & { headers: Options['requestHeaders'] },\n\tcallback: (request: XMLHttpRequest) => void\n): XMLHttpRequest => {\n\tconst defaults = {\n\t\turl: window.location.pathname + window.location.search,\n\t\tmethod: 'GET',\n\t\tdata: null,\n\t\theaders: {}\n\t};\n\n\tconst { url, method, headers, data } = { ...defaults, ...options };\n\n\tconst request = new XMLHttpRequest();\n\n\trequest.onreadystatechange = function () {\n\t\tif (request.readyState === 4) {\n\t\t\t// if (request.status === 500) {} else {}\n\t\t\tcallback(request);\n\t\t}\n\t};\n\n\trequest.open(method, url, true);\n\tObject.entries(headers).forEach(([key, header]) => {\n\t\trequest.setRequestHeader(key, header);\n\t});\n\trequest.send(data);\n\n\treturn request;\n};\n\nexport default fetch;\n","/**\n * A helper for creating a Location from either an element\n * or a URL object/string\n *\n * Note: this could be implemented as a class inheriting from URL\n * Except: Babel will add tons of boilerplate for ES6 classes + getters\n * So for now it's implemented as an augmented URL object with custom getter\n *\n * class Location extends URL {\n * get url() {\n *\t return this.pathname + this.search;\n * }\n * }\n *\n */\n\nexport default class Location extends URL {\n\tconstructor(url: string, base: string = document.baseURI) {\n\t\tsuper(url.toString(), base);\n\t}\n\n\tget url() {\n\t\treturn this.pathname + this.search;\n\t}\n\n\t/**\n\t * Instantiate a Location from an element's href attribute\n\t * @param {Element} el\n\t * @return new Location instance\n\t */\n\tstatic fromElement(el: HTMLAnchorElement): Location {\n\t\tconst href = el.getAttribute('href') || el.getAttribute('xlink:href');\n\t\treturn new Location(href!);\n\t}\n\n\t/**\n\t * Instantiate a Location from a URL object or string\n\t * @param {URL|string} url\n\t * @return new Location instance\n\t */\n\tstatic fromUrl(url: string): Location {\n\t\treturn new Location(url);\n\t}\n}\n","import { query, queryAll } from '../utils.js';\n\nconst markSwupElements = (element: Element, containers: string[]): void => {\n\tlet blocks = 0;\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, element) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t} else {\n\t\t\tqueryAll(selector).forEach((item: Element, index: number) => {\n\t\t\t\tqueryAll(selector, element)[index].setAttribute('data-swup', String(blocks));\n\t\t\t\tblocks++;\n\t\t\t});\n\t\t}\n\t});\n};\n\nexport default markSwupElements;\n","const isSwupClass = (className: string): boolean =>\n\t/^to-/.test(className) || ['is-changing', 'is-rendering', 'is-popstate'].includes(className);\n\nconst cleanupAnimationClasses = (): void => {\n\tconst htmlClasses = document.documentElement.className.split(' ');\n\tconst removeClasses = htmlClasses.filter(isSwupClass);\n\tdocument.documentElement.classList.remove(...removeClasses);\n};\n\nexport default cleanupAnimationClasses;\n","type Comparator = '>' | '>=' | '<' | '<=';\n\n// Fill versions to exactly 3 decimals\nconst normalizeVersion = (version: string): string => {\n\treturn String(version).split('.').concat(['0', '0']).slice(0, 3).join('.');\n};\n\n// Numerically compare version strings after normalizing them\nconst compareVersion = (a: string, b: string): number => {\n\ta = normalizeVersion(a);\n\tb = normalizeVersion(b);\n\treturn a.localeCompare(b, undefined, { numeric: true });\n};\n\n// Apply a comparator (equals, greater-than, etc) by its symbol to a sort comparison\nconst applyComparator = (comparisonResult: number, comparator: Comparator) => {\n\tconst comparators = {\n\t\t'': (r: number) => r === 0,\n\t\t'>': (r: number) => r > 0,\n\t\t'>=': (r: number) => r >= 0,\n\t\t'<': (r: number) => r < 0,\n\t\t'<=': (r: number) => r <= 0\n\t};\n\tconst comparatorFn = comparators[comparator] || comparators[''];\n\treturn comparatorFn(comparisonResult);\n};\n\n/**\n * Check if a version satisfies all given version requirements\n *\n * versionSatisfies('2.1.0', ['>=2', '<4']) // true\n * versionSatisfies('2.1.0', ['5']) // false\n *\n * @param {string} installed Installed version\n * @param {Array.<string>} requirements Array of requirements that must be satisfied\n * @returns boolean\n */\nexport const versionSatisfies = (installed: string, requirements: string[]) => {\n\treturn requirements.every((required) => {\n\t\tconst [, comparator, version] = required.match(/^([\\D]+)?(.*)$/) || [];\n\t\tconst comparisonResult = compareVersion(installed, version);\n\t\treturn applyComparator(comparisonResult, (comparator as Comparator) || '>=');\n\t});\n};\n\nexport default versionSatisfies;\n"],"names":["classify","text","fallback","String","toLowerCase","replace","getCurrentUrl","hash","pathname","location","search","createHistoryRecord","url","customData","data","random","Math","source","history","pushState","updateHistoryRecord","_extends","state","replaceState","delegateEvent","selector","type","callback","_ref","base","document","eventOptions","_objectWithoutPropertiesLoose","_excluded","delegate","destroy","delegation","query","context","querySelector","queryAll","Array","from","querySelectorAll","getDataFromHtml","html","containers","fakeDom","createElement","innerHTML","blocks","forEach","console","warn","length","item","index","setAttribute","push","outerHTML","title","_query","innerText","_query2","className","pageClass","originalContent","fetch","options","defaults","window","method","headers","request","XMLHttpRequest","onreadystatechange","readyState","open","Object","entries","key","header","setRequestHeader","send","Location","URL","constructor","baseURI","super","toString","this","static","el","href","getAttribute","markSwupElements","element","isSwupClass","test","includes","cleanupAnimationClasses","removeClasses","documentElement","split","filter","classList","remove","normalizeVersion","version","concat","slice","join","versionSatisfies","installed","requirements","every","required","comparator","match","a","b","comparisonResult","comparators","r","applyComparator","localeCompare","undefined","numeric"],"mappings":"2BAAMA,MAAAA,EAAW,CAACC,EAAcC,IAChBC,OAAOF,GACpBG,cAGAC,QAAQ,YAAa,KACrBA,QAAQ,WAAY,IACpBA,QAAQ,OAAQ,KAChBA,QAAQ,UAAW,KACJH,GAAY,uOCTxBI,MAAaA,EAAG,EAAGC,QAA6B,CAAE,aACvCC,SAAWC,SAASC,QAAUH,EAAOE,SAASF,KAAO,ICChEI,EAAsB,CAACC,EAAaC,EAAsC,CAAA,KAE/E,MAAMC,EACLF,EAAAA,CAAAA,IAFDA,EAAMA,GAAON,EAAc,CAAEC,MAAM,IAGlCQ,OAAQC,KAAKD,SACbE,OAAQ,QACLJ,GAEJK,QAAQC,UAAUL,EAAM,GAAIF,EAC7B,ECTyBQ,EAAG,CAC3BR,EAAqB,KACrBC,EAAsC,CAAA,KAEtCD,EAAMA,GAAON,EAAc,CAAEC,MAAM,IACnC,MAAUO,EAAAO,EAAA,CAAA,EACNH,QAAQI,MAAK,CAChBV,MACAG,OAAQC,KAAKD,SACbE,OAAQ,QACLJ,GAEJK,QAAQK,aAAaT,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WQ,EAASE,MAAM,mBAAqB,GA/B/C,IAACC,EAAWC,EAiCjC,MA1BsB,EAACC,EAA0BJ,KAClD,MAAMK,EAAc,CACnB,GAAKC,GAAoB,IAANA,EACnB,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,EAC1B,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,GAG3B,OADqBD,EAAYL,IAAeK,EAAY,KACxCD,EAAgB,EAiB5BG,EAjC0BJ,EAgCkBZ,EA/BpDW,EAAIZ,EADmBY,EAgCkBN,GA9BzCO,EAAIb,EAAiBa,GACbD,EAACM,cAAcL,OAAGM,EAAW,CAAEC,SAAS,KA8BLV,GAA6B,KAAI"}
@@ -1,2 +0,0 @@
1
- import t from"delegate-it";const e=(t,e)=>String(t).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/,"")||e||"",n=function(t){let{hash:e}=void 0===t?{}:t;return location.pathname+location.search+(e?location.hash:"")},o=function(t,e){void 0===e&&(e={});const o={url:t=t||n({hash:!0}),random:Math.random(),source:"swup",...e};history.pushState(o,"",t)},r=function(t,e){void 0===t&&(t=null),void 0===e&&(e={}),t=t||n({hash:!0});const o={...history.state,url:t,random:Math.random(),source:"swup",...e};history.replaceState(o,"",t)},a=function(e,n,o,r){let{base:a=document,...s}=void 0===r?{}:r;const c=t(a,e,n,o,s);return{destroy:()=>c.destroy()}},s=function(t,e){return void 0===e&&(e=document),e.querySelector(t)},c=function(t,e){return void 0===e&&(e=document),Array.from(e.querySelectorAll(t))},l=(t,e)=>{var n,o;let r=document.createElement("html");r.innerHTML=t;let a=[];e.forEach(t=>{if(null==s(t,r))return console.warn("[swup] Container "+t+" not found on page."),null;c(t).length!==c(t,r).length&&console.warn("[swup] Mismatched number of containers found on new page."),c(t).forEach((e,n)=>{c(t,r)[n].setAttribute("data-swup",String(a.length)),a.push(c(t,r)[n].outerHTML)})});const l=(null==(n=s("title",r))?void 0:n.innerText)||"",i=null==(o=s("body",r))?void 0:o.className;return r.innerHTML="",r=null,{title:l,pageClass:i,blocks:a,originalContent:t}},i=(t,e)=>{const n={url:window.location.pathname+window.location.search,method:"GET",data:null,headers:{}},{url:o,method:r,headers:a,data:s}={...n,...t},c=new XMLHttpRequest;return c.onreadystatechange=function(){4===c.readyState&&e(c)},c.open(r,o,!0),Object.entries(a).forEach(t=>{let[e,n]=t;c.setRequestHeader(e,n)}),c.send(s),c};class u extends URL{constructor(t,e){void 0===e&&(e=document.baseURI),super(t.toString(),e)}get url(){return this.pathname+this.search}static fromElement(t){const e=t.getAttribute("href")||t.getAttribute("xlink:href");return new u(e)}static fromUrl(t){return new u(t)}}const d=(t,e)=>{let n=0;e.forEach(e=>{null==s(e,t)?console.warn("[swup] Container "+e+" not found on page."):c(e).forEach((o,r)=>{c(e,t)[r].setAttribute("data-swup",String(n)),n++})})},h=t=>/^to-/.test(t)||["is-changing","is-rendering","is-popstate"].includes(t),m=()=>{const t=document.documentElement.className.split(" ").filter(h);document.documentElement.classList.remove(...t)},p=t=>String(t).split(".").concat(["0","0"]).slice(0,3).join("."),f=(t,e)=>e.every(e=>{const[,n,o]=e.match(/^([\D]+)?(.*)$/)||[];var r,a;return((t,e)=>{const n={"":t=>0===t,">":t=>t>0,">=":t=>t>=0,"<":t=>t<0,"<=":t=>t<=0};return(n[e]||n[""])(t)})((a=o,r=p(r=t),a=p(a),r.localeCompare(a,void 0,{numeric:!0})),n||">=")});export{u as Location,e as classify,m as cleanupAnimationClasses,o as createHistoryRecord,a as delegateEvent,i as fetch,n as getCurrentUrl,l as getDataFromHtml,d as markSwupElements,r as updateHistoryRecord,f as versionSatisfies};
2
- //# sourceMappingURL=helpers.module.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.module.js","sources":["../src/helpers/classify.ts","../src/helpers/getCurrentUrl.ts","../src/helpers/createHistoryRecord.ts","../src/helpers/updateHistoryRecord.ts","../src/helpers/delegateEvent.ts","../src/utils/index.ts","../src/helpers/getDataFromHtml.ts","../src/helpers/fetch.ts","../src/helpers/Location.ts","../src/helpers/markSwupElements.ts","../src/helpers/cleanupAnimationClasses.ts","../src/helpers/versionSatisfies.ts"],"sourcesContent":["const classify = (text: string, fallback?: string): string => {\n\tconst output = String(text)\n\t\t.toLowerCase()\n\t\t// .normalize('NFD') // split an accented letter in the base letter and the acent\n\t\t// .replace(/[\\u0300-\\u036f]/g, '') // remove all previously split accents\n\t\t.replace(/[\\s/_.]+/g, '-') // replace spaces and _./ with '-'\n\t\t.replace(/[^\\w-]+/g, '') // remove all non-word chars\n\t\t.replace(/--+/g, '-') // replace repeating '-' with single '-'\n\t\t.replace(/^-+|-+$/, ''); // trim '-' from edges\n\treturn output || fallback || '';\n};\n\nexport default classify;\n","const getCurrentUrl = ({ hash }: { hash?: boolean } = {}): string => {\n\treturn location.pathname + location.search + (hash ? location.hash : '');\n};\n\nexport default getCurrentUrl;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst createHistoryRecord = (url: string, customData: Record<string, unknown> = {}): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.pushState(data, '', url);\n};\n\nexport default createHistoryRecord;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst updateHistoryRecord = (\n\turl: string | null = null,\n\tcustomData: Record<string, unknown> = {}\n): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\t...history.state,\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.replaceState(data, '', url);\n};\n\nexport default updateHistoryRecord;\n","import delegate, { EventType } from 'delegate-it';\nimport { ParseSelector } from 'typed-query-selector/parser';\n\nexport type Unsubscribe = {\n\tdestroy: () => void;\n};\nconst delegateEvent = <Selector extends string, TEvent extends EventType>(\n\tselector: Selector,\n\ttype: TEvent,\n\tcallback: delegate.EventHandler<GlobalEventHandlersEventMap[TEvent]>,\n\t{ base = document, ...eventOptions } = {}\n): Unsubscribe => {\n\tconst delegation = delegate<string, ParseSelector<Selector, HTMLElement>, TEvent>(\n\t\tbase,\n\t\tselector,\n\t\ttype,\n\t\tcallback,\n\t\teventOptions\n\t);\n\treturn { destroy: () => delegation.destroy() };\n};\n\nexport default delegateEvent;\n","export const query = (selector: string, context: Document | Element = document) => {\n\treturn context.querySelector<HTMLElement>(selector);\n};\n\nexport const queryAll = (\n\tselector: string,\n\tcontext: Document | Element = document\n): HTMLElement[] => {\n\treturn Array.from(context.querySelectorAll(selector));\n};\n\nexport const nextTick = (callback: () => void) => {\n\trequestAnimationFrame(() => {\n\t\trequestAnimationFrame(() => {\n\t\t\tcallback();\n\t\t});\n\t});\n};\n\nexport const escapeCssIdentifier = (ident: string) => {\n\t// @ts-ignore this is for support check, so it's correct that TS complains\n\tif (window.CSS && window.CSS.escape) {\n\t\treturn CSS.escape(ident);\n\t} else {\n\t\treturn ident;\n\t}\n};\n\n// Fix for Chrome below v61 formatting CSS floats with comma in some locales\nexport const toMs = (s: string) => {\n\treturn Number(s.slice(0, -1).replace(',', '.')) * 1000;\n};\n","import { query, queryAll } from '../utils.js';\n\nexport type PageHtmlData = {\n\ttitle: string;\n\toriginalContent: string;\n\tblocks: string[];\n\tpageClass?: string;\n};\n\nconst getDataFromHtml = (html: string, containers: string[]): PageHtmlData => {\n\tlet fakeDom = document.createElement('html');\n\tfakeDom.innerHTML = html;\n\tlet blocks: string[] = [];\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, fakeDom) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t\treturn null;\n\t\t} else {\n\t\t\tif (queryAll(selector).length !== queryAll(selector, fakeDom).length) {\n\t\t\t\tconsole.warn(`[swup] Mismatched number of containers found on new page.`);\n\t\t\t}\n\t\t\tqueryAll(selector).forEach((item, index) => {\n\t\t\t\tqueryAll(selector, fakeDom)[index].setAttribute('data-swup', String(blocks.length));\n\t\t\t\tblocks.push(queryAll(selector, fakeDom)[index].outerHTML);\n\t\t\t});\n\t\t}\n\t});\n\n\tconst title = query('title', fakeDom)?.innerText || '';\n\tconst pageClass = query('body', fakeDom)?.className;\n\n\t// to prevent memory leaks\n\tfakeDom.innerHTML = '';\n\t// @ts-ignore don't want to type it as possible null, since it's created at the top of the function always\n\tfakeDom = null;\n\n\treturn { title, pageClass, blocks, originalContent: html };\n};\n\nexport default getDataFromHtml;\n","import { TransitionOptions } from '../modules/loadPage.js';\nimport { Options } from '../Swup.js';\n\nconst fetch = (\n\toptions: TransitionOptions & { headers: Options['requestHeaders'] },\n\tcallback: (request: XMLHttpRequest) => void\n): XMLHttpRequest => {\n\tconst defaults = {\n\t\turl: window.location.pathname + window.location.search,\n\t\tmethod: 'GET',\n\t\tdata: null,\n\t\theaders: {}\n\t};\n\n\tconst { url, method, headers, data } = { ...defaults, ...options };\n\n\tconst request = new XMLHttpRequest();\n\n\trequest.onreadystatechange = function () {\n\t\tif (request.readyState === 4) {\n\t\t\t// if (request.status === 500) {} else {}\n\t\t\tcallback(request);\n\t\t}\n\t};\n\n\trequest.open(method, url, true);\n\tObject.entries(headers).forEach(([key, header]) => {\n\t\trequest.setRequestHeader(key, header);\n\t});\n\trequest.send(data);\n\n\treturn request;\n};\n\nexport default fetch;\n","/**\n * A helper for creating a Location from either an element\n * or a URL object/string\n *\n * Note: this could be implemented as a class inheriting from URL\n * Except: Babel will add tons of boilerplate for ES6 classes + getters\n * So for now it's implemented as an augmented URL object with custom getter\n *\n * class Location extends URL {\n * get url() {\n *\t return this.pathname + this.search;\n * }\n * }\n *\n */\n\nexport default class Location extends URL {\n\tconstructor(url: string, base: string = document.baseURI) {\n\t\tsuper(url.toString(), base);\n\t}\n\n\tget url() {\n\t\treturn this.pathname + this.search;\n\t}\n\n\t/**\n\t * Instantiate a Location from an element's href attribute\n\t * @param {Element} el\n\t * @return new Location instance\n\t */\n\tstatic fromElement(el: HTMLAnchorElement): Location {\n\t\tconst href = el.getAttribute('href') || el.getAttribute('xlink:href');\n\t\treturn new Location(href!);\n\t}\n\n\t/**\n\t * Instantiate a Location from a URL object or string\n\t * @param {URL|string} url\n\t * @return new Location instance\n\t */\n\tstatic fromUrl(url: string): Location {\n\t\treturn new Location(url);\n\t}\n}\n","import { query, queryAll } from '../utils.js';\n\nconst markSwupElements = (element: Element, containers: string[]): void => {\n\tlet blocks = 0;\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, element) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t} else {\n\t\t\tqueryAll(selector).forEach((item: Element, index: number) => {\n\t\t\t\tqueryAll(selector, element)[index].setAttribute('data-swup', String(blocks));\n\t\t\t\tblocks++;\n\t\t\t});\n\t\t}\n\t});\n};\n\nexport default markSwupElements;\n","const isSwupClass = (className: string): boolean =>\n\t/^to-/.test(className) || ['is-changing', 'is-rendering', 'is-popstate'].includes(className);\n\nconst cleanupAnimationClasses = (): void => {\n\tconst htmlClasses = document.documentElement.className.split(' ');\n\tconst removeClasses = htmlClasses.filter(isSwupClass);\n\tdocument.documentElement.classList.remove(...removeClasses);\n};\n\nexport default cleanupAnimationClasses;\n","type Comparator = '>' | '>=' | '<' | '<=';\n\n// Fill versions to exactly 3 decimals\nconst normalizeVersion = (version: string): string => {\n\treturn String(version).split('.').concat(['0', '0']).slice(0, 3).join('.');\n};\n\n// Numerically compare version strings after normalizing them\nconst compareVersion = (a: string, b: string): number => {\n\ta = normalizeVersion(a);\n\tb = normalizeVersion(b);\n\treturn a.localeCompare(b, undefined, { numeric: true });\n};\n\n// Apply a comparator (equals, greater-than, etc) by its symbol to a sort comparison\nconst applyComparator = (comparisonResult: number, comparator: Comparator) => {\n\tconst comparators = {\n\t\t'': (r: number) => r === 0,\n\t\t'>': (r: number) => r > 0,\n\t\t'>=': (r: number) => r >= 0,\n\t\t'<': (r: number) => r < 0,\n\t\t'<=': (r: number) => r <= 0\n\t};\n\tconst comparatorFn = comparators[comparator] || comparators[''];\n\treturn comparatorFn(comparisonResult);\n};\n\n/**\n * Check if a version satisfies all given version requirements\n *\n * versionSatisfies('2.1.0', ['>=2', '<4']) // true\n * versionSatisfies('2.1.0', ['5']) // false\n *\n * @param {string} installed Installed version\n * @param {Array.<string>} requirements Array of requirements that must be satisfied\n * @returns boolean\n */\nexport const versionSatisfies = (installed: string, requirements: string[]) => {\n\treturn requirements.every((required) => {\n\t\tconst [, comparator, version] = required.match(/^([\\D]+)?(.*)$/) || [];\n\t\tconst comparisonResult = compareVersion(installed, version);\n\t\treturn applyComparator(comparisonResult, (comparator as Comparator) || '>=');\n\t});\n};\n\nexport default versionSatisfies;\n"],"names":["classify","text","fallback","String","toLowerCase","replace","getCurrentUrl","_temp","hash","pathname","location","search","createHistoryRecord","url","customData","data","random","Math","source","history","pushState","updateHistoryRecord","state","replaceState","delegateEvent","selector","type","callback","base","document","eventOptions","delegate","destroy","delegation","query","context","querySelector","queryAll","Array","from","querySelectorAll","html","containers","_query","_query2","createElement","fakeDom","innerHTML","blocks","forEach","console","warn","length","item","index","setAttribute","push","outerHTML","title","innerText","className","pageClass","originalContent","fetch","options","defaults","window","method","headers","request","XMLHttpRequest","onreadystatechange","readyState","open","Object","entries","_ref","key","header","setRequestHeader","send","Location","constructor","baseURI","super","toString","this","static","el","getAttribute","href","markSwupElements","element","isSwupClass","test","includes","cleanupAnimationClasses","removeClasses","documentElement","split","filter","classList","remove","normalizeVersion","version","concat","slice","join","versionSatisfies","installed","requirements","every","required","comparator","match","a","b","comparisonResult","comparators","r","applyComparator","localeCompare","undefined","numeric"],"mappings":"2BAAMA,MAAAA,EAAW,CAACC,EAAcC,IAChBC,OAAOF,GACpBG,cAGAC,QAAQ,YAAa,KACrBA,QAAQ,WAAY,IACpBA,QAAQ,OAAQ,KAChBA,QAAQ,UAAW,KACJH,GAAY,GCTXI,EAAG,SAA8CC,GAAA,IAA7CC,KAAEA,QAA6B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,EAAkBlD,KAC3C,IAAUM,EAAG,EAEbN,EAAWO,QAASxB,IACa,MAA5BS,EAAMT,EAAUmE,GACnB1C,QAAQC,KAAI,oBAAqB1B,EACjC,uBACAY,EAASZ,GAAUwB,QAAQ,CAACI,EAAeC,KAC1CjB,EAASZ,EAAUmE,GAAStC,GAAOC,aAAa,YAAapD,OAAO6C,IACpEA,GAAM,EAEP,EAEH,ECfiB6C,EAAIjC,GACpB,OAAOkC,KAAKlC,IAAc,CAAC,cAAe,eAAgB,eAAemC,SAASnC,GAE7EoC,EAA0B,KAC/B,MACmBC,EADCpE,SAASqE,gBAAgBtC,UAAUuC,MAAM,KAC3BC,OAAOP,GACzChE,SAASqE,gBAAgBG,UAAUC,UAAUL,EAC9C,ECJMM,EAAoBC,GAClBrG,OAAOqG,GAASL,MAAM,KAAKM,OAAO,CAAC,IAAK,MAAMC,MAAM,EAAG,GAAGC,KAAK,KAiC1CC,EAAG,CAACC,EAAmBC,IAC5CA,EAAaC,MAAOC,IAC1B,OAASC,EAAYT,GAAWQ,EAASE,MAAM,mBAAqB,GA/B/C,IAACC,EAAWC,EAiCjC,MA1BsB,EAACC,EAA0BJ,KAClD,MAAMK,EAAc,CACnB,GAAKC,GAAoB,IAANA,EACnB,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,EAC1B,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,GAG3B,OADqBD,EAAYL,IAAeK,EAAY,KACxCD,EAAgB,EAiB5BG,EAjC0BJ,EAgCkBZ,EA/BpDW,EAAIZ,EADmBY,EAgCkBN,GA9BzCO,EAAIb,EAAiBa,GACbD,EAACM,cAAcL,OAAGM,EAAW,CAAEC,SAAS,KA8BLV,GAA6B,KAAI"}
@@ -1,11 +0,0 @@
1
- export { default as classify } from './classify.js';
2
- export { default as createHistoryRecord } from './createHistoryRecord.js';
3
- export { default as updateHistoryRecord } from './updateHistoryRecord.js';
4
- export { default as delegateEvent } from './delegateEvent.js';
5
- export { default as getDataFromHtml } from './getDataFromHtml.js';
6
- export { default as fetch } from './fetch.js';
7
- export { default as getCurrentUrl } from './getCurrentUrl.js';
8
- export { default as Location } from './Location.js';
9
- export { default as markSwupElements } from './markSwupElements.js';
10
- export { default as cleanupAnimationClasses } from './cleanupAnimationClasses.js';
11
- export { default as versionSatisfies } from './versionSatisfies.js';
@@ -1,11 +0,0 @@
1
- /**
2
- * Check if a version satisfies all given version requirements
3
- *
4
- * versionSatisfies('2.1.0', ['>=2', '<4']) // true
5
- * versionSatisfies('2.1.0', ['5']) // false
6
- *
7
- * @param {string} installed Installed version
8
- * @param {Array.<string>} requirements Array of requirements that must be satisfied
9
- * @returns boolean
10
- */
11
- export declare const versionSatisfies: (installed: string, requirements: string[]) => boolean;
@@ -1,3 +0,0 @@
1
- import Swup from '../Swup.js';
2
- import { EventType, Handler } from './on.js';
3
- export declare const off: (this: Swup, event?: EventType, handler?: Handler) => void;
@@ -1,3 +0,0 @@
1
- import { EventType } from './on.js';
2
- import Swup from '../Swup.js';
3
- export declare const triggerEvent: (this: Swup, eventName: EventType, originalEvent?: PopStateEvent | MouseEvent) => void;
package/dist/utils.cjs DELETED
@@ -1,2 +0,0 @@
1
- exports.escapeCssIdentifier=e=>window.CSS&&window.CSS.escape?CSS.escape(e):e,exports.nextTick=e=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})},exports.query=function(e,r){return void 0===r&&(r=document),r.querySelector(e)},exports.queryAll=function(e,r){return void 0===r&&(r=document),Array.from(r.querySelectorAll(e))},exports.toMs=e=>1e3*Number(e.slice(0,-1).replace(",","."));
2
- //# sourceMappingURL=utils.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.cjs","sources":["../src/utils/index.ts"],"sourcesContent":["export const query = (selector: string, context: Document | Element = document) => {\n\treturn context.querySelector<HTMLElement>(selector);\n};\n\nexport const queryAll = (\n\tselector: string,\n\tcontext: Document | Element = document\n): HTMLElement[] => {\n\treturn Array.from(context.querySelectorAll(selector));\n};\n\nexport const nextTick = (callback: () => void) => {\n\trequestAnimationFrame(() => {\n\t\trequestAnimationFrame(() => {\n\t\t\tcallback();\n\t\t});\n\t});\n};\n\nexport const escapeCssIdentifier = (ident: string) => {\n\t// @ts-ignore this is for support check, so it's correct that TS complains\n\tif (window.CSS && window.CSS.escape) {\n\t\treturn CSS.escape(ident);\n\t} else {\n\t\treturn ident;\n\t}\n};\n\n// Fix for Chrome below v61 formatting CSS floats with comma in some locales\nexport const toMs = (s: string) => {\n\treturn Number(s.slice(0, -1).replace(',', '.')) * 1000;\n};\n"],"names":["ident","window","CSS","escape","callback","requestAnimationFrame","selector","context","document","querySelector","Array","from","querySelectorAll","s","Number","slice","replace"],"mappings":"4BAmBoCA,GAE/BC,OAAOC,KAAOD,OAAOC,IAAIC,OAClBD,IAACC,OAAOH,GAEXA,mBAbgBI,IACxBC,sBAAsB,KACrBA,sBAAsB,KACrBD,GAAQ,EAEV,EACD,gBAjBqB,SAACE,EAAkBC,GACvC,YADuC,IAAAA,IAAAA,EAA8BC,UACvDD,EAACE,cAA2BH,EAC3C,mBAEwB,SACvBA,EACAC,GAEA,YAFA,IAAAA,IAAAA,EAA8BC,UAElBE,MAACC,KAAKJ,EAAQK,iBAAiBN,GAC5C,eAoBqBO,GAC8B,IAArCC,OAACD,EAAEE,MAAM,GAAI,GAAGC,QAAQ,IAAK"}
@@ -1,2 +0,0 @@
1
- const e=(e,r=document)=>r.querySelector(e),r=(e,r=document)=>Array.from(r.querySelectorAll(e)),o=e=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})},t=e=>window.CSS&&window.CSS.escape?CSS.escape(e):e,c=e=>1e3*Number(e.slice(0,-1).replace(",","."));export{t as escapeCssIdentifier,o as nextTick,e as query,r as queryAll,c as toMs};
2
- //# sourceMappingURL=utils.modern.js.map