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