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

1 import {getById, writeError, 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 const brp = await fetch("/brp.json")
20 const cdata = await brp.json()
21
22 dactal.data = {
23 personen: cdata
24 }
25
26 input.onkeydown = async (e) => {
27 if (e.key === "Enter" && !e.shiftKey) {
28 e.preventDefault()
29
30 try {
31 let result = await dactal.query(input.value)
32
33 const results = getById("results")
34 results.replaceChildren(renderValue(result.slice(0, 100)))
35
36 if (result.length > 100) {
37 results.appendChild(div(span(`Not showing ${result.length - 100} more results.`)))
38 }
39 } catch (e) {
40 writeError(e.message)
41 }
42 }
43 }
44
45 input.dispatchEvent(enterEvent)
46 }
47
48 function renderValue(obj) {
49 if (Array.isArray(obj)) {
50 return h("ol",
51 ...obj.map((item) => h("li", renderValue(item)))
52 )
53 } else if (typeof obj === "object") {
54 return h("ul",
55 ...Object.entries(obj).map(([name, item]) =>
56 addClass(h("li",
57 addClass(span(name), "name"),
58 span(" "),
59 renderValue(item)),
60 "dash")))
61 } else if (typeof obj === "boolean") {
62 return addClass(span(obj), obj ? "json-true" : "json-false")
63 } else if (typeof obj === "number") {
64 return addClass(span(obj), "json-number")
65 } else if (typeof obj === "string") {
66 return span(obj)
67 }
68 }