| 1 |
import type Swup from '../Swup.js'; |
| 2 |
import { query, queryAll } from '../utils.js'; |
| 3 |
import type { Visit } from './Visit.js'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Perform the replacement of content after loading a page. |
| 7 |
* |
| 8 |
* @returns Whether all containers were replaced. |
| 9 |
*/ |
| 10 |
export const replaceContent = function (this: Swup, visit: Visit): boolean { |
| 11 |
const incomingDocument = visit.to.document; |
| 12 |
if (!incomingDocument) return false; |
| 13 |
|
| 14 |
// Update browser title |
| 15 |
const title = incomingDocument.querySelector('title')?.innerText || ''; |
| 16 |
document.title = title; |
| 17 |
|
| 18 |
// Save persisted elements |
| 19 |
const persistedElements = queryAll('[data-swup-persist]:not([data-swup-persist=""])'); |
| 20 |
|
| 21 |
// Update content containers |
| 22 |
const replaced = visit.containers |
| 23 |
.map((selector) => { |
| 24 |
const currentEl = document.querySelector(selector); |
| 25 |
const incomingEl = incomingDocument.querySelector(selector); |
| 26 |
if (currentEl && incomingEl) { |
| 27 |
currentEl.replaceWith(incomingEl.cloneNode(true)); |
| 28 |
return true; |
| 29 |
} |
| 30 |
if (!currentEl) { |
| 31 |
console.warn(`[swup] Container missing in current document: ${selector}`); |
| 32 |
} |
| 33 |
if (!incomingEl) { |
| 34 |
console.warn(`[swup] Container missing in incoming document: ${selector}`); |
| 35 |
} |
| 36 |
return false; |
| 37 |
}) |
| 38 |
.filter(Boolean); |
| 39 |
|
| 40 |
// Restore persisted elements |
| 41 |
persistedElements.forEach((existing) => { |
| 42 |
const key = existing.getAttribute('data-swup-persist'); |
| 43 |
const replacement = query(`[data-swup-persist="${key}"]`); |
| 44 |
if (replacement && replacement !== existing) { |
| 45 |
replacement.replaceWith(existing); |
| 46 |
} |
| 47 |
}); |
| 48 |
|
| 49 |
// Return true if all containers were replaced |
| 50 |
return replaced.length === visit.containers.length; |
| 51 |
}; |