All files / src/utils dropdown.ts

89.9% Statements 98/109
80.68% Branches 71/88
93.54% Functions 29/31
89.81% Lines 97/108

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2824x                     4x                     60x 60x   60x 60x     48x   48x 48x 48x   48x 30x 30x     18x 12x   12x     12x     6x 6x           177x   177x 165x     543x 543x           177x   354x       354x     878x     878x 12x             878x 878x 450x               543x 9x     543x 543x 180x         73x 31x     73x 71x   71x   71x 71x   71x 48x 48x     23x 20x 20x             119x 119x 630x 119x       119x 119x     119x 119x 119x 119x         1214x 1214x       233x 202x   31x                     198x       67x   67x 5x   62x     67x       6x 6x   6x 3x   3x     6x               39x 39x         1511x       39x       1406x 42x 42x                     60x 60x     58x 58x 58x 58x     60x   60x                                                   4x 167x 167x 167x            
import { log } from "../api/client"
import { SearchAutocompleteOptions } from "../autocomplete"
 
type OnClickBindings<State> = {
    [key: string]: (obj: {
        data: string | undefined
        el: HTMLElement
        update: (state: State) => void
    }) => unknown
}
 
export function createDropdown<State>(
    container: HTMLElement,
    initialState: PromiseLike<State>,
    render: (container: HTMLElement, state: State) => void | PromiseLike<void>,
    submit: (
        inputValue: string,
        options?: SearchAutocompleteOptions
    ) => unknown,
    updateInput: (inputValue: string) => void,
    onClickBindings?: OnClickBindings<State>
) {
    let elements: HTMLElement[] = []
    let unbindCallbacks: Array<() => void> = []
 
    let isEmpty: boolean = true
    let selectedIndex: number = -1
 
    function handleElementSubmit(el: HTMLElement): void {
        const hit = el?.dataset?.nsHit
 
        if (hit) {
            const parsedHit = parseHit(hit)
            hide()
 
            if (parsedHit?.item) {
                submit(parsedHit.item)
                return
            }
 
            if (parsedHit?.keyword) {
                submit(parsedHit.keyword, { redirect: !!parsedHit?._redirect, isKeyword: true })
 
                Iif (parsedHit?._redirect) {
                    location.href = parsedHit._redirect
                }
                return
            }
 
            if (parsedHit?.url) {
                location.href = parsedHit.url
            }
        }
    }
 
    function loadElements() {
        isEmpty = !container.innerHTML.trim()
 
        if (!isEmpty) {
            elements = Array.from<HTMLElement>(
                container.querySelectorAll("[data-ns-hit]")
            ).map(el => {
                bindElementSubmit(el)
                return el
            })
        }
    }
 
    function bindDataCallbacks() {
        Object.entries(onClickBindings ?? {}).map(([key, callback]) => {
            // Convert camelCase to kebab-case
            const dataKey = `[data-ns-${key
                .replace(/([A-Z])/g, "-$1")
                .toLowerCase()}]`
 
            Array.from<HTMLElement>(container.querySelectorAll(dataKey)).map(
                el => {
                    const data =
                        el?.dataset?.[
                            `ns${key.charAt(0).toUpperCase() + key.slice(1)}`
                        ]
                    const onClick = () => {
                        callback({
                            data,
                            el,
                            update,
                        })
                    }
 
                    el.addEventListener("click", onClick)
                    unbindCallbacks.push(() => {
                        el.removeEventListener("click", onClick)
                    })
                }
            )
        })
    }
 
    function bindElementSubmit(el: HTMLElement) {
        const onSubmit = () => {
            handleElementSubmit(el)
        }
 
        el.addEventListener("click", onSubmit)
        unbindCallbacks.push(() => {
            el.removeEventListener("click", onSubmit)
        })
    }
 
    function highlight(index: number, prevIndex?: number) {
        if (typeof prevIndex === "number" && elements[prevIndex]) {
            elements[prevIndex].classList.remove("selected")
        }
 
        if (typeof index === "number" && elements[index]) {
            elements[index]?.classList.add("selected")
 
            const hit = elements[index]?.dataset?.nsHit
 
            if (hit) {
                const parsedHit = parseHit(hit)
 
                if (parsedHit.item) {
                    updateInput(parsedHit.item)
                    return
                }
 
                if (parsedHit.keyword) {
                    updateInput(parsedHit.keyword)
                    return
                }
            }
        }
    }
 
    function dispose() {
        resetHighlight()
        elements = []
        unbindCallbacks.forEach(v => v())
        unbindCallbacks = []
    }
 
    async function update(state: State) {
        dispose()
        await Promise.resolve(render(container, state))
 
        // Without setTimeout React does not have committed DOM changes yet, so we don't have the correct elements.
        setTimeout(() => {
            loadElements()
            bindDataCallbacks()
            show()
        }, 0)
    }
 
    function hide() {
        resetHighlight()
        container.style.display = "none"
    }
 
    function show() {
        if (!isEmpty) {
            container.style.display = ""
        } else {
            hide()
        }
    }
 
    function clear() {
        dispose()
        isEmpty = true
        hide()
    }
 
    function isOpen() {
        return container.style.display !== "none"
    }
 
    function goDown() {
        let prevIndex = selectedIndex
 
        if (selectedIndex === elements.length - 1) {
            selectedIndex = 0
        } else {
            prevIndex = selectedIndex++
        }
 
        highlight(selectedIndex, prevIndex)
    }
 
    function goUp() {
        if (hasHighlight()) {
            let prevIndex = selectedIndex
 
            if (selectedIndex === 0) {
                selectedIndex = elements.length - 1
            } else {
                prevIndex = selectedIndex--
            }
 
            highlight(selectedIndex, prevIndex)
        } else E{
            selectedIndex = elements.length - 1
            highlight(selectedIndex)
        }
    }
 
    function handleSubmit() {
        if (isOpen() && hasHighlight() && elements[selectedIndex]) {
            handleElementSubmit(elements[selectedIndex])
        }
    }
 
    function hasHighlight() {
        return selectedIndex > -1
    }
 
    function getHighlight() {
        return elements[selectedIndex]
    }
 
    function resetHighlight() {
        if (hasHighlight()) {
            elements[selectedIndex]?.classList.remove("selected")
            selectedIndex = -1
        }
    }
 
    function destroy() {
        dispose()
        isEmpty = true
        container.innerHTML = ""
    }
 
    async function init() {
        const state = await Promise.resolve(initialState)
        await Promise.resolve(render(container, state))
 
        // Without setTimeout React does not have committed DOM changes yet, so we don't have the correct elements.
        setTimeout(() => {
            loadElements()
            bindDataCallbacks()
            hide()
        }, 0)
    }
    init()
 
    return {
        update,
        clear,
        isOpen,
        goDown,
        goUp,
        handleSubmit,
        destroy,
        show,
        hide,
        resetHighlight,
        hasHighlight,
        getHighlight,
        container,
    }
}
 
export type Dropdown<T> = ReturnType<typeof createDropdown<T>>
 
interface Hit {
    item?: string
    keyword?: string
    url?: string
    _redirect?: string
}
 
export function parseHit(hit: string): Hit {
    try {
        const parsedHit: Hit | undefined | null = JSON.parse(hit)
        return parsedHit ?? {}
    } catch (error) {
        log("Could not parse hit", error, "warn")
        return {}
    }
}