-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathindex.ts
More file actions
174 lines (158 loc) · 5.45 KB
/
Copy pathindex.ts
File metadata and controls
174 lines (158 loc) · 5.45 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { range } from "d3-array";
import { mount, unmount } from "svelte";
import { get as store_get } from "svelte/store";
import { delegate } from "../lib/events.ts";
import { fetch, handleText } from "../lib/fetch.ts";
import { log_error } from "../log.ts";
import { notify_err } from "../notifications.ts";
import { router } from "../router.ts";
import { type SortableJournal, sortableJournal } from "../sort/index.ts";
import { fql_filter } from "../stores/filters.ts";
import { journalShow } from "../stores/journal.ts";
import JournalFilters from "./JournalFilters.svelte";
/**
* Escape the value to produce a valid regex for the Fava filter.
*/
export function escape_for_regex(value: string): string {
return value.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
}
/**
* Add a filter to the existing list of filters. Any parts that are interpreted
* as a regex must be escaped.
*/
function addFilter(value: string): void {
const $fql_filter = store_get(fql_filter);
router.set_search_param(
"filter",
$fql_filter ? `${$fql_filter} ${value}` : value,
);
}
function handleClick({ target }: Event): void {
if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
return;
}
if (target.className === "tag" || target.className === "link") {
// Filter for tags and links when clicking on them.
addFilter(target.innerText);
} else if (target.className === "payee") {
// Filter for payees when clicking on them.
// Note: any special characters in the payee string are escaped so the
// filter matches against the payee literally.
addFilter(`payee:"^${escape_for_regex(target.innerText)}$"`);
} else if (target.tagName === "DT") {
// Filter for metadata key when clicking on the key. The key tag text
// includes the colon.
const expr = `${target.innerText}""`;
if (target.closest(".postings")) {
// Posting metadata.
addFilter(`any(${expr})`);
} else {
// Entry metadata.
addFilter(expr);
}
} else if (target.tagName === "DD") {
// Filter for metadata key and value when clicking on the value. The key
// tag text includes the colon.
const key = (target.previousElementSibling as HTMLElement).innerText;
const value = `"^${escape_for_regex(target.innerText)}$"`;
const expr = `${key}${value}`;
if (target.closest(".postings")) {
// Posting metadata.
addFilter(`any(${expr})`);
} else {
// Entry metadata.
addFilter(expr);
}
} else if (target.closest(".indicators")) {
// Toggle postings and metadata by clicking on indicators.
const entry = target.closest(".journal > li");
if (entry) {
entry.classList.toggle("show-full-entry");
}
}
}
export class FavaJournal extends HTMLElement {
/** Unmount the Svelte component. */
unmount?: () => void;
/** Unsubscribe store listener. */
unsubscribe?: () => void;
sortableJournal?: SortableJournal;
connectedCallback(): void {
const ol = this.querySelector("ol");
if (!ol) {
throw new Error("fava-journal is missing its <ol>");
}
const total_pages = this.getAttribute("total-pages");
if (total_pages != null) {
void this.fetchAllPages(ol, parseInt(total_pages, 10));
}
this.unsubscribe = journalShow.subscribe((show) => {
const classes = [...show].map((s) => `show-${s}`).join(" ");
ol.className = `flex-table journal ${classes}`;
});
const component = mount(JournalFilters, { target: this, anchor: ol });
this.unmount = () => {
void unmount(component);
};
this.sortableJournal = sortableJournal(ol);
delegate(this, "click", "li", handleClick);
}
disconnectedCallback(): void {
this.unsubscribe?.();
this.unmount?.();
}
private async fetchAllPages(
ol: HTMLOListElement,
total: number,
): Promise<void> {
const { current } = router;
const parser = new DOMParser();
const pages = range(2, total + 1);
const pages_and_urls = pages.map((page): [number, URL] => {
const page_url = new URL(current);
page_url.searchParams.set("partial", "true");
page_url.searchParams.set("page", page.toString());
return [page, page_url];
});
let errorShown = false;
const promises = pages_and_urls.map(async ([page, page_url]) => {
return fetch(page_url)
.then(handleText)
.then(
(html) => {
const doc = parser.parseFromString(html, "text/html");
return doc.querySelectorAll("ol.journal > li:not(.head)");
},
(error: unknown) => {
log_error(`Failed to fetch page ${page.toString()}`, error);
if (!errorShown) {
notify_err(new Error("Failed to fetch some journal pages"));
errorShown = true;
}
return [];
},
);
});
let sorting = false;
for (const promise of promises) {
ol.append(...(await promise));
if (sorting) {
continue;
}
sorting = true;
// Batch sorting to avoid repeatedly sorting in-between consecutive
// items appending.
setTimeout(() => {
sorting = false;
if (this.sortableJournal) {
const [column, order] = this.sortableJournal.getOrder();
// The data is already sorted by date desc, so no need to sort again
// if that's the current order.
if (column !== "date" || order !== "desc") {
this.sortableJournal.sort();
}
}
});
}
}
}