////
// We try to keep the command textbox focused at all times.

import { cmdInput } from "./dom"

export function initFocus() {
    window.addEventListener("click", focusHandler)
    focusInput()
}

export function focusInput() {
    cmdInput.focus()
}

// clicking anywhere outside of a link should focus the prompt, unless the user is
// selecting text or focusing an input
export function focusHandler(e: MouseEvent) {
    const target = e.target

    // who knows where they clicked... just focus the textbox
    if (!(target instanceof HTMLElement)) {
        focusInput()
        return
    }

    if (["INPUT", "TEXTAREA", "CANVAS", "A"].includes(target.tagName))
        return false

    const selection = window.getSelection() || ""
    if (selection.toString() === "")
        focusInput()

    e.preventDefault()
}
