Blog/Components/Pages/Query.razor.js 1.9 K · 73 lines · raw · history

1 import {getById, writeError, writeDebug, h, span, addClass, div} from '/common.module.js'
2 import {DACTAL} from "/dactal.js"
3
4 const enterEvent = new KeyboardEvent('keydown', {
5 key: 'Enter',
6 code: 'Enter',
7 keyCode: 13,
8 which: 13,
9 bubbles: true,
10 cancelable: true
11 });
12
13 let dactal
14
15 export async function onLoad() {
16 const input = getById("input")
17 dactal = new DACTAL()
18
19 fetch("/brp.json").then(async res => {
20 const cdata = await res.json()
21 dactal.load(cdata, "personen")
22 writeDebug("Loaded brp data")
23 await runQuery(input.value)
24 })
25
26 input.onkeydown = async (e) => {
27 if (e.key === "Enter" && !e.shiftKey) {
28 e.preventDefault()
29 await runQuery(input.value)
30 }
31 }
32
33 input.dispatchEvent(enterEvent)
34 }
35
36 async function runQuery(query) {
37 const results = getById("results")
38
39 try {
40 let result = await dactal.query(query)
41
42 results.replaceChildren(renderValue(result.slice(0, 100)))
43
44 if (result.length > 100) {
45 results.appendChild(div(span(`Not showing ${result.length - 100} more results.`)))
46 }
47 } catch (e) {
48 writeError(e.message)
49 results.replaceChildren()
50 }
51 }
52
53 function renderValue(obj) {
54 if (Array.isArray(obj)) {
55 return h("ol",
56 ...obj.map((item) => h("li", renderValue(item)))
57 )
58 } else if (typeof obj === "object") {
59 return h("ul",
60 ...Object.entries(obj).map(([name, item]) =>
61 addClass(h("li",
62 addClass(span(name), "name"),
63 span(" "),
64 renderValue(item)),
65 "dash")))
66 } else if (typeof obj === "boolean") {
67 return addClass(span(obj), obj ? "json-true" : "json-false")
68 } else if (typeof obj === "number") {
69 return addClass(span(obj), "json-number")
70 } else if (typeof obj === "string") {
71 return span(obj)
72 }
73 }