combobox-input-new.js

/** @module form-controls **/

import van from 'vanjs-core';
import selectOptions from './select-options';
import { Button, Input, typeMap } from './form-controls.js';

typeMap.set('combobox', ComboboxInput);


/**
 * Create a searchable input control with dropdown options.
 * Dropdown behavior is implemented by the component and does not require Bootstrap JavaScript or Popper.
 * @param {object} props
 * @property {SelectOption} options 
 * @property {string|object} style
 * @property {string} bsSize 
 * @property {boolean} disabled
 * @property {function} onitemclick - onitemclick(value,selItem)
 * <br>&nbsp;&nbsp;vaue = selItem.value
 * <br>&nbsp;&nbsp;selItem = [text,value] 
 * <br>&nbsp;&nbsp;returns new value
 * @property {function} afteritemclick - afteritemclick(event)
 * @property {object} ...inputProps other props
 * @returns {HTMLElement} input control with dropdown options
 */

export function ComboboxInput(props) {
    const { div, ul, li } = van.tags;
    var {
        options = [],
        style,
        bsSize,
        onitemclick,
        afteritemclick,
        disabled,
        ...inputProps                                               // name, value, oninput ...
    } = props;

    options = selectOptions(options);

    var dvalue = van.state(valueToDisplay(options, van.val(props.value)));  // declare display value as van.state
    const isOpen = van.state(false);
    const activeIndex = van.state(-1);
    const listId = `${props.id || 'combobox'}-${Math.random().toString(36).substring(2, 9)}-options`;

    function displayToValue(options, value) {
        let oItem = options.find(o => o.children === value);      // lookup in options to get associated value
        if (oItem) value = oItem.value;                             // value fount, otherwise it's still the caption
        return value;
    }

    function valueToDisplay(options, value) {
        var oItem = options.find(o => o.value === value);             // lookup in options to get associated display value
        if (oItem) value = oItem.children;
        return value;
    }

    function selectClick(value) {
        let { name, type } = props;
        value = displayToValue(options, value);

        if (onitemclick) {
            let selItem = options.find(o => o.value === value);
            let newValue = onitemclick(value, selItem);
            if (newValue !== undefined) value = newValue;
        }

        dvalue.val = valueToDisplay(options, value);
        isOpen.val = false;
        activeIndex.val = -1;

        props.oninput && props.oninput({
            target: { name, value, type }
        });

        props.afteritemclick && props.afteritemclick({
            target: { name, value, type }
        });

        return false;
    };


    const menuStyle = 'top:100%;left:0;right:0;max-height:16rem;overflow-y:auto;cursor:default;'
    // 'position:absolute; top:100%; left:0; right:0; z-index:1000;  max-height: 16rem; overflow-y:auto; margin:0.125rem 0 0;'
    //   + 'padding: 0.25rem 0; list-style: none;'
    //   + ' backgroundColor: #fff; border: 1px solid #ced4da; border-radius: 0.375rem;'
    //   + 'box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);'


    return div({
        style: van.val(props.style),
        class: () => {
            let res = 'input-group';
            if (van.val(bsSize)) res += ' input-group-' + van.val(bsSize);
            if (van.val(props.class)) res += ' ' + van.val(props.class);
            return res;
        },
        onfocusout: event => {
            if (!event.currentTarget.contains(event.relatedTarget)) {
                isOpen.val = false;
                activeIndex.val = -1;
            }
        }
    },

        Input({
            ...inputProps,
            bsSize,
            disabled,
            value: dvalue,
            role: 'combobox',
            'aria-autocomplete': 'list',
            'aria-haspopup': 'listbox',
            'aria-controls': listId,
            'aria-expanded': () => isOpen.val,
            'aria-activedescendant': () => activeIndex.val >= 0
                ? `${listId}-${activeIndex.val}`
                : undefined,
            onfocus: event => {
                inputProps.onfocus && inputProps.onfocus(event);
            },
            oninput: event => {
                let { value } = event.target;
                dvalue.val = value;
                activeIndex.val = -1;
                if (inputProps.oninput) inputProps.oninput({
                    target: {
                        value: displayToValue(options, value),
                        name: props.name,
                        type: props.type
                    }
                });
            },
            onkeydown: event => {
                if (options.length && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
                    event.preventDefault();
                    if (!isOpen.val) isOpen.val = true;
                    const step = event.key === 'ArrowDown' ? 1 : -1;
                    const current = activeIndex.val;
                    activeIndex.val = current < 0
                        ? (step > 0 ? 0 : options.length - 1)
                        : (current + step + options.length) % options.length;
                } else if (options.length && event.key === 'Enter' && isOpen.val && activeIndex.val >= 0) {
                    event.preventDefault();
                    selectClick(options[activeIndex.val].children);
                } else if (event.key === 'Escape' && isOpen.val) {
                    event.preventDefault();
                    isOpen.val = false;
                    activeIndex.val = -1;
                }
                inputProps.onkeydown && inputProps.onkeydown(event);
            },
        }),

        ul({
            id: listId,
            role: 'listbox',
            class: 'dropdown-menu',
            style: () => (menuStyle + `display: ${isOpen.val ? 'block' : 'none'};`),
        },
            options.map((o, index) => li({
                id: `${listId}-${index}`,
                role: 'option',
                'aria-selected': () => activeIndex.val === index,
                class: 'dropdown-item',
                style: () => ({
                    display: 'block',
                    width: '100%',
                    padding: '0.25rem 0.75rem',
                    color: '#212529',
                    backgroundColor: activeIndex.val === index ? '#e9ecef' : '#fff',
                    cursor: 'pointer',
                }),
                onmousedown: event => event.preventDefault(),
                onclick: () => selectClick(o.children),
            }, o.children))
        ),
        Button({
            disabled,
            'aria-label': 'Show options',
            'aria-haspopup': 'listbox',
            'aria-controls': listId,
            'aria-expanded': () => isOpen.val,
            onclick: () => {
                isOpen.val = !isOpen.val;
                activeIndex.val = -1;
            },
        }, '▾'),
    )
}