xref: /plugin/combo/resources/snippet/js/search.js (revision c3437056399326d621a01da73b649707fbb0ae69)
1window.addEventListener('load', function () {
2
3    let searchBox = document.getElementById("internal-search-box");
4    let autoCompletionUlElement = searchBox.nextElementSibling;
5    const popperInstance = Popper.createPopper(
6        searchBox,
7        autoCompletionUlElement,
8        {
9            modifiers: [
10                {
11                    name: 'offset', // to be below the box-shadow on focus
12                    options: {
13                        offset: [0, 4],
14                    },
15                },
16            ]
17        }
18    );
19
20    searchBox.addEventListener("input", debounce(
21        async function () {
22            await buildAutoCompletionList(this)
23        },
24        500
25    ));
26
27    searchBox.addEventListener("blur", function (event) {
28        let relatedTarget = event.relatedTarget;
29        if (relatedTarget === null) {
30            return;
31        }
32        let form = relatedTarget.closest("form");
33        if (form === null) {
34            return;
35        }
36        // Only if it's not a node of the search form
37        // ie deleting show will prevent click navigation from a page list suggestion
38        if (!form.classList.contains("search")) {
39            autoCompletionUlElement.classList.remove("show");
40        }
41    });
42
43
44let buildAutoCompletionList = async function (searchBox) {
45
46    let searchTerm = searchBox.value;
47    if (searchTerm.length < 3) {
48        return;
49    }
50    let formData = new URLSearchParams();
51    formData.append('call', 'combo-search');
52    formData.append('q', searchTerm);
53    let response = await fetch(DOKU_BASE + 'lib/exe/ajax.php',
54        {
55            method: "POST",
56            body: formData,
57            headers: {
58                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
59            },
60        });
61    let data = await response.json();
62    while (autoCompletionUlElement.firstChild) {
63        autoCompletionUlElement.firstChild.remove()
64    }
65    autoCompletionUlElement.classList.add("show");
66    popperInstance.update();
67    for (let index in data) {
68        if (!data.hasOwnProperty(index)) {
69            continue;
70        }
71        let anchor = data[index];
72        let li = document.createElement("li");
73        li.classList.add("dropdown-item");
74        li.setAttribute("tabindex", "0");
75        li.innerHTML = anchor;
76        autoCompletionUlElement.append(li);
77    }
78
79}
80
81})
82;
83