Debian Codegraph @

frontend/src/router.ts

raw
1 /**
2 * Routing
3 *
4 * Fava intercepts all clicks on links and will in most cases asynchronously
5 * load the content of the page and replace the <article> contents with them.
6 */
7
8 import type { Readable, Writable } from "svelte/store";
9 import { writable } from "svelte/store";
10
11 import { getUrlPath } from "./helpers";
12 import { delegate, Events } from "./lib/events";
13 import { fetch, handleText } from "./lib/fetch";
14 import { DEFAULT_INTERVAL, getInterval } from "./lib/interval";
15 import { log_error } from "./log";
16 import { notify_err } from "./notifications";
17 import type { FrontendRoute } from "./reports/route";
18 import { raw_page_title } from "./sidebar/page-title";
19 import { conversion, interval } from "./stores";
20 import { showCharts } from "./stores/chart";
21 import { account_filter, fql_filter, time_filter } from "./stores/filters";
22 import { pathname, search, urlHash } from "./stores/url";
23
24 /**
25 * Set a store's inital value from the URL.
26 */
27 export function setStoreValuesFromURL(): void {
28 const params = new URL(window.location.href).searchParams;
29 account_filter.set(params.get("account") ?? "");
30 fql_filter.set(params.get("filter") ?? "");
31 time_filter.set(params.get("time") ?? "");
32 interval.set(getInterval(params.get("interval")));
33 conversion.set(params.get("conversion") ?? "at_cost");
34 showCharts.set(params.get("charts") !== "false");
35 }
36
37 const is_loading_internal = writable(false);
38 /** Whether the logo should be spinning to indicate that something is loading. */
39 export const is_loading: Readable<boolean> = is_loading_internal;
40
41 export class Router extends Events<"page-loaded"> {
42 /** The URL hash. */
43 private hash: string;
44
45 /** The URL pathname. */
46 private pathname: string;
47
48 /** The URL search string. */
49 private search: string;
50
51 /** The <article> element. */
52 private article: HTMLElement;
53
54 /** The frontend rendered routes. */
55 private frontend_routes?: FrontendRoute[];
56
57 /** A possibly frontend rendered component. */
58 private frontend_route?: FrontendRoute;
59
60 /**
61 * Function to intercept navigation, e.g., when there are unsaved changes.
62 *
63 * If they return a string, that is displayed to the user in an alert to
64 * confirm navigation.
65 */
66 private interruptHandlers: Set<() => string | null>;
67
68 constructor() {
69 super();
70
71 const article = document.querySelector("article");
72 if (!article) {
73 throw new Error("<article> element is missing from markup");
74 }
75 this.article = article;
76
77 this.hash = window.location.hash;
78 this.pathname = window.location.pathname;
79 this.search = window.location.search;
80
81 this.interruptHandlers = new Set();
82 }
83
84 /**
85 * Whether an interrupt handler is active like on the editor or import report.
86 * Avoid auto-reloading in that case.
87 */
88 get hasInteruptHandler(): boolean {
89 return this.interruptHandlers.size > 0;
90 }
91
92 /**
93 * Add an interrupt handler. Returns a function that removes it.
94 * This can be used directly in a svelte onMount hook.
95 */
96 addInteruptHandler(handler: () => string | null): () => void {
97 this.interruptHandlers.add(handler);
98
99 return () => {
100 this.interruptHandlers.delete(handler);
101 };
102 }
103
104 /**
105 * Check whether any of the registered interruptHandlers wants to stop
106 * navigation.
107 */
108 private shouldInterrupt(): string | null {
109 for (const handler of this.interruptHandlers) {
110 const ret = handler();
111 if (ret != null) {
112 return ret;
113 }
114 }
115 return null;
116 }
117
118 private async frontendRender(url: URL): Promise<void> {
119 const report = getUrlPath(url);
120 const route = this.frontend_routes?.find(
121 (r) => report?.startsWith(`${r.report}/`) === true,
122 );
123 if (route) {
124 is_loading_internal.set(true);
125 try {
126 await route.render(this.article, url, this.frontend_route);
127 } finally {
128 is_loading_internal.set(false);
129 }
130 raw_page_title.set(route.title);
131 } else {
132 this.frontend_route?.destroy();
133 }
134 this.frontend_route = route;
135 }
136
137 /**
138 * This should be called once when the page has been loaded. Initializes the
139 * router and takes over clicking on links.
140 */
141 init(frontend_routes: FrontendRoute[]): void {
142 this.frontend_routes = frontend_routes;
143 urlHash.set(window.location.hash.slice(1));
144 this.updateState();
145
146 this.frontendRender(new URL(window.location.href)).catch(log_error);
147
148 window.addEventListener("beforeunload", (event) => {
149 const leaveMessage = this.shouldInterrupt();
150 if (leaveMessage != null) {
151 event.preventDefault();
152 }
153 });
154
155 window.addEventListener("popstate", () => {
156 urlHash.set(window.location.hash.slice(1));
157 if (
158 window.location.hash !== this.hash &&
159 window.location.pathname === this.pathname &&
160 window.location.search === this.search
161 ) {
162 this.updateState();
163 } else if (
164 window.location.pathname !== this.pathname ||
165 window.location.search !== this.search
166 ) {
167 this.loadURL(window.location.href, false).catch(log_error);
168 setStoreValuesFromURL();
169 }
170 });
171
172 this.takeOverLinks();
173 }
174
175 /**
176 * Go to URL. If load is `true`, load the page at URL, otherwise only update
177 * the current state.
178 */
179 navigate(url: string, load = true): void {
180 if (load) {
181 this.loadURL(url).catch(log_error);
182 } else {
183 window.history.pushState(null, "", url);
184 this.updateState();
185 }
186 }
187
188 /**
189 * Set the URL parameter and push a history state for it if changed.
190 */
191 set_search_param(key: string, value: string): void {
192 const url = new URL(window.location.href);
193 const current_value = url.searchParams.get(key) ?? "";
194 if (value !== current_value) {
195 if (value) {
196 url.searchParams.set(key, value);
197 } else {
198 url.searchParams.delete(key);
199 }
200 window.history.pushState(null, "", url);
201 this.updateState();
202 }
203 }
204
205 /*
206 * Replace <article> contents with the page at `url`.
207 *
208 * If `historyState` is false, do not create a history state and do not
209 * scroll to top.
210 */
211 private async loadURL(url: string, historyState = true): Promise<void> {
212 const leaveMessage = this.shouldInterrupt();
213 if (leaveMessage != null) {
214 if (!window.confirm(leaveMessage)) {
215 return;
216 }
217 }
218
219 const getUrl = new URL(url, window.location.href);
220
221 await this.frontendRender(getUrl);
222
223 try {
224 if (!this.frontend_route) {
225 getUrl.searchParams.set("partial", "true");
226 is_loading_internal.set(true);
227 const content = await fetch(getUrl.toString()).then(handleText);
228 if (historyState) {
229 window.history.pushState(null, "", url);
230 window.scroll(0, 0);
231 }
232 this.updateState();
233 this.article.innerHTML = content;
234 } else {
235 if (historyState) {
236 window.history.pushState(null, "", url);
237 window.scroll(0, 0);
238 }
239 this.updateState();
240 }
241 this.trigger("page-loaded");
242 setStoreValuesFromURL();
243 const hash = window.location.hash.slice(1);
244 urlHash.set(hash);
245 if (hash) {
246 document.getElementById(hash)?.scrollIntoView();
247 }
248 } catch (error) {
249 notify_err(error, (e) => `Loading ${url} failed: ${e.message}`);
250 } finally {
251 is_loading_internal.set(false);
252 }
253 }
254
255 /*
256 * Update the routers state.
257 *
258 * The routers state is used to distinguish between the user navigating the
259 * browser history or the hash changing.
260 */
261 private updateState(): void {
262 this.hash = window.location.hash;
263 this.pathname = window.location.pathname;
264 this.search = window.location.search;
265 pathname.set(this.pathname);
266 search.set(this.search);
267 }
268
269 /*
270 * Intercept all clicks on links (<a>) and .navigate() to the link instead.
271 *
272 * Doesn't intercept if
273 * - a button different from the main button is used,
274 * - a modifier key is pressed,
275 * - the link starts with a hash '#', or
276 * - the link has a `data-remote` attribute.
277 */
278 private takeOverLinks(): void {
279 const is_normal_click = (event: MouseEvent) =>
280 event.button === 0 &&
281 !event.altKey &&
282 !event.ctrlKey &&
283 !event.metaKey &&
284 !event.shiftKey;
285
286 const is_external_link = (link: HTMLAnchorElement | SVGAElement) =>
287 link.hasAttribute("data-remote") ||
288 (link instanceof HTMLAnchorElement &&
289 (link.host !== window.location.host ||
290 !link.protocol.startsWith("http")));
291
292 delegate(document, "click", "a", (event, link) => {
293 if (
294 !(event instanceof MouseEvent) ||
295 !(link instanceof HTMLAnchorElement || link instanceof SVGAElement)
296 ) {
297 return;
298 }
299 if (!is_normal_click(event)) {
300 return;
301 }
302 if (event.defaultPrevented) {
303 return;
304 }
305 if (link.getAttribute("href")?.charAt(0) === "#") {
306 return;
307 }
308 if (is_external_link(link)) {
309 return;
310 }
311
312 event.preventDefault();
313 const href =
314 link instanceof HTMLAnchorElement ? link.href : link.href.baseVal;
315
316 this.navigate(href);
317 });
318 }
319
320 /*
321 * Reload the page.
322 */
323 reload(): void {
324 this.loadURL(window.location.href, false).catch(log_error);
325 }
326 }
327
328 const router = new Router();
329 export default router;
330
331 /**
332 * Sync a store value to the URL.
333 *
334 * Update and navigate to the URL on store changes.
335 */
336 function syncToURL<T extends boolean | string>(
337 store: Writable<T>,
338 name: string,
339 defaultValue: T,
340 shouldLoad = true,
341 ): void {
342 store.subscribe((val: T) => {
343 const newURL = new URL(window.location.href);
344 newURL.searchParams.set(name, val.toString());
345 if (val === "" || val === defaultValue) {
346 newURL.searchParams.delete(name);
347 }
348 if (newURL.href !== window.location.href) {
349 router.navigate(newURL.href, shouldLoad);
350 }
351 });
352 }
353
354 /**
355 * Update URL on store changes.
356 */
357 export function syncStoreValuesToURL(): void {
358 syncToURL(account_filter, "account", "");
359 syncToURL(fql_filter, "filter", "");
360 syncToURL(time_filter, "time", "");
361 syncToURL(interval, "interval", DEFAULT_INTERVAL);
362 syncToURL(conversion, "conversion", "at_cost");
363 syncToURL(showCharts, "charts", true, false);
364 }