Debian Codegraph @

src/modules/navigate.ts

raw
1 import type Swup from '../Swup.js';
2 import { FetchError, type FetchOptions, type PageData } from './fetchPage.js';
3 import { type VisitInitOptions, type Visit, VisitState } from './Visit.js';
4 import { createHistoryRecord, updateHistoryRecord, Location, classify } from '../helpers.js';
5 import { getContextualAttr } from '../utils.js';
6
7 export type HistoryAction = 'push' | 'replace';
8 export type HistoryDirection = 'forwards' | 'backwards';
9 export type NavigationToSelfAction = 'scroll' | 'navigate';
10 export type CacheControl = Partial<{ read: boolean; write: boolean }>;
11
12 /** Define how to navigate to a page. */
13 type NavigationOptions = {
14 /** Whether this visit is animated. Default: `true` */
15 animate?: boolean;
16 /** Name of a custom animation to run. */
17 animation?: string;
18 /** History action to perform: `push` for creating a new history entry, `replace` for replacing the current entry. Default: `push` */
19 history?: HistoryAction;
20 /** Whether this visit should read from or write to the cache. */
21 cache?: CacheControl;
22 /** Custom metadata associated with this visit. */
23 meta?: Record<string, unknown>;
24 };
25
26 /**
27 * Navigate to a new URL.
28 * @param url The URL to navigate to.
29 * @param options Options for how to perform this visit.
30 * @returns Promise<void>
31 */
32 export function navigate(
33 this: Swup,
34 url: string,
35 options: NavigationOptions & FetchOptions = {},
36 init: Omit<VisitInitOptions, 'to'> = {}
37 ) {
38 if (typeof url !== 'string') {
39 throw new Error(`swup.navigate() requires a URL parameter`);
40 }
41
42 // Check if the visit should be ignored
43 if (this.shouldIgnoreVisit(url, { el: init.el, event: init.event })) {
44 window.location.assign(url);
45 return;
46 }
47
48 const { url: to, hash } = Location.fromUrl(url);
49
50 const visit = this.createVisit({ ...init, to, hash });
51 this.performNavigation(visit, options);
52 }
53
54 /**
55 * Start a visit to a new URL.
56 *
57 * Internal method that assumes the visit context has already been created.
58 *
59 * As a user, you should call `swup.navigate(url)` instead.
60 *
61 * @param url The URL to navigate to.
62 * @param options Options for how to perform this visit.
63 * @returns Promise<void>
64 */
65 export async function performNavigation(
66 this: Swup,
67 visit: Visit,
68 options: NavigationOptions & FetchOptions = {}
69 ): Promise<void> {
70 if (this.navigating) {
71 if (this.visit.state >= VisitState.ENTERING) {
72 // Currently navigating and content already loaded? Finish and queue
73 visit.state = VisitState.QUEUED;
74 this.onVisitEnd = () => this.performNavigation(visit, options);
75 return;
76 } else {
77 // Currently navigating and content not loaded? Abort running visit
78 await this.hooks.call('visit:abort', this.visit, undefined);
79 delete this.visit.to.document;
80 this.visit.state = VisitState.ABORTED;
81 }
82 }
83
84 this.navigating = true;
85 this.visit = visit;
86
87 const { el } = visit.trigger;
88 options.referrer = options.referrer || this.location.url;
89
90 if (options.animate === false) {
91 visit.animation.animate = false;
92 }
93
94 // Clean up old animation classes
95 if (!visit.animation.animate) {
96 this.classes.clear();
97 }
98
99 // Get history action from option or attribute on trigger element
100 const history = options.history || getContextualAttr(el, 'data-swup-history');
101 if (typeof history === 'string' && ['push', 'replace'].includes(history)) {
102 visit.history.action = history as HistoryAction;
103 }
104
105 // Get custom animation name from option or attribute on trigger element
106 const animation = options.animation || getContextualAttr(el, 'data-swup-animation');
107 if (typeof animation === 'string') {
108 visit.animation.name = animation;
109 }
110
111 // Get custom metadata from option
112 visit.meta = options.meta || {};
113
114 // Sanitize cache option
115 if (typeof options.cache === 'object') {
116 visit.cache.read = options.cache.read ?? visit.cache.read;
117 visit.cache.write = options.cache.write ?? visit.cache.write;
118 } else if (options.cache !== undefined) {
119 visit.cache = { read: !!options.cache, write: !!options.cache };
120 }
121 // Delete this so that window.fetch doesn't misinterpret it
122 delete options.cache;
123
124 try {
125 await this.hooks.call('visit:start', visit, undefined);
126
127 visit.state = VisitState.STARTED;
128
129 // Begin loading page
130 const page = this.hooks.call('page:load', visit, { options }, async (visit, args) => {
131 // Read from cache
132 let cachedPage: PageData | undefined;
133 if (visit.cache.read) {
134 cachedPage = this.cache.get(visit.to.url);
135 }
136
137 args.page = cachedPage || (await this.fetchPage(visit.to.url, args.options));
138 args.cache = !!cachedPage;
139
140 return args.page;
141 });
142
143 /**
144 * When the page is loaded: mark the visit as loaded and save
145 * the raw html and a parsed document of the received page in the visit object
146 */
147 page.then(({ html }) => {
148 visit.advance(VisitState.LOADED);
149 visit.to.html = html;
150 visit.to.document = new DOMParser().parseFromString(html, 'text/html');
151 });
152
153 // Create/update history record if this is not a popstate call or leads to the same URL
154 const newUrl = visit.to.url + visit.to.hash;
155 if (!visit.history.popstate) {
156 if (visit.history.action === 'replace' || visit.to.url === this.location.url) {
157 updateHistoryRecord(newUrl);
158 } else {
159 this.currentHistoryIndex++;
160 createHistoryRecord(newUrl, { index: this.currentHistoryIndex });
161 }
162 }
163 this.location = Location.fromUrl(newUrl);
164
165 // Mark visit type with classes
166 if (visit.history.popstate) {
167 this.classes.add('is-popstate');
168 }
169 if (visit.animation.name) {
170 this.classes.add(`to-${classify(visit.animation.name)}`);
171 }
172
173 // Wait for page before starting to animate out?
174 if (visit.animation.wait) {
175 await page;
176 }
177
178 // Check if failed/aborted in the meantime
179 if (visit.done) return;
180
181 // Perform the actual transition: animate and replace content
182 await this.hooks.call('visit:transition', visit, undefined, async () => {
183 // No animation? Just await page and render
184 if (!visit.animation.animate) {
185 await this.hooks.call('animation:skip', undefined);
186 await this.renderPage(visit, await page);
187 return;
188 }
189
190 // Animate page out, render page, animate page in
191 visit.advance(VisitState.LEAVING);
192 await this.animatePageOut(visit);
193 if (visit.animation.native && document.startViewTransition) {
194 await document.startViewTransition(
195 async () => await this.renderPage(visit, await page)
196 ).finished;
197 } else {
198 await this.renderPage(visit, await page);
199 }
200 await this.animatePageIn(visit);
201 });
202
203 // Check if failed/aborted in the meantime
204 if (visit.done) return;
205
206 // Finalize visit
207 await this.hooks.call('visit:end', visit, undefined, () => this.classes.clear());
208 visit.state = VisitState.COMPLETED;
209 this.navigating = false;
210
211 /** Run eventually queued function */
212 if (this.onVisitEnd) {
213 this.onVisitEnd();
214 this.onVisitEnd = undefined;
215 }
216 } catch (error) {
217 // Return early if error is undefined or signals an aborted request
218 if (!error || (error as FetchError)?.aborted) {
219 visit.state = VisitState.ABORTED;
220 return;
221 }
222
223 visit.state = VisitState.FAILED;
224
225 // Log to console
226 console.error(error);
227
228 // Remove current history entry, then load requested url in browser
229 this.options.skipPopStateHandling = () => {
230 window.location.assign(visit.to.url + visit.to.hash);
231 return true;
232 };
233
234 // Go back to the actual page we're still at
235 window.history.back();
236 } finally {
237 delete visit.to.document;
238 }
239 }