Debian Codegraph @

frontend/src/helpers.ts

raw
1 import { derived, get as store_get } from "svelte/store";
2
3 import { base_url, fava_options } from "./stores";
4 import { syncedSearchParams } from "./stores/url";
5
6 /**
7 * Get the URL path relative to the base url of the current ledger.
8 */
9 export function getUrlPath(
10 url: Pick<URL | Location, "pathname">,
11 ): string | null {
12 const $base_url = store_get(base_url);
13 return $base_url && url.pathname.startsWith($base_url)
14 ? decodeURI(url.pathname.slice($base_url.length))
15 : null;
16 }
17
18 /**
19 * Get the URL string for one of Fava's reports (pure internal function, just exported for tests).
20 * @param $base_url - the current value of base_url
21 * @param $searchParams - the current value of searchParams or null
22 * if url-synced parameters are not needed.
23 * @param report - report name
24 * @param params - URL params to set
25 * @returns The URL string.
26 */
27 export function urlForInternal(
28 $base_url: string,
29 $syncedSearchParams: URLSearchParams | null,
30 report: string,
31 params: Record<string, string | number | undefined> | undefined,
32 ): string {
33 const url = `${$base_url}${report}`;
34 const urlParams = $syncedSearchParams
35 ? new URLSearchParams($syncedSearchParams)
36 : new URLSearchParams();
37 if (params) {
38 Object.entries(params).forEach(([key, value]) => {
39 if (value != null) {
40 urlParams.set(key, value.toString());
41 }
42 });
43 }
44 const urlParamString = urlParams.toString();
45 return urlParamString ? `${url}?${urlParams.toString()}` : url;
46 }
47
48 /**
49 * Get the URL string for one of Fava's reports.
50 */
51 export const urlFor = derived(
52 [base_url, syncedSearchParams],
53 ([$base_url, $syncedSearchParams]) =>
54 (
55 report: string,
56 params?: Record<string, string | number | undefined>,
57 ): string =>
58 urlForInternal($base_url, $syncedSearchParams, report, params),
59 );
60
61 /**
62 * Get the URL string for one of Fava's reports - without synced params.
63 */
64 export const urlForRaw = derived(
65 [base_url],
66 ([$base_url]) =>
67 (
68 report: string,
69 params?: Record<string, string | number | undefined>,
70 ): string =>
71 urlForInternal($base_url, null, report, params),
72 );
73
74 const use_external_editor = derived(
75 fava_options,
76 ($fava_options) => $fava_options.use_external_editor,
77 );
78
79 /** URL for the editor to the source location of an entry. */
80 export const urlForSource = derived(
81 [urlFor, use_external_editor],
82 ([$urlFor, $use_external_editor]) =>
83 (file_path: string, line: string): string =>
84 $use_external_editor
85 ? `beancount://${file_path}?lineno=${line}`
86 : $urlFor("editor/", { file_path, line }),
87 );
88
89 /** URL for the account report (derived store to keep track of filter changes.). */
90 export const urlForAccount = derived(
91 urlFor,
92 ($urlFor) =>
93 (account: string, params?: Record<string, string>): string =>
94 $urlFor(`account/${account}/`, params),
95 );