Debian Codegraph @

src/Swup.ts

raw
1 import { type DelegateEvent } from 'delegate-it';
2
3 import version from './config/version.js';
4
5 import { delegateEvent, getCurrentUrl, Location, updateHistoryRecord } from './helpers.js';
6 import { type DelegateEventUnsubscribe } from './helpers/delegateEvent.js';
7
8 import { Cache } from './modules/Cache.js';
9 import { Classes } from './modules/Classes.js';
10 import { type Visit, createVisit } from './modules/Visit.js';
11 import { Hooks, type HookName, type HookInitOptions } from './modules/Hooks.js';
12 import { getAnchorElement } from './modules/getAnchorElement.js';
13 import { awaitAnimations } from './modules/awaitAnimations.js';
14 import { navigate, performNavigation, type NavigationToSelfAction } from './modules/navigate.js';
15 import { fetchPage } from './modules/fetchPage.js';
16 import { animatePageOut } from './modules/animatePageOut.js';
17 import { replaceContent } from './modules/replaceContent.js';
18 import { scrollToContent } from './modules/scrollToContent.js';
19 import { animatePageIn } from './modules/animatePageIn.js';
20 import { renderPage } from './modules/renderPage.js';
21 import { use, unuse, findPlugin, type Plugin } from './modules/plugins.js';
22 import { isSameResolvedUrl, resolveUrl } from './modules/resolveUrl.js';
23 import { nextTick } from './utils.js';
24 import { type HistoryState } from './helpers/history.js';
25
26 /** Options for customizing swup's behavior. */
27 export type Options = {
28 /** Whether history visits are animated. Default: `false` */
29 animateHistoryBrowsing: boolean;
30 /** Selector for detecting animation timing. Default: `[class*="transition-"]` */
31 animationSelector: string | false;
32 /** Elements on which to add animation classes. Default: `html` element */
33 animationScope: 'html' | 'containers';
34 /** Enable in-memory page cache. Default: `true` */
35 cache: boolean;
36 /** Content containers to be replaced on page visits. Default: `['#swup']` */
37 containers: string[];
38 /** Callback for ignoring visits. Receives the element and event that triggered the visit. */
39 ignoreVisit: (url: string, { el, event }: { el?: Element; event?: Event }) => boolean;
40 /** Selector for links that trigger visits. Default: `'a[href]'` */
41 linkSelector: string;
42 /** How swup handles links to the same page. Default: `scroll` */
43 linkToSelf: NavigationToSelfAction;
44 /** Enable native animations using the View Transitions API. */
45 native: boolean;
46 /** Hook handlers to register. */
47 hooks: Partial<HookInitOptions>;
48 /** Plugins to register on startup. */
49 plugins: Plugin[];
50 /** Custom headers sent along with fetch requests. */
51 requestHeaders: Record<string, string>;
52 /** Rewrite URLs before loading them. */
53 resolveUrl: (url: string) => string;
54 /** Callback for telling swup to ignore certain popstate events. */
55 skipPopStateHandling: (event: PopStateEvent) => boolean;
56 /** Request timeout in milliseconds. */
57 timeout: number;
58 };
59
60 const defaults: Options = {
61 animateHistoryBrowsing: false,
62 animationSelector: '[class*="transition-"]',
63 animationScope: 'html',
64 cache: true,
65 containers: ['#swup'],
66 hooks: {},
67 ignoreVisit: (url, { el } = {}) => !!el?.closest('[data-no-swup]'),
68 linkSelector: 'a[href]',
69 linkToSelf: 'scroll',
70 native: false,
71 plugins: [],
72 resolveUrl: (url) => url,
73 requestHeaders: {
74 'X-Requested-With': 'swup',
75 'Accept': 'text/html, application/xhtml+xml'
76 },
77 skipPopStateHandling: (event) => (event.state as HistoryState)?.source !== 'swup',
78 timeout: 0
79 };
80
81 /** Swup page transition library. */
82 export default class Swup {
83 /** Library version */
84 readonly version: string = version;
85 /** Options passed into the instance */
86 options: Options;
87 /** Default options before merging user options */
88 readonly defaults: Options = defaults;
89 /** Registered plugin instances */
90 plugins: Plugin[] = [];
91 /** Data about the current visit */
92 visit: Visit;
93 /** Cache instance */
94 readonly cache: Cache;
95 /** Hook registry */
96 readonly hooks: Hooks;
97 /** Animation class manager */
98 readonly classes: Classes;
99 /** Location of the currently visible page */
100 location: Location = Location.fromUrl(window.location.href);
101 /** URL of the currently visible page @deprecated Use swup.location.url instead */
102 get currentPageUrl(): string {
103 return this.location.url;
104 }
105 /** Index of the current history entry */
106 protected currentHistoryIndex: number;
107 /** Delegated event subscription handle */
108 protected clickDelegate?: DelegateEventUnsubscribe;
109 /** Navigation status */
110 protected navigating: boolean = false;
111 /** Run anytime a visit ends */
112 protected onVisitEnd?: () => Promise<unknown>;
113
114 /** Install a plugin */
115 use = use;
116 /** Uninstall a plugin */
117 unuse = unuse;
118 /** Find a plugin by name or instance */
119 findPlugin = findPlugin;
120
121 /** Log a message. Has no effect unless debug plugin is installed */
122 log: (message: string, context?: unknown) => void = () => {};
123
124 /** Navigate to a new URL */
125 navigate = navigate;
126 /** Actually perform a navigation */
127 protected performNavigation = performNavigation;
128 /** Create a new context for this visit */
129 protected createVisit = createVisit;
130 /** Register a delegated event listener */
131 delegateEvent = delegateEvent;
132 /** Fetch a page from the server */
133 fetchPage = fetchPage;
134 /** Resolve when animations on the page finish */
135 awaitAnimations = awaitAnimations;
136 protected renderPage = renderPage;
137 /** Replace the content after page load */
138 replaceContent = replaceContent;
139 protected animatePageIn = animatePageIn;
140 protected animatePageOut = animatePageOut;
141 protected scrollToContent = scrollToContent;
142 /** Find the anchor element for a given hash */
143 getAnchorElement = getAnchorElement;
144
145 /** Get the current page URL */
146 getCurrentUrl = getCurrentUrl;
147 /** Resolve a URL to its final location */
148 resolveUrl = resolveUrl;
149 /** Check if two URLs resolve to the same location */
150 protected isSameResolvedUrl = isSameResolvedUrl;
151
152 constructor(options: Partial<Options> = {}) {
153 // Merge defaults and options
154 this.options = { ...this.defaults, ...options };
155
156 this.handleLinkClick = this.handleLinkClick.bind(this);
157 this.handlePopState = this.handlePopState.bind(this);
158
159 this.cache = new Cache(this);
160 this.classes = new Classes(this);
161 this.hooks = new Hooks(this);
162 this.visit = this.createVisit({ to: '' });
163
164 this.currentHistoryIndex = (window.history.state as HistoryState)?.index ?? 1;
165
166 this.enable();
167 }
168
169 /** Enable this instance, adding listeners and classnames. */
170 async enable() {
171 // Add event listener
172 const { linkSelector } = this.options;
173 this.clickDelegate = this.delegateEvent(linkSelector, 'click', this.handleLinkClick);
174
175 window.addEventListener('popstate', this.handlePopState);
176
177 // Set scroll restoration to manual if animating history visits
178 if (this.options.animateHistoryBrowsing) {
179 window.history.scrollRestoration = 'manual';
180 }
181
182 // Initial save to cache
183 if (this.options.cache) {
184 // Disabled to avoid caching modified dom state: logic moved to preload plugin
185 // https://github.com/swup/swup/issues/475
186 }
187
188 // Sanitize/check native option
189 this.options.native = this.options.native && !!document.startViewTransition;
190
191 // Mount plugins
192 this.options.plugins.forEach((plugin) => this.use(plugin));
193
194 // Install user hooks
195 for (const [key, handler] of Object.entries(this.options.hooks)) {
196 // Build hook options from modifier suffix: 'content:replace.before' => { before: true }
197 const [hook, modifiers] = this.hooks.parseName(key as HookName);
198 // @ts-expect-error: object.entries() does not preserve key/value types
199 this.hooks.on(hook, handler, modifiers);
200 }
201
202 // Create initial history record
203 if ((window.history.state as HistoryState)?.source !== 'swup') {
204 updateHistoryRecord(null, { index: this.currentHistoryIndex });
205 }
206
207 // Give consumers a chance to hook into enable
208 await nextTick();
209
210 // Trigger enable hook
211 await this.hooks.call('enable', undefined, undefined, () => {
212 const html = document.documentElement;
213 html.classList.add('swup-enabled');
214 html.classList.toggle('swup-native', this.options.native);
215 });
216 }
217
218 /** Disable this instance, removing listeners and classnames. */
219 async destroy() {
220 // remove delegated listener
221 this.clickDelegate!.destroy();
222
223 // remove popstate listener
224 window.removeEventListener('popstate', this.handlePopState);
225
226 // empty cache
227 this.cache.clear();
228
229 // unmount plugins
230 this.options.plugins.forEach((plugin) => this.unuse(plugin));
231
232 // trigger disable hook
233 await this.hooks.call('disable', undefined, undefined, () => {
234 const html = document.documentElement;
235 html.classList.remove('swup-enabled');
236 html.classList.remove('swup-native');
237 });
238
239 // remove handlers
240 this.hooks.clear();
241 }
242
243 /** Determine if a visit should be ignored by swup, based on URL or trigger element. */
244 shouldIgnoreVisit(href: string, { el, event }: { el?: Element; event?: Event } = {}) {
245 const { origin, url, hash } = Location.fromUrl(href);
246
247 // Ignore if the new origin doesn't match the current one
248 if (origin !== window.location.origin) {
249 return true;
250 }
251
252 // Ignore if the link/form would open a new window (or none at all)
253 if (el && this.triggerWillOpenNewWindow(el)) {
254 return true;
255 }
256
257 // Ignore if the visit should be ignored as per user options
258 if (this.options.ignoreVisit(url + hash, { el, event })) {
259 return true;
260 }
261
262 // Finally, allow the visit
263 return false;
264 }
265
266 protected handleLinkClick(event: DelegateEvent<MouseEvent>) {
267 const el = event.delegateTarget as HTMLAnchorElement;
268 const { href, url, hash } = Location.fromElement(el);
269
270 // Exit early if the link should be ignored
271 if (this.shouldIgnoreVisit(href, { el, event })) {
272 return;
273 }
274
275 // Ignore if swup is currently navigating towards the link's URL
276 if (this.navigating && url === this.visit.to.url) {
277 event.preventDefault();
278 return;
279 }
280
281 const visit = this.createVisit({ to: url, hash, el, event });
282
283 // Exit early if control key pressed
284 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
285 this.hooks.callSync('link:newtab', visit, { href });
286 return;
287 }
288
289 // Exit early if other than left mouse button
290 if (event.button !== 0) {
291 return;
292 }
293
294 this.hooks.callSync('link:click', visit, { el, event }, () => {
295 const from = visit.from.url ?? '';
296
297 event.preventDefault();
298
299 // Handle links to the same page
300 if (!url || url === from) {
301 if (hash) {
302 // With hash: scroll to anchor
303 this.hooks.callSync('link:anchor', visit, { hash }, () => {
304 updateHistoryRecord(url + hash);
305 this.scrollToContent(visit);
306 });
307 } else {
308 // Without hash: scroll to top or load/reload page
309 this.hooks.callSync('link:self', visit, undefined, () => {
310 if (this.options.linkToSelf === 'navigate') {
311 this.performNavigation(visit);
312 } else {
313 updateHistoryRecord(url);
314 this.scrollToContent(visit);
315 }
316 });
317 }
318 return;
319 }
320
321 // Exit early if the resolved path hasn't changed
322 if (this.isSameResolvedUrl(url, from)) {
323 return;
324 }
325
326 // Finally, proceed with loading the page
327 this.performNavigation(visit);
328 });
329 }
330
331 protected handlePopState(event: PopStateEvent) {
332 const href: string = (event.state as HistoryState)?.url ?? window.location.href;
333
334 // Exit early if this event should be ignored
335 if (this.options.skipPopStateHandling(event)) {
336 return;
337 }
338
339 // Exit early if the resolved path hasn't changed
340 if (this.isSameResolvedUrl(getCurrentUrl(), this.location.url)) {
341 return;
342 }
343
344 const { url, hash } = Location.fromUrl(href);
345
346 const visit = this.createVisit({ to: url, hash, event });
347
348 // Mark as history visit
349 visit.history.popstate = true;
350
351 // Determine direction of history visit
352 const index = (event.state as HistoryState)?.index ?? 0;
353 if (index && index !== this.currentHistoryIndex) {
354 const direction = index - this.currentHistoryIndex > 0 ? 'forwards' : 'backwards';
355 visit.history.direction = direction;
356 this.currentHistoryIndex = index;
357 }
358
359 // Disable animation & scrolling for history visits
360 visit.animation.animate = false;
361 visit.scroll.reset = false;
362 visit.scroll.target = false;
363
364 // Animated history visit: re-enable animation & scroll reset
365 if (this.options.animateHistoryBrowsing) {
366 visit.animation.animate = true;
367 visit.scroll.reset = true;
368 }
369
370 this.hooks.callSync('history:popstate', visit, { event }, () => {
371 this.performNavigation(visit);
372 });
373 }
374
375 /** Determine whether an element will open a new tab when clicking/activating. */
376 protected triggerWillOpenNewWindow(triggerEl: Element) {
377 if (triggerEl.matches('[download], [target="_blank"]')) {
378 return true;
379 }
380 return false;
381 }
382 }