Repository navigation
Expand file tree
/
Copy pathsqlpage.ts
More file actions
580 lines (543 loc) · 19 KB
/
Copy pathsqlpage.ts
File metadata and controls
580 lines (543 loc) · 19 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
import { bootstrap as bundled_bootstrap } from "@tabler/core";
import type * as Leaflet from "leaflet";
import { add_init_fn, type InitRoot, select_all } from "./init.ts";
// A page may load its own Bootstrap; prefer it over the bundled copy.
const page_bootstrap = () => window.bootstrap ?? bundled_bootstrap;
const nonce =
document.currentScript instanceof HTMLScriptElement
? document.currentScript.nonce
: "";
function sqlpage_card(root: InitRoot) {
const cards = select_all(root, "[data-pre-init=card]", HTMLElement);
for (const c of cards) {
c.removeAttribute("data-pre-init");
if (!c.dataset.embed) continue;
const url = new URL(c.dataset.embed, window.location.href);
url.searchParams.set("_sqlpage_embed", "1");
fetch(url)
.then((res) => res.text())
.then((html) => {
const body = c.querySelector(".card-content");
if (body) body.innerHTML = html;
const spinner = c.querySelector(".card-loading-placeholder");
spinner?.remove();
const fragLoadedEvt = new CustomEvent("fragment-loaded", {
bubbles: true,
});
c.dispatchEvent(fragLoadedEvt);
})
.catch((e) => {
console.error(e);
c.querySelector(".card-loading-placeholder")?.remove();
});
}
}
function setup_table(root_el: HTMLElement) {
const search_input = root_el.querySelector<HTMLInputElement>("input.search");
const table_el = root_el.querySelector("table");
if (!table_el) return;
const sort_button_els = table_el.querySelectorAll<HTMLElement>(
"button.sort[data-sort]",
);
const sort_buttons = [...sort_button_els];
const item_parent = table_el.querySelector("tbody");
const has_sort = sort_buttons.length > 0;
if (search_input || has_sort) {
const items = table_parse_data(table_el, sort_buttons);
if (search_input) setup_table_search_behavior(search_input, items);
if (has_sort && item_parent)
setup_sort_behavior(sort_buttons, items, item_parent);
}
// Change number format AFTER parsing and storing the sort keys
apply_number_formatting(table_el);
}
/**
*/
function setup_table_search_behavior(
search_input: HTMLInputElement,
items: TableRow[],
) {
function onSearch() {
const lower_search = search_input.value
.toLowerCase()
.split(/\s+/)
.filter((s) => s);
for (const item of items) {
const show = lower_search.every((s) =>
item.el.textContent.toLowerCase().includes(s),
);
item.el.style.display = show ? "" : "none";
}
}
search_input.addEventListener("input", onSearch);
onSearch();
}
function apply_number_formatting(table_el: HTMLElement) {
const header_els = table_el.querySelectorAll<HTMLElement>("thead > tr > th");
const col_types = [...header_els].map((el) => el.dataset.column_type);
const col_rawnums = [...header_els].map((el) => !!el.dataset.raw_number);
const col_money = [...header_els].map((el) => !!el.dataset.money);
const number_format_locale = table_el.dataset.number_format_locale;
const number_format_digits = table_el.dataset.number_format_digits
? Number(table_el.dataset.number_format_digits)
: undefined;
const currency = table_el.dataset.currency;
for (const tr_el of table_el.querySelectorAll("tbody tr, tfoot tr")) {
const cells = tr_el.getElementsByTagName("td");
for (const [idx, cell_el] of [...cells].entries()) {
const column_type = col_types[idx];
const is_raw_number = col_rawnums[idx];
const text = cell_el.textContent;
if (column_type === "number" && !is_raw_number && text) {
const num = Number.parseFloat(text);
const is_money = col_money[idx];
cell_el.textContent = num.toLocaleString(number_format_locale, {
maximumFractionDigits: number_format_digits,
currency,
style: is_money ? "currency" : undefined,
});
}
}
}
}
type TableRow = { el: HTMLElement; sort_keys: { num: number; str: string }[] };
/** Prepare the table rows for sorting.
*/
function table_parse_data(
table_el: HTMLElement,
sort_buttons: HTMLElement[],
): TableRow[] {
const is_num = [...sort_buttons].map(
(btn_el) => btn_el.parentElement?.dataset.column_type === "number",
);
const row_els = table_el.querySelectorAll<HTMLElement>("tbody tr");
return [...row_els].map((tr_el) => {
const cells = tr_el.getElementsByTagName("td");
return {
el: tr_el,
sort_keys: sort_buttons.map((_btn_el, idx) => {
const str = cells[idx]?.textContent ?? "";
const num = is_num[idx] ? Number.parseFloat(str) : Number.NaN;
return { num, str };
}),
};
});
}
/**
* Adds event listeners to the sort buttons to sort the table rows.
*/
function setup_sort_behavior(
sort_buttons: HTMLElement[],
items: TableRow[],
item_parent: HTMLElement,
) {
sort_buttons.forEach((button, button_index) => {
button.addEventListener("click", function sort_items() {
const sort_desc = button.classList.contains("asc");
for (const b of sort_buttons) {
b.classList.remove("asc", "desc");
}
button.classList.add(sort_desc ? "desc" : "asc");
const multiplier = sort_desc ? -1 : 1;
items.sort((a, b) => {
const a_key = a.sort_keys[button_index];
const b_key = b.sort_keys[button_index];
if (!a_key || !b_key)
throw new Error("Table row is missing the selected column sort key");
return (
multiplier *
(Number.isNaN(a_key.num) || Number.isNaN(b_key.num)
? a_key.str.localeCompare(b_key.str)
: a_key.num - b_key.num)
);
});
item_parent.append(...items.map((item) => item.el));
});
});
}
function sqlpage_table(root: InitRoot) {
const tables = select_all(root, "[data-pre-init=table]", HTMLElement);
for (const r of tables) {
r.removeAttribute("data-pre-init");
try {
setup_table(r);
} catch (e) {
console.error(e);
}
}
}
// Leaflet is loaded from a CDN by sqlpage_map, so it is a global, not an import.
declare const L: typeof Leaflet;
type MarkerStyle = Leaflet.MarkerOptions &
Leaflet.PathOptions & {
/** A GeoJSON feature may size its own icon, overriding the SVG's width. */
size?: number | string;
};
let is_leaflet_injected = false;
let is_leaflet_loaded = false;
const pending_maps = new Set<HTMLElement>();
function sqlpage_map(root: InitRoot) {
const maps = select_all(root, "[data-pre-init=map]", HTMLElement);
const first_map = maps[0];
if (!is_leaflet_loaded) {
for (const map of maps) pending_maps.add(map);
}
const leaflet_base_url = "https://cdn.jsdelivr.net/npm/leaflet@1.9.4";
if (first_map && !is_leaflet_injected) {
// Add the leaflet js and css to the page
const leaflet_css = document.createElement("link");
leaflet_css.rel = "stylesheet";
leaflet_css.href = `${leaflet_base_url}/dist/leaflet.css`;
leaflet_css.integrity =
"sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=";
leaflet_css.crossOrigin = "anonymous";
document.head.appendChild(leaflet_css);
const leaflet_js = document.createElement("script");
leaflet_js.src = `${leaflet_base_url}/dist/leaflet.js`;
leaflet_js.integrity =
"sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=";
leaflet_js.crossOrigin = "anonymous";
leaflet_js.nonce = nonce;
// Preserve each announced map, including maps arriving during loading.
leaflet_js.onload = () => {
is_leaflet_loaded = true;
for (const map of pending_maps) {
if (map.isConnected) onLeafletLoad(map);
}
pending_maps.clear();
};
document.head.appendChild(leaflet_js);
is_leaflet_injected = true;
}
if (first_map && is_leaflet_loaded) {
onLeafletLoad(root);
}
function parseCoords(
coords: string | undefined,
): Leaflet.LatLngTuple | undefined {
if (!coords) return undefined;
const [latitude, longitude] = coords
.split(",", 2)
.map((c) => Number.parseFloat(c));
if (
latitude === undefined ||
longitude === undefined ||
!Number.isFinite(latitude) ||
!Number.isFinite(longitude)
) {
console.error(
`Invalid map coordinates: ${JSON.stringify(coords)}. Expected a "latitude,longitude" pair of numbers.`,
);
return undefined;
}
return [latitude, longitude];
}
function onLeafletLoad(map_root: InitRoot) {
is_leaflet_loaded = true;
const maps = select_all(map_root, "[data-pre-init=map]", HTMLElement);
for (const m of maps) {
const tile_source = m.dataset.tile_source;
const maxZoom = Number(m.dataset.max_zoom);
const attribution = m.dataset.attribution;
const map = L.map(m, { attributionControl: !!attribution });
const zoom = Number(m.dataset.zoom);
const center = parseCoords(m.dataset.center);
if (tile_source)
L.tileLayer(tile_source, { attribution, maxZoom }).addTo(map);
const markers: (Leaflet.Marker | Leaflet.GeoJSON)[] = [];
for (const marker_elem of m.querySelectorAll<HTMLElement>(".marker")) {
setTimeout(() => {
const marker = addMarker(marker_elem, map);
if (marker) markers.push(marker);
}, 0);
}
setTimeout(() => {
if (center) map.setView(center, zoom);
else {
const bounds = L.latLngBounds([]);
for (const marker of markers)
bounds.extend(
marker instanceof L.Marker
? marker.getLatLng()
: marker.getBounds(),
);
if (markers.length > 0) map.fitBounds(bounds);
else map.setView([51.505, 10], zoom);
if (!Number.isNaN(zoom)) map.setZoom(zoom);
}
}, 100);
m.removeAttribute("data-pre-init");
m.querySelector(".spinner-border")?.remove();
}
}
function addMarker(marker_elem: HTMLElement, map: Leaflet.Map) {
const { color, coords, geojson, link } = marker_elem.dataset;
const options: MarkerStyle = {
color,
title: marker_elem.querySelector("h3")?.textContent?.trim(),
};
const marker = coords
? createMarker(marker_elem, options)
: geojson && createGeoJSONMarker(marker_elem, geojson, options);
if (!marker) return undefined;
marker.addTo(map);
if (marker_elem.textContent?.trim()) marker.bindPopup(marker_elem);
else if (link) {
marker.on("click", () => {
window.location.href = link;
});
}
return marker;
}
function createMarker(marker_elem: HTMLElement, options: MarkerStyle) {
const coords = parseCoords(marker_elem.dataset.coords);
return coords && createMarkerAt(marker_elem, coords, options);
}
function createMarkerAt(
marker_elem: HTMLElement,
coords: Leaflet.LatLngTuple,
options: MarkerStyle,
) {
const icon_obj = marker_elem.querySelector<HTMLElement>(".mapicon");
if (!icon_obj) return L.marker(coords, options);
const size =
1.5 *
+(
options.size ||
icon_obj.firstElementChild?.getAttribute("width") ||
24
);
const icon = L.divIcon({
html: icon_obj,
className: `border-0 bg-${options.color || "primary"} bg-gradient text-white rounded-circle shadow d-flex justify-content-center align-items-center`,
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
});
return L.marker(coords, { ...options, icon });
}
function createGeoJSONMarker(
marker_elem: HTMLElement,
geojson: string,
options: MarkerStyle,
) {
if (options.color) {
options.color = get_tabler_color(options.color) || options.color;
}
return L.geoJSON(JSON.parse(geojson), {
style: (feature) => {
const properties = feature?.properties;
if (typeof properties !== "object") return options;
return { ...options, ...properties };
},
pointToLayer: (feature, latlng) =>
createMarkerAt(marker_elem, [latlng.lat, latlng.lng], {
...options,
...feature.properties,
}),
});
}
}
const initialized_file_inputs = new WeakSet<HTMLInputElement>();
const initialized_auto_submit_forms = new WeakSet<HTMLFormElement>();
function sqlpage_form(root: InitRoot) {
const file_inputs = select_all(
root,
"input[type=file][data-max-size]",
HTMLInputElement,
);
for (const input of file_inputs) {
if (initialized_file_inputs.has(input)) continue;
initialized_file_inputs.add(input);
const max_size = Number(input.dataset.maxSize);
input.addEventListener("change", () => {
input.classList.remove("is-invalid");
input.setCustomValidity("");
for (const { size } of input.files ?? []) {
if (size > max_size) {
input.classList.add("is-invalid");
return input.setCustomValidity(
`File size must be less than ${max_size / 1000} kB.`,
);
}
}
});
}
const auto_submit_forms = select_all(
root,
"form[data-auto-submit]",
HTMLFormElement,
);
for (const form of auto_submit_forms) {
if (initialized_auto_submit_forms.has(form)) continue;
initialized_auto_submit_forms.add(form);
form.addEventListener("change", () => form.submit());
}
}
function get_tabler_color(name: string) {
return getComputedStyle(document.documentElement).getPropertyValue(
`--tblr-${name}`,
);
}
function load_scripts(root: InitRoot) {
const addjs = select_all(root, "[data-sqlpage-js]", HTMLElement);
const existing_scripts = new Map(
[...document.querySelectorAll("script")].map((s) => [s.src, s]),
);
for (const el of addjs) {
if (!el.dataset.sqlpageJs) continue;
const js = new URL(el.dataset.sqlpageJs, window.location.href).href;
const existing = existing_scripts.get(js);
if (existing) {
existing.sqlpage_init_roots?.add(el);
continue;
}
const script = document.createElement("script");
script.sqlpage_init_roots = new Set([el]);
existing_scripts.set(js, script);
script.src = js;
document.head.appendChild(script);
}
}
function normalize_hash(hash: string | undefined) {
const normalized = hash?.replace(/^#/, "") ?? "";
try {
return decodeURIComponent(normalized);
} catch {
return normalized;
}
}
function open_toasts_for_hash(toasts: Iterable<HTMLElement>) {
const Toast = page_bootstrap().Toast;
const hash = normalize_hash(window.location.hash);
if (!hash) return;
for (const toast of toasts) {
if (normalize_hash(toast.dataset.toastTrigger) === hash) {
const instance = Toast.getOrCreateInstance(toast);
if (!(instance instanceof Toast))
throw new Error("Invalid toast instance");
instance.show();
}
}
}
function restore_focus_after_toast(toast: HTMLElement, container: HTMLElement) {
if (!toast.contains(document.activeElement)) return;
const next_close = container.querySelector<HTMLElement>(
'.toast.show [data-bs-dismiss="toast"]',
);
if (next_close) {
next_close.focus();
return;
}
const main = document.querySelector("main");
if (!main) return;
if (!main.hasAttribute("tabindex")) main.tabIndex = -1;
main.focus({ preventScroll: true });
}
function sqlpage_toast(root: InitRoot) {
const Toast = page_bootstrap().Toast;
const initialized_toasts: HTMLElement[] = [];
const toasts = select_all(root, '[data-pre-init="toast"]', HTMLElement);
for (const toast of toasts) {
const source_container = toast.parentElement;
if (!source_container) continue;
const position = source_container.dataset.sqlpageToastPosition;
let container: HTMLElement | null = document.querySelector(
`.toast-container[data-sqlpage-toast-position="${position}"]:not([data-pre-init])`,
);
if (!container) {
container = source_container;
container.removeAttribute("data-pre-init");
document.body.appendChild(container);
} else {
container.appendChild(toast);
source_container.remove();
}
toast.removeAttribute("data-pre-init");
const instance = Toast.getOrCreateInstance(toast);
if (!(instance instanceof Toast)) throw new Error("Invalid toast instance");
initialized_toasts.push(toast);
toast.addEventListener("hidden.bs.toast", () => {
restore_focus_after_toast(toast, container);
if (toast.dataset.toastTrigger) {
if (
normalize_hash(window.location.hash) ===
normalize_hash(toast.dataset.toastTrigger)
) {
window.history.replaceState(window.history.state, "", "#");
}
return;
}
instance.dispose();
toast.remove();
if (!container.querySelector(".toast")) {
container.remove();
}
});
if (!toast.dataset.toastTrigger) {
instance.show();
}
}
open_toasts_for_hash(initialized_toasts);
}
function sqlpage_modal(root: InitRoot) {
// Bootstrap modals use position: fixed and are documented to live as
// direct children of <body>
// (https://getbootstrap.com/docs/5.3/components/modal/#how-it-works).
// SQLPage renders them inside .page, but Tabler 1.5 sets
// `contain: layout` on .page, which makes fixed positioning relative to
// .page instead of the viewport. The modal then scrolls with the page
// content and ends up behind its own backdrop, so its buttons cannot be
// clicked. Moving modals to <body> keeps them viewport-fixed.
for (const modal of select_all(root, "body .page .modal", HTMLElement)) {
document.body.appendChild(modal);
// The modal leaves the original root; announce its subtree separately so
// every initializer, including later-loaded bundles, can still see it.
modal.dispatchEvent(new CustomEvent("fragment-loaded", { bubbles: true }));
}
}
add_init_fn(sqlpage_table);
add_init_fn(sqlpage_map);
add_init_fn(sqlpage_card);
add_init_fn(sqlpage_form);
add_init_fn(sqlpage_modal);
add_init_fn(load_scripts);
add_init_fn(sqlpage_toast);
window.addEventListener("hashchange", () =>
open_toasts_for_hash(
document.querySelectorAll<HTMLElement>("[data-toast-trigger]"),
),
);
function init_bootstrap_components(root: InitRoot) {
const bootstrap = page_bootstrap();
for (const [selector, Component] of [
['[data-bs-toggle="tooltip"]', bootstrap.Tooltip],
['[data-bs-toggle="popover"]', bootstrap.Popover],
['[data-bs-toggle="dropdown"]', bootstrap.Dropdown],
['[data-bs-ride="carousel"]', bootstrap.Carousel],
] as const) {
for (const el of select_all(root, selector, HTMLElement)) {
Component.getOrCreateInstance(el);
}
}
}
add_init_fn(init_bootstrap_components);
function open_modal_for_hash() {
const hash = window.location.hash.substring(1);
if (!hash) return;
const modal = document.getElementById(hash);
if (!modal?.classList.contains("modal")) return;
const Modal = page_bootstrap().Modal;
const bootstrap_modal = Modal.getOrCreateInstance(modal);
if (!(bootstrap_modal instanceof Modal))
throw new Error("Invalid modal instance");
bootstrap_modal.show();
modal.addEventListener(
"hidden.bs.modal",
() => {
window.history.replaceState(null, "", "#");
},
{ once: true },
);
}
window.addEventListener("hashchange", open_modal_for_hash);
window.addEventListener("DOMContentLoaded", open_modal_for_hash);