{"version":3,"file":"index.cjs","sources":["../src/mergeHeadContents.ts","../src/updateAttributes.ts","../src/waitForAssets.ts","../src/index.ts"],"sourcesContent":["type ElementCollection = { el: Element; index?: number }[];\n\nexport default function mergeHeadContents(\n\tcurrentHead: HTMLHeadElement,\n\tnewHead: HTMLHeadElement,\n\t{ shouldPersist = () => false }: { shouldPersist?: (el: Element) => boolean } = {}\n) {\n\tconst currentTags = Array.from(currentHead.children);\n\tconst newChildren = Array.from(newHead.children);\n\n\tconst addTags = getTagsToAdd(currentTags, newChildren);\n\tconst removeTags = getTagsToRemove(currentTags, newChildren);\n\n\t// Remove tags in reverse to keep indexes, keep persistant elements\n\tremoveTags\n\t\t.reverse()\n\t\t.filter(({ el }) => shouldManageTag(el))\n\t\t.filter(({ el }) => !shouldPersist(el))\n\t\t.forEach(({ el }) => currentHead.removeChild(el));\n\n\t// Insert tag *after* previous version of itself to preserve JS variable scope and CSS cascade\n\tconst newAddTags = addTags\n\t\t.filter(({ el }) => shouldManageTag(el))\n\t\t.map((tag) => {\n\t\t\tlet newEl = tag.el.cloneNode(true) as Element;\n\t\t\tcurrentHead.insertBefore(newEl, currentHead.children[(tag.index || 0) + 1] || null);\n\n\t\t\treturn { ...tag, el: newEl };\n\t\t});\n\n\treturn {\n\t\tremoved: removeTags.map(({ el }) => el),\n\t\tadded: newAddTags.map(({ el }) => el)\n\t};\n}\n\nfunction getTagsToRemove(currentEls: Element[], newEls: Element[]): ElementCollection {\n\treturn currentEls.reduce((tags, el) => {\n\t\tconst isAmongNew = newEls.some((newEl) => compareTags(el, newEl));\n\t\tif (!isAmongNew) {\n\t\t\ttags.push({ el });\n\t\t}\n\t\treturn tags;\n\t}, [] as ElementCollection);\n}\n\nfunction getTagsToAdd(currentEls: Element[], newEls: Element[]): ElementCollection {\n\treturn newEls.reduce((tags, el, index) => {\n\t\tconst isAmongCurrent = currentEls.some((currentEl) => compareTags(el, currentEl));\n\t\tif (!isAmongCurrent) {\n\t\t\ttags.push({ el, index });\n\t\t}\n\t\treturn tags;\n\t}, [] as ElementCollection);\n}\n\nfunction shouldManageTag(el: Element) {\n\t// Let swup manage the title tag\n\tif (el.localName === 'title') {\n\t\treturn false;\n\t}\n\t// Leave swup theme styles untouched\n\tif (el.matches('[data-swup-theme]')) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction compareTags(oldTag: Element, newTag: Element) {\n\treturn oldTag.outerHTML === newTag.outerHTML;\n}\n","export default function updateAttributes(\n\ttarget: Element,\n\tsource: Element,\n\tfilters: (string | RegExp)[] = []\n): void {\n\tconst keep = new Set<string>();\n\n\tfor (const { name, value } of getAttributes(source, filters)) {\n\t\ttarget.setAttribute(name, value);\n\t\tkeep.add(name);\n\t}\n\n\tfor (const { name } of getAttributes(target, filters)) {\n\t\tif (!keep.has(name)) {\n\t\t\ttarget.removeAttribute(name);\n\t\t}\n\t}\n}\n\nfunction getAttributes(el: Element, filters: (string | RegExp)[] = []): Attr[] {\n\tconst all = Array.from(el.attributes);\n\tif (!filters.length) return all;\n\n\treturn all.filter(({ name }) =>\n\t\tfilters.some((pattern) =>\n\t\t\tpattern instanceof RegExp ? pattern.test(name) : name === pattern\n\t\t)\n\t);\n}\n","export default function waitForAssets(\n\telements: Element[],\n\ttimeoutMs: number = 0\n): Promise<HTMLLinkElement>[] {\n\treturn elements.filter(isStylesheet).map((el) => waitForStylesheet(el, timeoutMs));\n}\n\nfunction isStylesheet(el: Element): el is HTMLLinkElement {\n\treturn el.matches('link[rel=stylesheet][href]');\n}\n\nexport function waitForStylesheet(\n\telement: HTMLLinkElement,\n\ttimeoutMs: number = 0\n): Promise<HTMLLinkElement> {\n\tlet timeoutId: ReturnType<typeof setTimeout>;\n\n\tconst whenLoaded = (cb: () => void) => {\n\t\tif (element.sheet) {\n\t\t\tcb();\n\t\t} else {\n\t\t\ttimeoutId = setTimeout(() => whenLoaded(cb), 10);\n\t\t}\n\t};\n\n\treturn new Promise((resolve) => {\n\t\twhenLoaded(() => resolve(element));\n\t\tif (timeoutMs > 0) {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tresolve(element);\n\t\t\t}, timeoutMs);\n\t\t}\n\t});\n}\n","import { Handler } from 'swup';\nimport Plugin from '@swup/plugin';\n\nimport mergeHeadContents from './mergeHeadContents.js';\nimport updateAttributes from './updateAttributes.js';\nimport waitForAssets from './waitForAssets.js';\n\ntype Options = {\n\t/** Whether to keep orphaned `link`, `style` and `script` tags from the old page. Default: `false` */\n\tpersistAssets: boolean;\n\t/** Tags that will be persisted when a new page is loaded. Boolean, selector or predicate function. Default: `false` */\n\tpersistTags: boolean | string | ((el: Element) => boolean);\n\t/** Delay the transition to the new page until all newly added assets have finished loading. Default: `false` */\n\tawaitAssets: boolean;\n\t/** Additional attributes of the head element to update. Default: ['lang', 'dir']. */\n\tattributes: (string | RegExp)[];\n\t/** How long to wait for assets before continuing anyway. Only applies if `awaitAssets` is enabled. Default: `3000` */\n\ttimeout: number;\n};\n\nexport default class SwupHeadPlugin extends Plugin {\n\tname = 'SwupHeadPlugin';\n\n\trequires = { swup: '>=4.6' };\n\n\tdefaults: Options = {\n\t\tpersistTags: false,\n\t\tpersistAssets: false,\n\t\tawaitAssets: false,\n\t\tattributes: ['lang', 'dir'],\n\t\ttimeout: 3000\n\t};\n\toptions: Options;\n\n\tconstructor(options: Partial<Options> = {}) {\n\t\tsuper();\n\n\t\tthis.options = { ...this.defaults, ...options };\n\n\t\t// persistAssets is a shortcut for: persistTags with a default asset selector for scripts & styles\n\t\tif (this.options.persistAssets && !this.options.persistTags) {\n\t\t\tthis.options.persistTags = 'link[rel=stylesheet], script[src], style';\n\t\t}\n\t}\n\n\tmount() {\n\t\tthis.before('content:replace', this.updateHead);\n\t}\n\n\tupdateHead: Handler<'content:replace'> = async (visit, { page: { html } }) => {\n\t\tconst { awaitAssets, attributes, timeout } = this.options;\n\n\t\tconst newDocument = visit.to.document!;\n\n\t\tconst { removed, added } = mergeHeadContents(document.head, newDocument.head, {\n\t\t\tshouldPersist: (el) => this.isPersistentTag(el)\n\t\t});\n\n\t\tthis.swup.log(`Removed ${removed.length} / added ${added.length} tags in head`);\n\n\t\tif (attributes?.length) {\n\t\t\tupdateAttributes(document.documentElement, newDocument.documentElement, attributes);\n\t\t}\n\n\t\tif (awaitAssets) {\n\t\t\tconst assetLoadPromises = waitForAssets(added, timeout);\n\t\t\tif (assetLoadPromises.length) {\n\t\t\t\tthis.swup.log(`Waiting for ${assetLoadPromises.length} assets to load`);\n\t\t\t\tawait Promise.all(assetLoadPromises);\n\t\t\t}\n\t\t}\n\t};\n\n\tisPersistentTag(el: Element) {\n\t\tconst { persistTags } = this.options;\n\t\tif (typeof persistTags === 'function') {\n\t\t\treturn persistTags(el);\n\t\t}\n\t\tif (typeof persistTags === 'string' && persistTags.length > 0) {\n\t\t\treturn el.matches(persistTags);\n\t\t}\n\t\treturn Boolean(persistTags);\n\t}\n}\n"],"names":["shouldManageTag","el","localName","matches","compareTags","oldTag","newTag","outerHTML","getAttributes","filters","all","Array","from","attributes","length","filter","name","some","pattern","RegExp","test","isStylesheet","Plugin","constructor","options","super","_this","this","requires","swup","defaults","persistTags","persistAssets","awaitAssets","timeout","updateHead","visit","page","newDocument","to","document","removed","added","currentHead","newHead","shouldPersist","currentTags","children","newChildren","addTags","currentEls","reduce","tags","index","currentEl","push","removeTags","newEls","newEl","getTagsToRemove","reverse","forEach","removeChild","newAddTags","map","tag","cloneNode","insertBefore","mergeHeadContents","head","isPersistentTag","log","target","source","keep","Set","value","setAttribute","add","has","removeAttribute","updateAttributes","documentElement","_temp2","assetLoadPromises","elements","timeoutMs","element","timeoutId","whenLoaded","cb","sheet","setTimeout","Promise","resolve","clearTimeout","waitForStylesheet","waitForAssets","_temp","then","e","reject","mount","before","Boolean"],"mappings":"sHAwDA,SAASA,EAAgBC,GAExB,MAAqB,UAAjBA,EAAGC,YAIHD,EAAGE,QAAQ,oBAIhB,CAEA,SAASC,EAAYC,EAAiBC,G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